target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
src/main/jsx/components/lib/AutoRefreshComponent.js
dimacus/DotCi
import React from 'react'; export const Job = component(); export const Build = component(); function component(){ return React.createClass({ componentDidMount(){ this.refreshTimer = setInterval(this.props.refreshFunction, this.props.refreshInterval); }, componentWillUnmount(){ clearInterval(this.refreshTimer); }, render(){ return this.props.component; } }); }
src/routes/cmd/index.js
geoffreyfloyd/op
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Cmd from './Cmd'; export const path = '/cmd'; export const action = async (state) => { const title = 'Command Prompt'; state.context.onSetTitle(title); return <Cmd title={title} />; };
src/views/Card/CardContent.js
aabustamante/Semantic-UI-React
import cx from 'classnames' import _ from 'lodash' import PropTypes from 'prop-types' import React from 'react' import { createShorthand, customPropTypes, getElementType, getUnhandledProps, META, useKeyOnly, } from '../../lib' import CardDescription from './CardDescription' import CardHeader from './CardHeader' import CardMeta from './CardMeta' /** * A card can contain blocks of content or extra content meant to be formatted separately from the main content. */ function CardContent(props) { const { children, className, description, extra, header, meta, } = props const classes = cx( className, useKeyOnly(extra, 'extra'), 'content', ) const rest = getUnhandledProps(CardContent, props) const ElementType = getElementType(CardContent, props) if (!_.isNil(children)) { return <ElementType {...rest} className={classes}>{children}</ElementType> } return ( <ElementType {...rest} className={classes}> {createShorthand(CardHeader, val => ({ content: val }), header)} {createShorthand(CardMeta, val => ({ content: val }), meta)} {createShorthand(CardDescription, val => ({ content: val }), description)} </ElementType> ) } CardContent._meta = { name: 'CardContent', parent: 'Card', type: META.TYPES.VIEW, } CardContent.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for CardDescription. */ description: customPropTypes.itemShorthand, /** A card can contain extra content meant to be formatted separately from the main content. */ extra: PropTypes.bool, /** Shorthand for CardHeader. */ header: customPropTypes.itemShorthand, /** Shorthand for CardMeta. */ meta: customPropTypes.itemShorthand, } export default CardContent
ajax/libs/rxjs/2.4.3/rx.compat.js
Sneezry/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 = (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; }()); 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 hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // 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; }; } // Fix for Tessel if (!Object.prototype.propertyIsEnumerable) { Object.prototype.propertyIsEnumerable = function (key) { for (var k in this) { if (k === key) { return true; } } return false; }; } if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; this.items[this.length] = undefined; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed && !this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.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](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 NotSupportedError(); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); if (!item.isCancelled()) { !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; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); 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 NotSupportedError(); } 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, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; var onGlobalPostMessage = function (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); })(); var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept(onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString() { return 'OnNext(' + this.value + ')'; } return function (value) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.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) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; 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); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.onCompleted(); } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, function (e) { observer.onError(e); }, function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(o); }, this); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, 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); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; 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(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); /*try { var result = this.selector(x, this.i++, this.source); } catch (e) { return this.observer.onError(e); } this.observer.onNext(result);*/ }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, source).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate(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); }; /** * 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)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
src/components/MembersPage.js
KingCountySAR/database-frontend
import React from 'react'; import PropTypes from 'prop-types'; import { Card, CardHeader } from 'material-ui/Card'; import MembersTable from './MembersTable'; import { memberProp } from '../propTypes'; import Page from './Page'; const MembersPage = ({ members }) => ( <Page> <Card> <CardHeader title="Members" subtitle="List of Members in SAR" /> <MembersTable members={members} /> </Card> </Page> ); MembersPage.propTypes = { members: PropTypes.arrayOf(memberProp), }; MembersPage.defaultProps = { members: [], }; export default MembersPage;
Demo/src/components/VehicleDetail.js
bspaulding/presentation-react-router-4-universal-links
import React, { Component } from 'react'; import { View } from 'react-native'; import { getVehicle } from '../api/SWApi'; import Loading from './Loading'; import Text from './Text'; import Heading from './Heading'; import SectionHeading from './SectionHeading'; import LazyLinkList, { LazyLink } from './LazyLinkList'; import { Stats, Stat } from './Stat'; class SpeciesDetail extends Component { constructor() { super(); this.state = { loading: true }; } async componentDidMount() { const { id } = this.props.match.params; const vehicle = await getVehicle(id); this.setState({ vehicle, loading: false }); } render() { const { loading, vehicle } = this.state; if (loading) { return <Loading/>; } return ( <View> <Heading>{vehicle.name}</Heading> <Stats> <Stat label="Cargo Capacity">{vehicle.cargo_capacity}</Stat> <Stat label="Consumables">{vehicle.consumables}</Stat> <Stat label="Cost (credits)">{vehicle.cost_in_credits}</Stat> <Stat label="Crew">{vehicle.crew}</Stat> <Stat label="Length">{vehicle.length}</Stat> <Stat label="Manufacturer">{vehicle.manufacturer}</Stat> <Stat label="Speed (Max Atmos.)">{vehicle.max_atmosphering_speed}</Stat> <Stat label="Model">{vehicle.model}</Stat> <Stat label="Passengers">{vehicle.passengers}</Stat> <Stat label="Class">{vehicle.vehicle_class}</Stat> </Stats> <SectionHeading>Films ({vehicle.films.length})</SectionHeading> <LazyLinkList source={vehicle} association="films"/> <SectionHeading>Pilots ({vehicle.pilots.length})</SectionHeading> <LazyLinkList source={vehicle} accessor="pilots" association="people"/> </View> ); } } export default SpeciesDetail;
src/Card.js
jareth/react-materialize
import React from 'react'; import cx from 'classnames'; import Icon from './Icon'; class Card extends React.Component { constructor(props) { super(props); this.renderTitle = this.renderTitle.bind(this); } render() { let {title, header, className, textClassName, actions, reveal, children, ...props} = this.props; let classes = { card: true }; return ( <div {...props} className={cx(className, classes)} > {header} <div className={cx('card-content', textClassName)}> {title ? this.renderTitle(title, reveal) : null} <p>{children}</p> </div> {this.renderReveal(title, reveal)} {actions ? this.renderAction(actions) : null} </div> ); } renderTitle(title, reveal) { let revealIcon = null; if (reveal) { revealIcon = <Icon right>more_vert</Icon>; } let classes = { 'card-title': true, 'grey-text': true, 'text-darken-4': true, 'activator': reveal }; return ( <span className={cx(classes)}> {title} {revealIcon} </span> ); } renderReveal(title, reveal) { return ( <div className="card-reveal"> <span className="card-title grey-text text-darken-4">{title}<Icon right>close</Icon></span> {reveal} </div> ); } renderAction(actions) { return <div className='card-action'> {actions} </div>; } } Card.propTypes = { title: React.PropTypes.string, textClassName: React.PropTypes.string, reveal: React.PropTypes.element, header: React.PropTypes.element, // The buttons to be displayed at the action area actions: React.PropTypes.arrayOf(React.PropTypes.element), } export default Card;
admin/client/App/shared/Popout/PopoutFooter.js
xyzteam2016/keystone
/** * Render a footer for a popout */ import React from 'react'; const BUTTON_BASE_CLASSNAME = 'Popout__footer__button Popout__footer__button--'; const PopoutFooter = React.createClass({ displayName: 'PopoutFooter', propTypes: { children: React.PropTypes.node, primaryButtonAction: React.PropTypes.func, primaryButtonIsSubmit: React.PropTypes.bool, primaryButtonLabel: React.PropTypes.string, secondaryButtonAction: React.PropTypes.func, secondaryButtonLabel: React.PropTypes.string, }, // Render a primary button renderPrimaryButton () { if (!this.props.primaryButtonLabel) return null; return ( <button type={this.props.primaryButtonIsSubmit ? 'submit' : 'button'} className={BUTTON_BASE_CLASSNAME + 'primary'} onClick={this.props.primaryButtonAction} > {this.props.primaryButtonLabel} </button> ); }, // Render a secondary button renderSecondaryButton () { if (!this.props.secondaryButtonAction || !this.props.secondaryButtonLabel) return null; return ( <button type="button" className={BUTTON_BASE_CLASSNAME + 'secondary'} onClick={this.props.secondaryButtonAction} > {this.props.secondaryButtonLabel} </button> ); }, render () { return ( <div className="Popout__footer"> {this.renderPrimaryButton()} {this.renderSecondaryButton()} {this.props.children} </div> ); }, }); module.exports = PopoutFooter;
ajax/libs/js-data/2.0.0-beta.5/js-data-debug.min.js
dhenson02/cdnjs
/*! * js-data * @version 2.0.0-beta.5 - Homepage <http://www.js-data.io/> * @author Jason Dobry <jason.dobry@gmail.com> * @copyright (c) 2014-2015 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Robust framework-agnostic data store. */ (function webpackUniversalModuleDefinition(a,b){if(typeof exports==="object"&&typeof module==="object"){module.exports=b()}else{if(typeof define==="function"&&define.amd){define(b)}else{if(typeof exports==="object"){exports.JSData=b()}else{a.JSData=b()}}}})(this,function(){return(function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.loaded=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)})([function(module,exports,__webpack_require__){var _DS=__webpack_require__(1);var _DSUtils=__webpack_require__(2);var _DSErrors=__webpack_require__(3);module.exports={DS:_DS["default"],DSUtils:_DSUtils["default"],DSErrors:_DSErrors["default"],createStore:function createStore(options){return new _DS["default"](options)},version:{full:"2.0.0-beta.5",major:parseInt("2",10),minor:parseInt("0",10),patch:parseInt("0",10),alpha:true?"false":false,beta:true?"5":false}}},function(module,exports,__webpack_require__){var _classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var _createClass=(function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value" in descriptor){descriptor.writable=true}Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps){defineProperties(Constructor.prototype,protoProps)}if(staticProps){defineProperties(Constructor,staticProps)}return Constructor}})();var _DSUtils=__webpack_require__(2);var _DSErrors=__webpack_require__(3);var _syncMethods=__webpack_require__(4);var _asyncMethods=__webpack_require__(5);function lifecycleNoopCb(resource,attrs,cb){cb(null,attrs)}function lifecycleNoop(resource,attrs){return attrs}function compare(_x,_x2,_x3,_x4){var _again=true;_function:while(_again){def=cA=cB=undefined;_again=false;var orderBy=_x,index=_x2,a=_x3,b=_x4;var def=orderBy[index];var cA=_DSUtils["default"].get(a,def[0]),cB=_DSUtils["default"].get(b,def[0]);if(_DSUtils["default"]._s(cA)){cA=_DSUtils["default"].upperCase(cA)}if(_DSUtils["default"]._s(cB)){cB=_DSUtils["default"].upperCase(cB)}if(def[1]==="DESC"){if(cB<cA){return -1}else{if(cB>cA){return 1}else{if(index<orderBy.length-1){_x=orderBy;_x2=index+1;_x3=a;_x4=b;_again=true;continue _function}else{return 0}}}}else{if(cA<cB){return -1}else{if(cA>cB){return 1}else{if(index<orderBy.length-1){_x=orderBy;_x2=index+1;_x3=a;_x4=b;_again=true;continue _function}else{return 0}}}}}}var Defaults=(function(){function Defaults(){_classCallCheck(this,Defaults)}_createClass(Defaults,[{key:"errorFn",value:function errorFn(a,b){if(this.error&&typeof this.error==="function"){try{if(typeof a==="string"){throw new Error(a)}else{throw a}}catch(err){a=err}this.error(this.name||null,a||null,b||null)}}}]);return Defaults})();var defaultsPrototype=Defaults.prototype;defaultsPrototype.actions={};defaultsPrototype.afterCreate=lifecycleNoopCb;defaultsPrototype.afterCreateCollection=lifecycleNoop;defaultsPrototype.afterCreateInstance=lifecycleNoop;defaultsPrototype.afterDestroy=lifecycleNoopCb;defaultsPrototype.afterEject=lifecycleNoop;defaultsPrototype.afterInject=lifecycleNoop;defaultsPrototype.afterReap=lifecycleNoop;defaultsPrototype.afterUpdate=lifecycleNoopCb;defaultsPrototype.afterValidate=lifecycleNoopCb;defaultsPrototype.allowSimpleWhere=true;defaultsPrototype.basePath="";defaultsPrototype.beforeCreate=lifecycleNoopCb;defaultsPrototype.beforeCreateCollection=lifecycleNoop;defaultsPrototype.beforeCreateInstance=lifecycleNoop;defaultsPrototype.beforeDestroy=lifecycleNoopCb;defaultsPrototype.beforeEject=lifecycleNoop;defaultsPrototype.beforeInject=lifecycleNoop;defaultsPrototype.beforeReap=lifecycleNoop;defaultsPrototype.beforeUpdate=lifecycleNoopCb;defaultsPrototype.beforeValidate=lifecycleNoopCb;defaultsPrototype.bypassCache=false;defaultsPrototype.cacheResponse=!!_DSUtils["default"].w;defaultsPrototype.clearEmptyQueries=true;defaultsPrototype.computed={};defaultsPrototype.defaultAdapter="http";defaultsPrototype.debug=true;defaultsPrototype.defaultValues={};defaultsPrototype.eagerEject=false;defaultsPrototype.eagerInject=false;defaultsPrototype.endpoint="";defaultsPrototype.error=console?function(a,b,c){return console[typeof console.error==="function"?"error":"log"](a,b,c)}:false;defaultsPrototype.fallbackAdapters=["http"];defaultsPrototype.findStrictCache=false;defaultsPrototype.idAttribute="id";defaultsPrototype.ignoredChanges=[/\$/];defaultsPrototype.ignoreMissing=false;defaultsPrototype.keepChangeHistory=false;defaultsPrototype.linkRelations=true;defaultsPrototype.log=console?function(a,b,c,d,e){return console[typeof console.info==="function"?"info":"log"](a,b,c,d,e)}:false;defaultsPrototype.logFn=function(a,b,c,d){var _this=this;if(_this.debug&&_this.log&&typeof _this.log==="function"){_this.log(_this.name||null,a||null,b||null,c||null,d||null)}};defaultsPrototype.maxAge=false;defaultsPrototype.methods={};defaultsPrototype.notify=!!_DSUtils["default"].w;defaultsPrototype.reapAction=!!_DSUtils["default"].w?"inject":"none";defaultsPrototype.reapInterval=!!_DSUtils["default"].w?30000:false;defaultsPrototype.relationsEnumerable=false;defaultsPrototype.resetHistoryOnInject=true;defaultsPrototype.strategy="single";defaultsPrototype.upsert=!!_DSUtils["default"].w;defaultsPrototype.useClass=true;defaultsPrototype.useFilter=false;defaultsPrototype.validate=lifecycleNoopCb;defaultsPrototype.defaultFilter=function(collection,resourceName,params,options){var filtered=collection;var where=null;var reserved={skip:"",offset:"",where:"",limit:"",orderBy:"",sort:""};params=params||{};options=options||{};if(_DSUtils["default"]._o(params.where)){where=params.where}else{where={}}if(options.allowSimpleWhere){_DSUtils["default"].forOwn(params,function(value,key){if(!(key in reserved)&&!(key in where)){where[key]={"==":value}}})}if(_DSUtils["default"].isEmpty(where)){where=null}if(where){filtered=_DSUtils["default"].filter(filtered,function(attrs){var first=true;var keep=true;_DSUtils["default"].forOwn(where,function(clause,field){if(_DSUtils["default"]._s(clause)){clause={"===":clause}}else{if(_DSUtils["default"]._n(clause)||_DSUtils["default"].isBoolean(clause)){clause={"==":clause}}}if(_DSUtils["default"]._o(clause)){_DSUtils["default"].forOwn(clause,function(term,op){var expr=undefined;var isOr=op[0]==="|";var val=_DSUtils["default"].get(attrs,field);op=isOr?op.substr(1):op;if(op==="=="){expr=val==term}else{if(op==="==="){expr=val===term}else{if(op==="!="){expr=val!=term}else{if(op==="!=="){expr=val!==term}else{if(op===">"){expr=val>term}else{if(op===">="){expr=val>=term}else{if(op==="<"){expr=val<term}else{if(op==="<="){expr=val<=term}else{if(op==="isectEmpty"){expr=!_DSUtils["default"].intersection(val||[],term||[]).length}else{if(op==="isectNotEmpty"){expr=_DSUtils["default"].intersection(val||[],term||[]).length}else{if(op==="in"){if(_DSUtils["default"]._s(term)){expr=term.indexOf(val)!==-1}else{expr=_DSUtils["default"].contains(term,val)}}else{if(op==="notIn"){if(_DSUtils["default"]._s(term)){expr=term.indexOf(val)===-1}else{expr=!_DSUtils["default"].contains(term,val)}}else{if(op==="contains"){if(_DSUtils["default"]._s(val)){expr=val.indexOf(term)!==-1}else{expr=_DSUtils["default"].contains(val,term)}}else{if(op==="notContains"){if(_DSUtils["default"]._s(val)){expr=val.indexOf(term)===-1}else{expr=!_DSUtils["default"].contains(val,term)}}}}}}}}}}}}}}}if(expr!==undefined){keep=first?expr:isOr?keep||expr:keep&&expr}first=false})}});return keep})}var orderBy=null;if(_DSUtils["default"]._s(params.orderBy)){orderBy=[[params.orderBy,"ASC"]]}else{if(_DSUtils["default"]._a(params.orderBy)){orderBy=params.orderBy}}if(!orderBy&&_DSUtils["default"]._s(params.sort)){orderBy=[[params.sort,"ASC"]]}else{if(!orderBy&&_DSUtils["default"]._a(params.sort)){orderBy=params.sort}}if(orderBy){(function(){var index=0;_DSUtils["default"].forEach(orderBy,function(def,i){if(_DSUtils["default"]._s(def)){orderBy[i]=[def,"ASC"]}else{if(!_DSUtils["default"]._a(def)){throw new _DSErrors["default"].IA('DS.filter("'+resourceName+'"[, params][, options]): '+_DSUtils["default"].toJson(def)+": Must be a string or an array!",{params:{"orderBy[i]":{actual:typeof def,expected:"string|array"}}})}}});filtered=_DSUtils["default"].sort(filtered,function(a,b){return compare(orderBy,index,a,b)})})()}var limit=_DSUtils["default"]._n(params.limit)?params.limit:null;var skip=null;if(_DSUtils["default"]._n(params.skip)){skip=params.skip}else{if(_DSUtils["default"]._n(params.offset)){skip=params.offset}}if(limit&&skip){filtered=_DSUtils["default"].slice(filtered,skip,Math.min(filtered.length,skip+limit))}else{if(_DSUtils["default"]._n(limit)){filtered=_DSUtils["default"].slice(filtered,0,Math.min(filtered.length,limit))}else{if(_DSUtils["default"]._n(skip)){if(skip<filtered.length){filtered=_DSUtils["default"].slice(filtered,skip)}else{filtered=[]}}}}return filtered};var DS=(function(){function DS(options){_classCallCheck(this,DS);var _this=this;options=options||{};_this.store={};_this.s=_this.store;_this.definitions={};_this.defs=_this.definitions;_this.adapters={};_this.defaults=new Defaults();_this.observe=_DSUtils["default"].observe;_DSUtils["default"].forOwn(options,function(v,k){_this.defaults[k]=v});_this.defaults.logFn("new data store created",_this.defaults)}_createClass(DS,[{key:"getAdapter",value:function getAdapter(options){var errorIfNotExist=false;options=options||{};this.defaults.logFn("getAdapter",options);if(_DSUtils["default"]._s(options)){errorIfNotExist=true;options={adapter:options}}var adapter=this.adapters[options.adapter];if(adapter){return adapter}else{if(errorIfNotExist){throw new Error(""+options.adapter+" is not a registered adapter!")}else{return this.adapters[options.defaultAdapter]}}}},{key:"registerAdapter",value:function registerAdapter(name,Adapter,options){var _this=this;options=options||{};_this.defaults.logFn("registerAdapter",name,Adapter,options);if(_DSUtils["default"].isFunction(Adapter)){_this.adapters[name]=new Adapter(options)}else{_this.adapters[name]=Adapter}if(options["default"]){_this.defaults.defaultAdapter=name}_this.defaults.logFn("default adapter is "+_this.defaults.defaultAdapter)}},{key:"is",value:function is(resourceName,instance){var definition=this.defs[resourceName];if(!definition){throw new _DSErrors["default"].NER(resourceName)}return instance instanceof definition[definition["class"]]}}]);return DS})();var dsPrototype=DS.prototype;dsPrototype.getAdapter.shorthand=false;dsPrototype.registerAdapter.shorthand=false;dsPrototype.errors=_DSErrors["default"];dsPrototype.utils=_DSUtils["default"];_DSUtils["default"].deepMixIn(dsPrototype,_syncMethods["default"]);_DSUtils["default"].deepMixIn(dsPrototype,_asyncMethods["default"]);exports["default"]=DS},function(module,exports,__webpack_require__){var _defineProperty=function(obj,key,value){return Object.defineProperty(obj,key,{value:value,enumerable:key==null||typeof Symbol=="undefined"||key.constructor!==Symbol,configurable:true,writable:true})};var _DSErrors=__webpack_require__(3);var BinaryHeap=__webpack_require__(7);var forEach=__webpack_require__(8);var slice=__webpack_require__(9);var forOwn=__webpack_require__(13);var contains=__webpack_require__(10);var deepMixIn=__webpack_require__(14);var pascalCase=__webpack_require__(18);var remove=__webpack_require__(11);var pick=__webpack_require__(15);var sort=__webpack_require__(12);var upperCase=__webpack_require__(19);var get=__webpack_require__(16);var set=__webpack_require__(17);var observe=__webpack_require__(6);var w=undefined;var objectProto=Object.prototype;var toString=objectProto.toString;var P=undefined;try{P=Promise}catch(err){console.error("js-data requires a global Promise constructor!")}var isArray=Array.isArray||function isArray(value){return toString.call(value)=="[object Array]"||false};var isRegExp=function isRegExp(value){return toString.call(value)=="[object RegExp]"||false};var isBoolean=function isBoolean(value){return value===true||value===false||value&&typeof value=="object"&&toString.call(value)=="[object Boolean]"||false};var isString=function isString(value){return typeof value=="string"||value&&typeof value=="object"&&toString.call(value)=="[object String]"||false};var isObject=function isObject(value){return toString.call(value)=="[object Object]"||false};var isDate=function isDate(value){return value&&typeof value=="object"&&toString.call(value)=="[object Date]"||false};var isNumber=function isNumber(value){var type=typeof value;return type=="number"||value&&type=="object"&&toString.call(value)=="[object Number]"||false};var isFunction=function isFunction(value){return typeof value=="function"||value&&toString.call(value)==="[object Function]"||false};var isStringOrNumber=function isStringOrNumber(value){return isString(value)||isNumber(value)};var isStringOrNumberErr=function isStringOrNumberErr(field){return new _DSErrors["default"].IA('"'+field+'" must be a string or a number!')};var isObjectErr=function isObjectErr(field){return new _DSErrors["default"].IA('"'+field+'" must be an object!')};var isArrayErr=function isArrayErr(field){return new _DSErrors["default"].IA('"'+field+'" must be an array!')};var isEmpty=function isEmpty(val){if(val==null){return true}else{if(typeof val==="string"||isArray(val)){return !val.length}else{if(typeof val==="object"){var _ret=(function(){var result=true;forOwn(val,function(){result=false;return false});return{v:result}})();if(typeof _ret==="object"){return _ret.v}}else{return true}}}};var intersection=function intersection(array1,array2){if(!array1||!array2){return[]}var result=[];var item=undefined;for(var i=0,_length=array1.length;i<_length;i++){item=array1[i];if(contains(result,item)){continue}if(contains(array2,item)){result.push(item)}}return result};var filter=function filter(array,cb,thisObj){var results=[];forEach(array,function(value,key,arr){if(cb(value,key,arr)){results.push(value)}},thisObj);return results};try{w=window;w={}}catch(e){w=null}function Events(target){var events={};target=target||this;target.on=function(type,func,ctx){events[type]=events[type]||[];events[type].push({f:func,c:ctx})};target.off=function(type,func){var listeners=events[type];if(!listeners){events={}}else{if(func){for(var i=0;i<listeners.length;i++){if(listeners[i]===func){listeners.splice(i,1);break}}}else{listeners.splice(0,listeners.length)}}};target.emit=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}var listeners=events[args.shift()]||[];if(listeners){for(var i=0;i<listeners.length;i++){listeners[i].f.apply(listeners[i].c,args)}}}}var toPromisify=["beforeValidate","validate","afterValidate","beforeCreate","afterCreate","beforeUpdate","afterUpdate","beforeDestroy","afterDestroy"];var isBlacklisted=function isBlacklisted(prop,bl){var i=undefined;if(!bl||!bl.length){return false}for(i=0;i<bl.length;i++){if(bl[i]===prop){return true}}return false};var copy=(function(_copy){function copy(_x,_x2,_x3,_x4,_x5){return _copy.apply(this,arguments)}copy.toString=function(){return _copy.toString()};return copy})(function(source,destination,stackSource,stackDest,blacklist){if(!destination){destination=source;if(source){if(isArray(source)){destination=copy(source,[],stackSource,stackDest,blacklist)}else{if(isDate(source)){destination=new Date(source.getTime())}else{if(isRegExp(source)){destination=new RegExp(source.source,source.toString().match(/[^\/]*$/)[0]);destination.lastIndex=source.lastIndex}else{if(isObject(source)){destination=copy(source,Object.create(Object.getPrototypeOf(source)),stackSource,stackDest,blacklist)}}}}}}else{if(source===destination){throw new Error("Cannot copy! Source and destination are identical.")}stackSource=stackSource||[];stackDest=stackDest||[];if(isObject(source)){var index=stackSource.indexOf(source);if(index!==-1){return stackDest[index]}stackSource.push(source);stackDest.push(destination)}var result=undefined;if(isArray(source)){var i=undefined;destination.length=0;for(i=0;i<source.length;i++){result=copy(source[i],null,stackSource,stackDest,blacklist);if(isObject(source[i])){stackSource.push(source[i]);stackDest.push(result)}destination.push(result)}}else{if(isArray(destination)){destination.length=0}else{forEach(destination,function(value,key){delete destination[key]})}for(var key in source){if(source.hasOwnProperty(key)){if(isBlacklisted(key,blacklist)){continue}result=copy(source[key],null,stackSource,stackDest,blacklist);if(isObject(source[key])){stackSource.push(source[key]);stackDest.push(result)}destination[key]=result}}}}return destination});var equals=(function(_equals){function equals(_x6,_x7){return _equals.apply(this,arguments)}equals.toString=function(){return _equals.toString()};return equals})(function(o1,o2){if(o1===o2){return true}if(o1===null||o2===null){return false}if(o1!==o1&&o2!==o2){return true}var t1=typeof o1,t2=typeof o2,length,key,keySet;if(t1==t2){if(t1=="object"){if(isArray(o1)){if(!isArray(o2)){return false}if((length=o1.length)==o2.length){for(key=0;key<length;key++){if(!equals(o1[key],o2[key])){return false}}return true}}else{if(isDate(o1)){if(!isDate(o2)){return false}return equals(o1.getTime(),o2.getTime())}else{if(isRegExp(o1)&&isRegExp(o2)){return o1.toString()==o2.toString()}else{if(isArray(o2)){return false}keySet={};for(key in o1){if(key.charAt(0)==="$"||isFunction(o1[key])){continue}if(!equals(o1[key],o2[key])){return false}keySet[key]=true}for(key in o2){if(!keySet.hasOwnProperty(key)&&key.charAt(0)!=="$"&&o2[key]!==undefined&&!isFunction(o2[key])){return false}}return true}}}}}return false});var resolveId=function resolveId(definition,idOrInstance){if(isString(idOrInstance)||isNumber(idOrInstance)){return idOrInstance}else{if(idOrInstance&&definition){return idOrInstance[definition.idAttribute]||idOrInstance}else{return idOrInstance}}};var resolveItem=function resolveItem(resource,idOrInstance){if(resource&&(isString(idOrInstance)||isNumber(idOrInstance))){return resource.index[idOrInstance]||idOrInstance}else{return idOrInstance}};var isValidString=function isValidString(val){return val!=null&&val!==""};var join=function join(items,separator){separator=separator||"";return filter(items,isValidString).join(separator)};var makePath=function makePath(){for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}var result=join(args,"/");return result.replace(/([^:\/]|^)\/{2,}/g,"$1/")};exports["default"]={Promise:P,_:function _(parent,options){var _this=this;options=options||{};if(options&&options.constructor===parent.constructor){return options}else{if(!isObject(options)){throw new _DSErrors["default"].IA('"options" must be an object!')}}forEach(toPromisify,function(name){if(typeof options[name]==="function"&&options[name].toString().indexOf("for (var _len = arg")===-1){options[name]=_this.promisify(options[name])}});var O=function Options(attrs){var self=this;forOwn(attrs,function(value,key){self[key]=value})};O.prototype=parent;O.prototype.orig=function(){var orig={};forOwn(this,function(value,key){orig[key]=value});return orig};return new O(options)},_n:isNumber,_s:isString,_sn:isStringOrNumber,_snErr:isStringOrNumberErr,_o:isObject,_oErr:isObjectErr,_a:isArray,_aErr:isArrayErr,compute:function compute(fn,field){var _this=this;var args=[];forEach(fn.deps,function(dep){args.push(get(_this,dep))});set(_this,field,fn[fn.length-1].apply(_this,args))},contains:contains,copy:copy,deepMixIn:deepMixIn,diffObjectFromOldObject:observe.diffObjectFromOldObject,BinaryHeap:BinaryHeap,equals:equals,Events:Events,filter:filter,fillIn:function fillIn(target,obj){forOwn(obj,function(v,k){if(!(k in target)){target[k]=v}});return target},forEach:forEach,forOwn:forOwn,fromJson:function fromJson(json){return isString(json)?JSON.parse(json):json},get:get,intersection:intersection,isArray:isArray,isBoolean:isBoolean,isDate:isDate,isEmpty:isEmpty,isFunction:isFunction,isObject:isObject,isNumber:isNumber,isRegExp:isRegExp,isString:isString,makePath:makePath,observe:observe,pascalCase:pascalCase,pick:pick,promisify:function promisify(fn,target){var _this=this;if(!fn){return}else{if(typeof fn!=="function"){throw new Error("Can only promisify functions!")}}return function(){for(var _len3=arguments.length,args=Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3]}return new _this.Promise(function(resolve,reject){args.push(function(err,result){if(err){reject(err)}else{resolve(result)}});try{var promise=fn.apply(target||this,args);if(promise&&promise.then){promise.then(resolve,reject)}}catch(err){reject(err)}})}},remove:remove,set:set,slice:slice,sort:sort,toJson:JSON.stringify,updateTimestamp:function updateTimestamp(timestamp){var newTimestamp=typeof Date.now==="function"?Date.now():new Date().getTime();if(timestamp&&newTimestamp<=timestamp){return timestamp+1}else{return newTimestamp}},upperCase:upperCase,removeCircular:function removeCircular(object){return(function rmCirc(value,context){var i=undefined;var nu=undefined;if(typeof value==="object"&&value!==null&&!(value instanceof Boolean)&&!(value instanceof Date)&&!(value instanceof Number)&&!(value instanceof RegExp)&&!(value instanceof String)){var current=context.current;var parent=context.context;while(parent){if(parent.current===current){return undefined}parent=parent.context}if(isArray(value)){nu=[];for(i=0;i<value.length;i+=1){nu[i]=rmCirc(value[i],{context:context,current:value[i]})}}else{nu={};forOwn(value,function(v,k){nu[k]=rmCirc(value[k],{context:context,current:value[k]})})}return nu}return value})(object,{context:null,current:object})},resolveItem:resolveItem,resolveId:resolveId,w:w,applyRelationGettersToTarget:function applyRelationGettersToTarget(store,definition,target){this.forEach(definition.relationList,function(def){var relationName=def.relation;var enumerable=typeof def.enumerable==="boolean"?def.enumerable:!!definition.relationsEnumerable;if(typeof def.link==="boolean"?def.link:!!definition.linkRelations){delete target[def.localField];if(def.type==="belongsTo"){Object.defineProperty(target,def.localField,{enumerable:enumerable,get:function get(){return this[def.localKey]?definition.getResource(relationName).get(this[def.localKey]):undefined},set:function set(){}})}else{if(def.type==="hasMany"){Object.defineProperty(target,def.localField,{enumerable:enumerable,get:function get(){var params={};if(def.foreignKey){params[def.foreignKey]=this[definition.idAttribute];return store.defaults.constructor.prototype.defaultFilter.call(store,store.s[relationName].collection,relationName,params,{allowSimpleWhere:true})}else{if(def.localKeys){params.where=_defineProperty({},definition.getResource(relationName).idAttribute,{"in":this[def.localKeys]});return store.defaults.constructor.prototype.defaultFilter.call(store,store.s[relationName].collection,relationName,params)}}return undefined},set:function set(){}})}else{if(def.type==="hasOne"){if(def.localKey){Object.defineProperty(target,def.localField,{enumerable:enumerable,get:function get(){return this[def.localKey]?definition.getResource(relationName).get(this[def.localKey]):undefined},set:function set(){}})}else{Object.defineProperty(target,def.localField,{enumerable:enumerable,get:function get(){var params={};params[def.foreignKey]=this[definition.idAttribute];var items=params[def.foreignKey]?store.defaults.constructor.prototype.defaultFilter.call(store,store.s[relationName].collection,relationName,params,{allowSimpleWhere:true}):[];if(items.length){return items[0]}return undefined},set:function set(){}})}}}}}})}}},function(module,exports,__webpack_require__){var _classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var _inherits=function(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass){subClass.__proto__=superClass}};var IllegalArgumentError=(function(_Error){function IllegalArgumentError(message){_classCallCheck(this,IllegalArgumentError);var _this=new _Error(_this);_this.__proto__=IllegalArgumentError.prototype;if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(_this,_this.constructor)}_this.type=_this.constructor.name;_this.message=message||"Illegal Argument!";return _this}_inherits(IllegalArgumentError,_Error);return IllegalArgumentError})(Error);var RuntimeError=(function(_Error2){function RuntimeError(message){_classCallCheck(this,RuntimeError);var _this2=new _Error2(_this2);_this2.__proto__=RuntimeError.prototype;if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(_this2,_this2.constructor)}_this2.type=_this2.constructor.name;_this2.message=message||"RuntimeError Error!";return _this2}_inherits(RuntimeError,_Error2);return RuntimeError})(Error);var NonexistentResourceError=(function(_Error3){function NonexistentResourceError(resourceName){_classCallCheck(this,NonexistentResourceError);var _this3=new _Error3(_this3);_this3.__proto__=NonexistentResourceError.prototype;if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(_this3,_this3.constructor)}_this3.type=_this3.constructor.name;_this3.message=""+resourceName+" is not a registered resource!";return _this3}_inherits(NonexistentResourceError,_Error3);return NonexistentResourceError})(Error);exports["default"]={IllegalArgumentError:IllegalArgumentError,IA:IllegalArgumentError,RuntimeError:RuntimeError,R:RuntimeError,NonexistentResourceError:NonexistentResourceError,NER:NonexistentResourceError}},function(module,exports,__webpack_require__){var _DSUtils=__webpack_require__(2);var _DSErrors=__webpack_require__(3);var _defineResource=__webpack_require__(28);var _eject=__webpack_require__(29);var _ejectAll=__webpack_require__(30);var _filter=__webpack_require__(31);var _inject=__webpack_require__(32);var NER=_DSErrors["default"].NER;var IA=_DSErrors["default"].IA;var R=_DSErrors["default"].R;function diffIsEmpty(diff){return !(_DSUtils["default"].isEmpty(diff.added)&&_DSUtils["default"].isEmpty(diff.removed)&&_DSUtils["default"].isEmpty(diff.changed))}exports["default"]={changes:function changes(resourceName,id,options){var _this=this;var definition=_this.defs[resourceName];options=options||{};id=_DSUtils["default"].resolveId(definition,id);if(!definition){throw new NER(resourceName)}else{if(!_DSUtils["default"]._sn(id)){throw _DSUtils["default"]._snErr("id")}}options=_DSUtils["default"]._(definition,options);options.logFn("changes",id,options);var item=_this.get(resourceName,id);if(item){var _ret=(function(){if(_DSUtils["default"].w){_this.s[resourceName].observers[id].deliver()}var ignoredChanges=options.ignoredChanges||[];_DSUtils["default"].forEach(definition.relationFields,function(field){if(!_DSUtils["default"].contains(ignoredChanges,field)){ignoredChanges.push(field)}});var diff=_DSUtils["default"].diffObjectFromOldObject(item,_this.s[resourceName].previousAttributes[id],_DSUtils["default"].equals,ignoredChanges);_DSUtils["default"].forOwn(diff,function(changeset,name){var toKeep=[];_DSUtils["default"].forOwn(changeset,function(value,field){if(!_DSUtils["default"].isFunction(value)){toKeep.push(field)}});diff[name]=_DSUtils["default"].pick(diff[name],toKeep)});_DSUtils["default"].forEach(definition.relationFields,function(field){delete diff.added[field];delete diff.removed[field];delete diff.changed[field]});return{v:diff}})();if(typeof _ret==="object"){return _ret.v}}},changeHistory:function changeHistory(resourceName,id){var _this=this;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];id=_DSUtils["default"].resolveId(definition,id);if(resourceName&&!_this.defs[resourceName]){throw new NER(resourceName)}else{if(id&&!_DSUtils["default"]._sn(id)){throw _DSUtils["default"]._snErr("id")}}definition.logFn("changeHistory",id);if(!definition.keepChangeHistory){definition.errorFn("changeHistory is disabled for this resource!")}else{if(resourceName){var item=_this.get(resourceName,id);if(item){return resource.changeHistories[id]}}else{return resource.changeHistory}}},compute:function compute(resourceName,instance){var _this=this;var definition=_this.defs[resourceName];instance=_DSUtils["default"].resolveItem(_this.s[resourceName],instance);if(!definition){throw new NER(resourceName)}else{if(!instance){throw new R("Item not in the store!")}else{if(!_DSUtils["default"]._o(instance)&&!_DSUtils["default"]._sn(instance)){throw new IA('"instance" must be an object, string or number!')}}}definition.logFn("compute",instance);_DSUtils["default"].forOwn(definition.computed,function(fn,field){_DSUtils["default"].compute.call(instance,fn,field)});return instance},createInstance:function createInstance(resourceName,attrs,options){var definition=this.defs[resourceName];var item=undefined;attrs=attrs||{};if(!definition){throw new NER(resourceName)}else{if(attrs&&!_DSUtils["default"].isObject(attrs)){throw new IA('"attrs" must be an object!')}}options=_DSUtils["default"]._(definition,options);options.logFn("createInstance",attrs,options);if(options.notify){options.beforeCreateInstance(options,attrs)}var Constructor=definition[definition["class"]];item=new Constructor();if(options.defaultValues){_DSUtils["default"].deepMixIn(item,options.defaultValues)}_DSUtils["default"].deepMixIn(item,attrs);if(definition.computed){this.compute(definition.name,item)}if(options.notify){options.afterCreateInstance(options,item)}return item},createCollection:function createCollection(resourceName,arr,params,options){var _this=this;var definition=_this.defs[resourceName];arr=arr||[];params=params||{};if(!definition){throw new NER(resourceName)}else{if(arr&&!_DSUtils["default"].isArray(arr)){throw new IA('"arr" must be an array!')}}options=_DSUtils["default"]._(definition,options);options.logFn("createCollection",arr,options);if(options.notify){options.beforeCreateCollection(options,arr)}Object.defineProperties(arr,{fetch:{value:function value(params,options){var __this=this;__this.params=params||__this.params;return _this.findAll(resourceName,__this.params,options).then(function(data){if(data===__this){return __this}data.unshift(__this.length);data.unshift(0);__this.splice.apply(__this,data);data.shift();data.shift();if(data.$$injected){_this.s[resourceName].queryData[_DSUtils["default"].toJson(__this.params)]=__this;__this.$$injected=true}return __this})}},params:{value:params,writable:true},resourceName:{value:resourceName}});if(options.notify){options.afterCreateCollection(options,arr)}return arr},defineResource:_defineResource["default"],digest:function digest(){this.observe.Platform.performMicrotaskCheckpoint()},eject:_eject["default"],ejectAll:_ejectAll["default"],filter:_filter["default"],get:function get(resourceName,id,options){var _this=this;var definition=_this.defs[resourceName];if(!definition){throw new NER(resourceName)}else{if(!_DSUtils["default"]._sn(id)){throw _DSUtils["default"]._snErr("id")}}options=_DSUtils["default"]._(definition,options);options.logFn("get",id,options);var item=_this.s[resourceName].index[id];return item},getAll:function getAll(resourceName,ids){var _this=this;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var collection=[];if(!definition){throw new NER(resourceName)}else{if(ids&&!_DSUtils["default"]._a(ids)){throw _DSUtils["default"]._aErr("ids")}}definition.logFn("getAll",ids);if(_DSUtils["default"]._a(ids)){var _length=ids.length;for(var i=0;i<_length;i++){if(resource.index[ids[i]]){collection.push(resource.index[ids[i]])}}}else{collection=resource.collection.slice()}return collection},hasChanges:function hasChanges(resourceName,id){var _this=this;var definition=_this.defs[resourceName];id=_DSUtils["default"].resolveId(definition,id);if(!definition){throw new NER(resourceName)}else{if(!_DSUtils["default"]._sn(id)){throw _DSUtils["default"]._snErr("id")}}definition.logFn("hasChanges",id);if(_this.get(resourceName,id)){return diffIsEmpty(_this.changes(resourceName,id))}else{return false}},inject:_inject["default"],lastModified:function lastModified(resourceName,id){var definition=this.defs[resourceName];var resource=this.s[resourceName];id=_DSUtils["default"].resolveId(definition,id);if(!definition){throw new NER(resourceName)}definition.logFn("lastModified",id);if(id){if(!(id in resource.modified)){resource.modified[id]=0}return resource.modified[id]}return resource.collectionModified},lastSaved:function lastSaved(resourceName,id){var definition=this.defs[resourceName];var resource=this.s[resourceName];id=_DSUtils["default"].resolveId(definition,id);if(!definition){throw new NER(resourceName)}definition.logFn("lastSaved",id);if(!(id in resource.saved)){resource.saved[id]=0}return resource.saved[id]},previous:function previous(resourceName,id){var _this=this;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];id=_DSUtils["default"].resolveId(definition,id);if(!definition){throw new NER(resourceName)}else{if(!_DSUtils["default"]._sn(id)){throw _DSUtils["default"]._snErr("id")}}definition.logFn("previous",id);return resource.previousAttributes[id]?_DSUtils["default"].copy(resource.previousAttributes[id]):undefined}}},function(module,exports,__webpack_require__){var _create=__webpack_require__(33);var _destroy=__webpack_require__(34);var _destroyAll=__webpack_require__(35);var _find=__webpack_require__(36);var _findAll=__webpack_require__(37);var _loadRelations=__webpack_require__(38);var _reap=__webpack_require__(39);var _save=__webpack_require__(40);var _update=__webpack_require__(41);var _updateAll=__webpack_require__(42);exports["default"]={create:_create["default"],destroy:_destroy["default"],destroyAll:_destroyAll["default"],find:_find["default"],findAll:_findAll["default"],loadRelations:_loadRelations["default"],reap:_reap["default"],refresh:function refresh(resourceName,id,options){var _this=this;var DSUtils=_this.utils;return new DSUtils.Promise(function(resolve,reject){var definition=_this.defs[resourceName];id=DSUtils.resolveId(_this.defs[resourceName],id);if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.bypassCache=true;options.logFn("refresh",id,options);resolve(_this.get(resourceName,id))}}}).then(function(item){return item?_this.find(resourceName,id,options):item})},save:_save["default"],update:_update["default"],updateAll:_updateAll["default"]}},function(module,exports,__webpack_require__){(function(global){var testingExposeCycleCount=global.testingExposeCycleCount;function detectObjectObserve(){if(typeof Object.observe!=="function"||typeof Array.observe!=="function"){return false}var records=[];function callback(recs){records=recs}var test={};var arr=[];Object.observe(test,callback);Array.observe(arr,callback);test.id=1;test.id=2;delete test.id;arr.push(1,2);arr.length=0;Object.deliverChangeRecords(callback);if(records.length!==5){return false}if(records[0].type!="add"||records[1].type!="update"||records[2].type!="delete"||records[3].type!="splice"||records[4].type!="splice"){return false}Object.unobserve(test,callback);Array.unobserve(arr,callback);return true}var hasObserve=detectObjectObserve();var createObject=("__proto__" in {})?function(obj){return obj}:function(obj){var proto=obj.__proto__;if(!proto){return obj}var newObject=Object.create(proto);Object.getOwnPropertyNames(obj).forEach(function(name){Object.defineProperty(newObject,name,Object.getOwnPropertyDescriptor(obj,name))});return newObject};var MAX_DIRTY_CHECK_CYCLES=1000;function dirtyCheck(observer){var cycles=0;while(cycles<MAX_DIRTY_CHECK_CYCLES&&observer.check_()){cycles++}if(testingExposeCycleCount){global.dirtyCheckCycleCount=cycles}return cycles>0}function objectIsEmpty(object){for(var prop in object){return false}return true}function diffIsEmpty(diff){return objectIsEmpty(diff.added)&&objectIsEmpty(diff.removed)&&objectIsEmpty(diff.changed)}function isBlacklisted(prop,bl){if(!bl||!bl.length){return false}var matches;for(var i=0;i<bl.length;i++){if((Object.prototype.toString.call(bl[i])==="[object RegExp]"&&bl[i].test(prop))||bl[i]===prop){return matches=prop}}return !!matches}function diffObjectFromOldObject(object,oldObject,equals,bl){var added={};var removed={};var changed={};for(var prop in oldObject){var newValue=object[prop];if(isBlacklisted(prop,bl)){continue}if(newValue!==undefined&&(equals?equals(newValue,oldObject[prop]):newValue===oldObject[prop])){continue}if(!(prop in object)){removed[prop]=undefined;continue}if(equals?!equals(newValue,oldObject[prop]):newValue!==oldObject[prop]){changed[prop]=newValue}}for(var prop in object){if(prop in oldObject){continue}if(isBlacklisted(prop,bl)){continue}added[prop]=object[prop]}if(Array.isArray(object)&&object.length!==oldObject.length){changed.length=object.length}return{added:added,removed:removed,changed:changed}}var eomTasks=[];function runEOMTasks(){if(!eomTasks.length){return false}for(var i=0;i<eomTasks.length;i++){eomTasks[i]()}eomTasks.length=0;return true}var runEOM=hasObserve?(function(){return function(fn){return Promise.resolve().then(fn)}})():(function(){return function(fn){eomTasks.push(fn)}})();var observedObjectCache=[];function newObservedObject(){var observer;var object;var discardRecords=false;var first=true;function callback(records){if(observer&&observer.state_===OPENED&&!discardRecords){observer.check_(records)}}return{open:function(obs){if(observer){throw Error("ObservedObject in use")}if(!first){Object.deliverChangeRecords(callback)}observer=obs;first=false},observe:function(obj,arrayObserve){object=obj;if(arrayObserve){Array.observe(object,callback)}else{Object.observe(object,callback)}},deliver:function(discard){discardRecords=discard;Object.deliverChangeRecords(callback);discardRecords=false},close:function(){observer=undefined;Object.unobserve(object,callback);observedObjectCache.push(this)}}}function getObservedObject(observer,object,arrayObserve){var dir=observedObjectCache.pop()||newObservedObject();dir.open(observer);dir.observe(object,arrayObserve);return dir}var UNOPENED=0;var OPENED=1;var CLOSED=2;var nextObserverId=1;function Observer(){this.state_=UNOPENED;this.callback_=undefined;this.target_=undefined;this.directObserver_=undefined;this.value_=undefined;this.id_=nextObserverId++}Observer.prototype={open:function(callback,target){if(this.state_!=UNOPENED){throw Error("Observer has already been opened.")}addToAll(this);this.callback_=callback;this.target_=target;this.connect_();this.state_=OPENED;return this.value_},close:function(){if(this.state_!=OPENED){return}removeFromAll(this);this.disconnect_();this.value_=undefined;this.callback_=undefined;this.target_=undefined;this.state_=CLOSED},deliver:function(){if(this.state_!=OPENED){return}dirtyCheck(this)},report_:function(changes){try{this.callback_.apply(this.target_,changes)}catch(ex){Observer._errorThrownDuringCallback=true;console.error("Exception caught during observer callback: "+(ex.stack||ex))}},discardChanges:function(){this.check_(undefined,true);return this.value_}};var collectObservers=!hasObserve;var allObservers;Observer._allObserversCount=0;if(collectObservers){allObservers=[]}function addToAll(observer){Observer._allObserversCount++;if(!collectObservers){return}allObservers.push(observer)}function removeFromAll(observer){Observer._allObserversCount--}var runningMicrotaskCheckpoint=false;global.Platform=global.Platform||{};global.Platform.performMicrotaskCheckpoint=function(){if(runningMicrotaskCheckpoint){return}if(!collectObservers){return}runningMicrotaskCheckpoint=true;var cycles=0;var anyChanged,toCheck;do{cycles++;toCheck=allObservers;allObservers=[];anyChanged=false;for(var i=0;i<toCheck.length;i++){var observer=toCheck[i];if(observer.state_!=OPENED){continue}if(observer.check_()){anyChanged=true}allObservers.push(observer)}if(runEOMTasks()){anyChanged=true}}while(cycles<MAX_DIRTY_CHECK_CYCLES&&anyChanged);if(testingExposeCycleCount){global.dirtyCheckCycleCount=cycles}runningMicrotaskCheckpoint=false};if(collectObservers){global.Platform.clearObservers=function(){allObservers=[]}}function ObjectObserver(object){Observer.call(this);this.value_=object;this.oldObject_=undefined}ObjectObserver.prototype=createObject({__proto__:Observer.prototype,arrayObserve:false,connect_:function(callback,target){if(hasObserve){this.directObserver_=getObservedObject(this,this.value_,this.arrayObserve)}else{this.oldObject_=this.copyObject(this.value_)}},copyObject:function(object){var copy=Array.isArray(object)?[]:{};for(var prop in object){copy[prop]=object[prop]}if(Array.isArray(object)){copy.length=object.length}return copy},check_:function(changeRecords,skipChanges){var diff;var oldValues;if(hasObserve){if(!changeRecords){return false}oldValues={};diff=diffObjectFromChangeRecords(this.value_,changeRecords,oldValues)}else{oldValues=this.oldObject_;diff=diffObjectFromOldObject(this.value_,this.oldObject_)}if(diffIsEmpty(diff)){return false}if(!hasObserve){this.oldObject_=this.copyObject(this.value_)}this.report_([diff.added||{},diff.removed||{},diff.changed||{},function(property){return oldValues[property]}]);return true},disconnect_:function(){if(hasObserve){this.directObserver_.close();this.directObserver_=undefined}else{this.oldObject_=undefined}},deliver:function(){if(this.state_!=OPENED){return}if(hasObserve){this.directObserver_.deliver(false)}else{dirtyCheck(this)}},discardChanges:function(){if(this.directObserver_){this.directObserver_.deliver(true)}else{this.oldObject_=this.copyObject(this.value_)}return this.value_}});var observerSentinel={};var expectedRecordTypes={add:true,update:true,"delete":true};function diffObjectFromChangeRecords(object,changeRecords,oldValues){var added={};var removed={};for(var i=0;i<changeRecords.length;i++){var record=changeRecords[i];if(!expectedRecordTypes[record.type]){console.error("Unknown changeRecord type: "+record.type);console.error(record);continue}if(!(record.name in oldValues)){oldValues[record.name]=record.oldValue}if(record.type=="update"){continue}if(record.type=="add"){if(record.name in removed){delete removed[record.name]}else{added[record.name]=true}continue}if(record.name in added){delete added[record.name];delete oldValues[record.name]}else{removed[record.name]=true}}for(var prop in added){added[prop]=object[prop]}for(var prop in removed){removed[prop]=undefined}var changed={};for(var prop in oldValues){if(prop in added||prop in removed){continue}var newValue=object[prop];if(oldValues[prop]!==newValue){changed[prop]=newValue}}return{added:added,removed:removed,changed:changed}}global.Observer=Observer;global.Observer.runEOM_=runEOM;global.Observer.observerSentinel_=observerSentinel;global.Observer.hasObjectObserve=hasObserve;global.diffObjectFromOldObject=diffObjectFromOldObject;global.ObjectObserver=ObjectObserver})(exports)},function(module,exports,__webpack_require__){ /*! * yabh * @version 1.0.1 - Homepage <http://jmdobry.github.io/yabh/> * @author Jason Dobry <jason.dobry@gmail.com> * @copyright (c) 2015 Jason Dobry * @license MIT <https://github.com/jmdobry/yabh/blob/master/LICENSE> * * @overview Yet another Binary Heap. */ (function webpackUniversalModuleDefinition(root,factory){if(true){module.exports=factory()}else{if(typeof define==="function"&&define.amd){define("yabh",factory)}else{if(typeof exports==="object"){exports.BinaryHeap=factory()}else{root.BinaryHeap=factory()}}}})(this,function(){return(function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.loaded=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)})([function(module,exports,__webpack_require__){var _classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var _createClass=(function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value" in descriptor){descriptor.writable=true}Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps){defineProperties(Constructor.prototype,protoProps)}if(staticProps){defineProperties(Constructor,staticProps)}return Constructor}})();Object.defineProperty(exports,"__esModule",{value:true});function bubbleUp(heap,weightFunc,n){var element=heap[n];var weight=weightFunc(element);while(n>0){var parentN=Math.floor((n+1)/2)-1;var _parent=heap[parentN];if(weight>=weightFunc(_parent)){break}else{heap[parentN]=element;heap[n]=_parent;n=parentN}}}var bubbleDown=function bubbleDown(heap,weightFunc,n){var length=heap.length;var node=heap[n];var nodeWeight=weightFunc(node);while(true){var child2N=(n+1)*2,child1N=child2N-1;var swap=null;if(child1N<length){var child1=heap[child1N],child1Weight=weightFunc(child1);if(child1Weight<nodeWeight){swap=child1N}}if(child2N<length){var child2=heap[child2N],child2Weight=weightFunc(child2);if(child2Weight<(swap===null?nodeWeight:weightFunc(heap[child1N]))){swap=child2N}}if(swap===null){break}else{heap[n]=heap[swap];heap[swap]=node;n=swap}}};var BinaryHeap=(function(){function BinaryHeap(weightFunc,compareFunc){_classCallCheck(this,BinaryHeap);if(!weightFunc){weightFunc=function(x){return x}}if(!compareFunc){compareFunc=function(x,y){return x===y}}if(typeof weightFunc!=="function"){throw new Error('BinaryHeap([weightFunc][, compareFunc]): "weightFunc" must be a function!')}if(typeof compareFunc!=="function"){throw new Error('BinaryHeap([weightFunc][, compareFunc]): "compareFunc" must be a function!')}this.weightFunc=weightFunc;this.compareFunc=compareFunc;this.heap=[]}_createClass(BinaryHeap,[{key:"push",value:function push(node){this.heap.push(node);bubbleUp(this.heap,this.weightFunc,this.heap.length-1)}},{key:"peek",value:function peek(){return this.heap[0]}},{key:"pop",value:function pop(){var front=this.heap[0];var end=this.heap.pop();if(this.heap.length>0){this.heap[0]=end;bubbleDown(this.heap,this.weightFunc,0)}return front}},{key:"remove",value:function remove(node){var length=this.heap.length;for(var i=0;i<length;i++){if(this.compareFunc(this.heap[i],node)){var removed=this.heap[i];var end=this.heap.pop();if(i!==length-1){this.heap[i]=end;bubbleUp(this.heap,this.weightFunc,i);bubbleDown(this.heap,this.weightFunc,i)}return removed}}return null}},{key:"removeAll",value:function removeAll(){this.heap=[]}},{key:"size",value:function size(){return this.heap.length}}]);return BinaryHeap})();exports["default"]=BinaryHeap;module.exports=exports["default"]}])})},function(module,exports,__webpack_require__){function forEach(arr,callback,thisObj){if(arr==null){return}var i=-1,len=arr.length;while(++i<len){if(callback.call(thisObj,arr[i],i,arr)===false){break}}}module.exports=forEach},function(module,exports,__webpack_require__){function slice(arr,start,end){var len=arr.length;if(start==null){start=0}else{if(start<0){start=Math.max(len+start,0)}else{start=Math.min(start,len)}}if(end==null){end=len}else{if(end<0){end=Math.max(len+end,0)}else{end=Math.min(end,len)}}var result=[];while(start<end){result.push(arr[start++])}return result}module.exports=slice},function(module,exports,__webpack_require__){var indexOf=__webpack_require__(20);function contains(arr,val){return indexOf(arr,val)!==-1}module.exports=contains},function(module,exports,__webpack_require__){var indexOf=__webpack_require__(20);function remove(arr,item){var idx=indexOf(arr,item);if(idx!==-1){arr.splice(idx,1)}}module.exports=remove},function(module,exports,__webpack_require__){function mergeSort(arr,compareFn){if(arr==null){return[]}else{if(arr.length<2){return arr}}if(compareFn==null){compareFn=defaultCompare}var mid,left,right;mid=~~(arr.length/2);left=mergeSort(arr.slice(0,mid),compareFn);right=mergeSort(arr.slice(mid,arr.length),compareFn);return merge(left,right,compareFn)}function defaultCompare(a,b){return a<b?-1:(a>b?1:0)}function merge(left,right,compareFn){var result=[];while(left.length&&right.length){if(compareFn(left[0],right[0])<=0){result.push(left.shift())}else{result.push(right.shift())}}if(left.length){result.push.apply(result,left)}if(right.length){result.push.apply(result,right)}return result}module.exports=mergeSort},function(module,exports,__webpack_require__){var hasOwn=__webpack_require__(21);var forIn=__webpack_require__(22);function forOwn(obj,fn,thisObj){forIn(obj,function(val,key){if(hasOwn(obj,key)){return fn.call(thisObj,obj[key],key,obj)}})}module.exports=forOwn},function(module,exports,__webpack_require__){var forOwn=__webpack_require__(13);var isPlainObject=__webpack_require__(23);function deepMixIn(target,objects){var i=0,n=arguments.length,obj;while(++i<n){obj=arguments[i];if(obj){forOwn(obj,copyProp,target)}}return target}function copyProp(val,key){var existing=this[key];if(isPlainObject(val)&&isPlainObject(existing)){deepMixIn(existing,val)}else{this[key]=val}}module.exports=deepMixIn},function(module,exports,__webpack_require__){var slice=__webpack_require__(9);function pick(obj,var_keys){var keys=typeof arguments[1]!=="string"?arguments[1]:slice(arguments,1),out={},i=0,key;while(key=keys[i++]){out[key]=obj[key]}return out}module.exports=pick},function(module,exports,__webpack_require__){var isPrimitive=__webpack_require__(24);function get(obj,prop){var parts=prop.split("."),last=parts.pop();while(prop=parts.shift()){obj=obj[prop];if(obj==null){return}}return obj[last]}module.exports=get},function(module,exports,__webpack_require__){var namespace=__webpack_require__(25);function set(obj,prop,val){var parts=(/^(.+)\.(.+)$/).exec(prop);if(parts){namespace(obj,parts[1])[parts[2]]=val}else{obj[prop]=val}}module.exports=set},function(module,exports,__webpack_require__){var toString=__webpack_require__(26);var camelCase=__webpack_require__(27);var upperCase=__webpack_require__(19);function pascalCase(str){str=toString(str);return camelCase(str).replace(/^[a-z]/,upperCase)}module.exports=pascalCase},function(module,exports,__webpack_require__){var toString=__webpack_require__(26);function upperCase(str){str=toString(str);return str.toUpperCase()}module.exports=upperCase},function(module,exports,__webpack_require__){function indexOf(arr,item,fromIndex){fromIndex=fromIndex||0;if(arr==null){return -1}var len=arr.length,i=fromIndex<0?len+fromIndex:fromIndex;while(i<len){if(arr[i]===item){return i}i++}return -1}module.exports=indexOf},function(module,exports,__webpack_require__){function hasOwn(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=hasOwn},function(module,exports,__webpack_require__){var hasOwn=__webpack_require__(21);var _hasDontEnumBug,_dontEnums;function checkDontEnum(){_dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];_hasDontEnumBug=true;for(var key in {toString:null}){_hasDontEnumBug=false}}function forIn(obj,fn,thisObj){var key,i=0;if(_hasDontEnumBug==null){checkDontEnum()}for(key in obj){if(exec(fn,obj,key,thisObj)===false){break}}if(_hasDontEnumBug){var ctor=obj.constructor,isProto=!!ctor&&obj===ctor.prototype;while(key=_dontEnums[i++]){if((key!=="constructor"||(!isProto&&hasOwn(obj,key)))&&obj[key]!==Object.prototype[key]){if(exec(fn,obj,key,thisObj)===false){break}}}}}function exec(fn,obj,key,thisObj){return fn.call(thisObj,obj[key],key,obj)}module.exports=forIn},function(module,exports,__webpack_require__){function isPlainObject(value){return(!!value&&typeof value==="object"&&value.constructor===Object)}module.exports=isPlainObject},function(module,exports,__webpack_require__){function isPrimitive(value){switch(typeof value){case"string":case"number":case"boolean":return true}return value==null}module.exports=isPrimitive},function(module,exports,__webpack_require__){var forEach=__webpack_require__(8);function namespace(obj,path){if(!path){return obj}forEach(path.split("."),function(key){if(!obj[key]){obj[key]={}}obj=obj[key]});return obj}module.exports=namespace},function(module,exports,__webpack_require__){function toString(val){return val==null?"":val.toString()}module.exports=toString},function(module,exports,__webpack_require__){var toString=__webpack_require__(26);var replaceAccents=__webpack_require__(43);var removeNonWord=__webpack_require__(44);var upperCase=__webpack_require__(19);var lowerCase=__webpack_require__(45);function camelCase(str){str=toString(str);str=replaceAccents(str);str=removeNonWord(str).replace(/[\-_]/g," ").replace(/\s[a-z]/g,upperCase).replace(/\s+/g,"").replace(/^[A-Z]/g,lowerCase);return str}module.exports=camelCase},function(module,exports,__webpack_require__){exports["default"]=defineResource;var _DSUtils=__webpack_require__(2);var _DSErrors=__webpack_require__(3);var instanceMethods=["compute","refresh","save","update","destroy","loadRelations","changeHistory","changes","hasChanges","lastModified","lastSaved","previous"];function defineResource(definition){var _this=this;var definitions=_this.defs;if(_DSUtils["default"]._s(definition)){definition={name:definition.replace(/\s/gi,"")}}if(!_DSUtils["default"]._o(definition)){throw _DSUtils["default"]._oErr("definition")}else{if(!_DSUtils["default"]._s(definition.name)){throw new _DSErrors["default"].IA('"name" must be a string!')}else{if(_this.s[definition.name]){throw new _DSErrors["default"].R(""+definition.name+" is already registered!")}}}function Resource(options){this.defaultValues={};this.methods={};this.computed={};_DSUtils["default"].deepMixIn(this,options);var parent=_this.defaults;if(definition["extends"]&&definitions[definition["extends"]]){parent=definitions[definition["extends"]]}_DSUtils["default"].fillIn(this.defaultValues,parent.defaultValues);_DSUtils["default"].fillIn(this.methods,parent.methods);_DSUtils["default"].fillIn(this.computed,parent.computed);this.endpoint="endpoint" in options?options.endpoint:this.name}try{var def;var _class;var _ret=(function(){if(definition["extends"]&&definitions[definition["extends"]]){Resource.prototype=definitions[definition["extends"]]}else{Resource.prototype=_this.defaults}definitions[definition.name]=new Resource(definition);def=definitions[definition.name];def.n=def.name;def.logFn("Preparing resource.");if(!_DSUtils["default"]._s(def.idAttribute)){throw new _DSErrors["default"].IA('"idAttribute" must be a string!')}if(def.relations){def.relationList=[];def.relationFields=[];_DSUtils["default"].forOwn(def.relations,function(relatedModels,type){_DSUtils["default"].forOwn(relatedModels,function(defs,relationName){if(!_DSUtils["default"]._a(defs)){relatedModels[relationName]=[defs]}_DSUtils["default"].forEach(relatedModels[relationName],function(d){d.type=type;d.relation=relationName;d.name=def.n;def.relationList.push(d);if(d.localField){def.relationFields.push(d.localField)}})})});if(def.relations.belongsTo){_DSUtils["default"].forOwn(def.relations.belongsTo,function(relatedModel,modelName){_DSUtils["default"].forEach(relatedModel,function(relation){if(relation.parent){def.parent=modelName;def.parentKey=relation.localKey;def.parentField=relation.localField}})})}if(typeof Object.freeze==="function"){Object.freeze(def.relations);Object.freeze(def.relationList)}}def.getResource=function(resourceName){return _this.defs[resourceName]};def.getEndpoint=function(id,options){options=options||{};options.params=options.params||{};var item=undefined;var parentKey=def.parentKey;var endpoint=options.hasOwnProperty("endpoint")?options.endpoint:def.endpoint;var parentField=def.parentField;var parentDef=definitions[def.parent];var parentId=options.params[parentKey];if(parentId===false||!parentKey||!parentDef){if(parentId===false){delete options.params[parentKey]}return endpoint}else{delete options.params[parentKey];if(_DSUtils["default"]._sn(id)){item=def.get(id)}else{if(_DSUtils["default"]._o(id)){item=id}}if(item){parentId=parentId||item[parentKey]||(item[parentField]?item[parentField][parentDef.idAttribute]:null)}if(parentId){var _ret2=(function(){delete options.endpoint;var _options={};_DSUtils["default"].forOwn(options,function(value,key){_options[key]=value});return{v:_DSUtils["default"].makePath(parentDef.getEndpoint(parentId,_DSUtils["default"]._(parentDef,_options)),parentId,endpoint)}})();if(typeof _ret2==="object"){return _ret2.v}}else{return endpoint}}};if(def.filter){def.defaultFilter=def.filter;delete def.filter}_class=def["class"]=_DSUtils["default"].pascalCase(def.name);try{if(typeof def.useClass==="function"){eval("function "+_class+"() { def.useClass.call(this); }");def[_class]=eval(_class);def[_class].prototype=(function(proto){function Ctor(){}Ctor.prototype=proto;return new Ctor()})(def.useClass.prototype)}else{eval("function "+_class+"() {}");def[_class]=eval(_class)}}catch(e){def[_class]=function(){}}_DSUtils["default"].forOwn(def.methods,function(fn,m){def[_class].prototype[m]=fn});def[_class].prototype.set=function(key,value){_DSUtils["default"].set(this,key,value);_this.compute(def.n,this);return this};def[_class].prototype.get=function(key){return _DSUtils["default"].get(this,key)};_DSUtils["default"].applyRelationGettersToTarget(_this,def,def[_class].prototype);_DSUtils["default"].forOwn(def.computed,function(fn,field){if(_DSUtils["default"].isFunction(fn)){def.computed[field]=[fn];fn=def.computed[field]}if(def.methods&&field in def.methods){def.errorFn('Computed property "'+field+'" conflicts with previously defined prototype method!')}var deps;if(fn.length===1){var match=fn[0].toString().match(/function.*?\(([\s\S]*?)\)/);deps=match[1].split(",");def.computed[field]=deps.concat(fn);fn=def.computed[field];if(deps.length){def.errorFn("Use the computed property array syntax for compatibility with minified code!")}}deps=fn.slice(0,fn.length-1);_DSUtils["default"].forEach(deps,function(val,index){deps[index]=val.trim()});fn.deps=_DSUtils["default"].filter(deps,function(dep){return !!dep})});_DSUtils["default"].forEach(instanceMethods,function(name){def[_class].prototype["DS"+_DSUtils["default"].pascalCase(name)]=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}args.unshift(this[def.idAttribute]||this);args.unshift(def.n);return _this[name].apply(_this,args)}});def[_class].prototype.DSCreate=function(){for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}args.unshift(this);args.unshift(def.n);return _this.create.apply(_this,args)};_this.s[def.n]={collection:[],expiresHeap:new _DSUtils["default"].BinaryHeap(function(x){return x.expires},function(x,y){return x.item===y}),completedQueries:{},queryData:{},pendingQueries:{},index:{},modified:{},saved:{},previousAttributes:{},observers:{},changeHistories:{},changeHistory:[],collectionModified:0};if(def.reapInterval){setInterval(function(){return _this.reap(def.n,{isInterval:true})},def.reapInterval)}var fns=["registerAdapter","getAdapter","is"];for(key in _this){if(typeof _this[key]==="function"){fns.push(key)}}_DSUtils["default"].forEach(fns,function(key){var k=key;if(_this[k].shorthand!==false){def[k]=function(){for(var _len3=arguments.length,args=Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3]}args.unshift(def.n);return _this[k].apply(_this,args)}}else{def[k]=function(){for(var _len4=arguments.length,args=Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4]}return _this[k].apply(_this,args)}}});def.beforeValidate=_DSUtils["default"].promisify(def.beforeValidate);def.validate=_DSUtils["default"].promisify(def.validate);def.afterValidate=_DSUtils["default"].promisify(def.afterValidate);def.beforeCreate=_DSUtils["default"].promisify(def.beforeCreate);def.afterCreate=_DSUtils["default"].promisify(def.afterCreate);def.beforeUpdate=_DSUtils["default"].promisify(def.beforeUpdate);def.afterUpdate=_DSUtils["default"].promisify(def.afterUpdate);def.beforeDestroy=_DSUtils["default"].promisify(def.beforeDestroy);def.afterDestroy=_DSUtils["default"].promisify(def.afterDestroy);var defaultAdapter=undefined;if(def.hasOwnProperty("defaultAdapter")){defaultAdapter=def.defaultAdapter}_DSUtils["default"].forOwn(def.actions,function(action,name){if(def[name]&&!def.actions[name]){throw new Error('Cannot override existing method "'+name+'"!')}action.request=action.request||function(config){return config};action.response=action.response||function(response){return response};action.responseError=action.responseError||function(err){return _DSUtils["default"].Promise.reject(err)};def[name]=function(id,options){if(_DSUtils["default"]._o(id)){options=id}options=options||{};var adapter=_this.getAdapter(action.adapter||defaultAdapter||"http");var config=_DSUtils["default"].deepMixIn({},action);if(!options.hasOwnProperty("endpoint")&&config.endpoint){options.endpoint=config.endpoint}if(typeof options.getEndpoint==="function"){config.url=options.getEndpoint(def,options)}else{var args=[options.basePath||adapter.defaults.basePath||def.basePath,def.getEndpoint(_DSUtils["default"]._sn(id)?id:null,options)];if(_DSUtils["default"]._sn(id)){args.push(id)}args.push(action.pathname||name);config.url=_DSUtils["default"].makePath.apply(null,args)}config.method=config.method||"GET";_DSUtils["default"].deepMixIn(config,options);return new _DSUtils["default"].Promise(function(r){return r(config)}).then(options.request||action.request).then(function(config){return adapter.HTTP(config)}).then(options.response||action.response,options.responseError||action.responseError)}});_DSUtils["default"].Events(def);def.logFn("Done preparing resource.");return{v:def}})();if(typeof _ret==="object"){return _ret.v}}catch(err){delete definitions[definition.name];delete _this.s[definition.name];throw err}}},function(module,exports,__webpack_require__){exports["default"]=eject;function eject(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var item=undefined;var found=false;id=DSUtils.resolveId(definition,id);if(!definition){throw new _this.errors.NER(resourceName)}else{if(!DSUtils._sn(id)){throw DSUtils._snErr("id")}}options=DSUtils._(definition,options);options.logFn("eject",id,options);for(var i=0;i<resource.collection.length;i++){if(resource.collection[i][definition.idAttribute]==id){item=resource.collection[i];resource.expiresHeap.remove(item);found=true;break}}if(found){var _ret=(function(){definition.beforeEject(options,item);if(options.notify){definition.emit("DS.beforeEject",definition,item)}resource.collection.splice(i,1);if(DSUtils.w){resource.observers[id].close()}delete resource.observers[id];delete resource.index[id];delete resource.previousAttributes[id];delete resource.completedQueries[id];delete resource.pendingQueries[id];DSUtils.forEach(resource.changeHistories[id],function(changeRecord){DSUtils.remove(resource.changeHistory,changeRecord)});var toRemove=[];DSUtils.forOwn(resource.queryData,function(items,queryHash){if(items.$$injected){DSUtils.remove(items,item)}if(!items.length&&options.clearEmptyQueries){toRemove.push(queryHash)}});DSUtils.forEach(toRemove,function(queryHash){delete resource.completedQueries[queryHash];delete resource.queryData[queryHash]});delete resource.changeHistories[id];delete resource.modified[id];delete resource.saved[id];resource.collectionModified=DSUtils.updateTimestamp(resource.collectionModified);definition.afterEject(options,item);if(options.notify){definition.emit("DS.afterEject",definition,item)}return{v:item}})();if(typeof _ret==="object"){return _ret.v}}}},function(module,exports,__webpack_require__){exports["default"]=ejectAll;function ejectAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];params=params||{};if(!definition){throw new _this.errors.NER(resourceName)}else{if(!DSUtils._o(params)){throw DSUtils._oErr("params")}}definition.logFn("ejectAll",params,options);var resource=_this.s[resourceName];var queryHash=DSUtils.toJson(params);var items=_this.filter(definition.n,params);var ids=[];if(DSUtils.isEmpty(params)){resource.completedQueries={}}else{delete resource.completedQueries[queryHash]}DSUtils.forEach(items,function(item){if(item&&item[definition.idAttribute]){ids.push(item[definition.idAttribute])}});DSUtils.forEach(ids,function(id){_this.eject(definition.n,id,options)});resource.collectionModified=DSUtils.updateTimestamp(resource.collectionModified);return items}},function(module,exports,__webpack_require__){exports["default"]=filter;function filter(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];if(!definition){throw new _this.errors.NER(resourceName)}else{if(params&&!DSUtils._o(params)){throw DSUtils._oErr("params")}}params=params||{};options=DSUtils._(definition,options);options.logFn("filter",params,options);return definition.defaultFilter.call(_this,_this.s[resourceName].collection,resourceName,params,options)}},function(module,exports,__webpack_require__){exports["default"]=inject;var _DSUtils=__webpack_require__(2);var _DSErrors=__webpack_require__(3);function _getReactFunction(DS,definition,resource){var name=definition.n;return function _react(added,removed,changed,oldValueFn,firstTime){var target=this;var item=undefined;var innerId=oldValueFn&&oldValueFn(definition.idAttribute)?oldValueFn(definition.idAttribute):target[definition.idAttribute];_DSUtils["default"].forEach(definition.relationFields,function(field){delete added[field];delete removed[field];delete changed[field]});if(!_DSUtils["default"].isEmpty(added)||!_DSUtils["default"].isEmpty(removed)||!_DSUtils["default"].isEmpty(changed)||firstTime){item=DS.get(name,innerId);resource.modified[innerId]=_DSUtils["default"].updateTimestamp(resource.modified[innerId]);resource.collectionModified=_DSUtils["default"].updateTimestamp(resource.collectionModified);if(definition.keepChangeHistory){var changeRecord={resourceName:name,target:item,added:added,removed:removed,changed:changed,timestamp:resource.modified[innerId]};resource.changeHistories[innerId].push(changeRecord);resource.changeHistory.push(changeRecord)}}if(definition.computed){item=item||DS.get(name,innerId);_DSUtils["default"].forOwn(definition.computed,function(fn,field){var compute=false;_DSUtils["default"].forEach(fn.deps,function(dep){if(dep in added||dep in removed||dep in changed||!(field in item)){compute=true}});compute=compute||!fn.deps.length;if(compute){_DSUtils["default"].compute.call(item,fn,field)}})}if(definition.idAttribute in changed){definition.errorFn('Doh! You just changed the primary key of an object! Your data for the "'+name+'" resource is now in an undefined (probably broken) state.')}}}function _inject(definition,resource,attrs,options){var _this=this;var _react=_getReactFunction(_this,definition,resource,attrs,options);var injected=undefined;if(_DSUtils["default"]._a(attrs)){injected=[];for(var i=0;i<attrs.length;i++){injected.push(_inject.call(_this,definition,resource,attrs[i],options))}}else{var c=definition.computed;var idA=definition.idAttribute;if(c&&c[idA]){(function(){var args=[];_DSUtils["default"].forEach(c[idA].deps,function(dep){args.push(attrs[dep])});attrs[idA]=c[idA][c[idA].length-1].apply(attrs,args)})()}if(!(idA in attrs)){var error=new _DSErrors["default"].R(""+definition.n+'.inject: "attrs" must contain the property specified by "idAttribute"!');options.errorFn(error);throw error}else{try{_DSUtils["default"].forEach(definition.relationList,function(def){var relationName=def.relation;var relationDef=_this.defs[relationName];var toInject=attrs[def.localField];if(toInject){if(!relationDef){throw new _DSErrors["default"].R(""+definition.n+" relation is defined but the resource is not!")}if(_DSUtils["default"]._a(toInject)){(function(){var items=[];_DSUtils["default"].forEach(toInject,function(toInjectItem){if(toInjectItem!==_this.s[relationName].index[toInjectItem[relationDef.idAttribute]]){try{var injectedItem=_this.inject(relationName,toInjectItem,options.orig());if(def.foreignKey){injectedItem[def.foreignKey]=attrs[definition.idAttribute]}items.push(injectedItem)}catch(err){options.errorFn(err,"Failed to inject "+def.type+' relation: "'+relationName+'"!')}}})})()}else{if(toInject!==_this.s[relationName].index[toInject[relationDef.idAttribute]]){try{var _injected=_this.inject(relationName,attrs[def.localField],options.orig());if(def.foreignKey){_injected[def.foreignKey]=attrs[definition.idAttribute]}}catch(err){options.errorFn(err,"Failed to inject "+def.type+' relation: "'+relationName+'"!')}}}}});var id=attrs[idA];var item=_this.get(definition.n,id);var initialLastModified=item?resource.modified[id]:0;if(!item){if(attrs instanceof definition[definition["class"]]){item=attrs}else{item=new definition[definition["class"]]()}_DSUtils["default"].forEach(definition.relationList,function(def){delete attrs[def.localField]});_DSUtils["default"].deepMixIn(item,attrs);resource.collection.push(item);resource.changeHistories[id]=[];if(_DSUtils["default"].w){resource.observers[id]=new _this.observe.ObjectObserver(item);resource.observers[id].open(_react,item)}resource.index[id]=item;_react.call(item,{},{},{},null,true);resource.previousAttributes[id]=_DSUtils["default"].copy(item,null,null,null,definition.relationFields)}else{_DSUtils["default"].deepMixIn(item,attrs);if(definition.resetHistoryOnInject){resource.previousAttributes[id]=_DSUtils["default"].copy(item,null,null,null,definition.relationFields);if(resource.changeHistories[id].length){_DSUtils["default"].forEach(resource.changeHistories[id],function(changeRecord){_DSUtils["default"].remove(resource.changeHistory,changeRecord)});resource.changeHistories[id].splice(0,resource.changeHistories[id].length)}}if(_DSUtils["default"].w){resource.observers[id].deliver()}}resource.modified[id]=initialLastModified&&resource.modified[id]===initialLastModified?_DSUtils["default"].updateTimestamp(resource.modified[id]):resource.modified[id];resource.expiresHeap.remove(item);var timestamp=new Date().getTime();resource.expiresHeap.push({item:item,timestamp:timestamp,expires:definition.maxAge?timestamp+definition.maxAge:Number.MAX_VALUE});injected=item}catch(err){options.errorFn(err,attrs)}}}return injected}function inject(resourceName,attrs,options){var _this=this;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var injected=undefined;if(!definition){throw new _DSErrors["default"].NER(resourceName)}else{if(!_DSUtils["default"]._o(attrs)&&!_DSUtils["default"]._a(attrs)){throw new _DSErrors["default"].IA(""+resourceName+'.inject: "attrs" must be an object or an array!')}}options=_DSUtils["default"]._(definition,options);options.logFn("inject",attrs,options);options.beforeInject(options,attrs);if(options.notify){definition.emit("DS.beforeInject",definition,attrs)}injected=_inject.call(_this,definition,resource,attrs,options);resource.collectionModified=_DSUtils["default"].updateTimestamp(resource.collectionModified);options.afterInject(options,injected);if(options.notify){definition.emit("DS.afterInject",definition,injected)}return injected}},function(module,exports,__webpack_require__){exports["default"]=create;function create(resourceName,attrs,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];options=options||{};attrs=attrs||{};var rejectionError=undefined;if(!definition){rejectionError=new _this.errors.NER(resourceName)}else{if(!DSUtils._o(attrs)){rejectionError=DSUtils._oErr("attrs")}else{options=DSUtils._(definition,options);if(options.upsert&&DSUtils._sn(attrs[definition.idAttribute])){return _this.update(resourceName,attrs[definition.idAttribute],attrs,options)}options.logFn("create",attrs,options)}}return new DSUtils.Promise(function(resolve,reject){if(rejectionError){reject(rejectionError)}else{resolve(attrs)}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeCreate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeCreate",definition,attrs)}return _this.getAdapter(options).create(definition,attrs,options)}).then(function(attrs){return options.afterCreate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.afterCreate",definition,attrs)}if(options.cacheResponse){var created=_this.inject(definition.n,attrs,options.orig());var id=created[definition.idAttribute];var resource=_this.s[resourceName];resource.completedQueries[id]=new Date().getTime();resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);return created}else{return _this.createInstance(resourceName,attrs,options)}})}},function(module,exports,__webpack_require__){exports["default"]=destroy;function destroy(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var item=undefined;return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{item=_this.get(resourceName,id)||{id:id};options=DSUtils._(definition,options);options.logFn("destroy",id,options);resolve(item)}}}).then(function(attrs){return options.beforeDestroy.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeDestroy",definition,attrs)}if(options.eagerEject){_this.eject(resourceName,id)}return _this.getAdapter(options).destroy(definition,id,options)}).then(function(){return options.afterDestroy.call(item,options,item)}).then(function(item){if(options.notify){definition.emit("DS.afterDestroy",definition,item)}_this.eject(resourceName,id);return id})["catch"](function(err){if(options&&options.eagerEject&&item){_this.inject(resourceName,item,{notify:false})}return DSUtils.Promise.reject(err)})}},function(module,exports,__webpack_require__){exports["default"]=destroyAll;function destroyAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var ejected=undefined,toEject=undefined;params=params||{};return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._o(params)){reject(DSUtils._oErr("attrs"))}else{options=DSUtils._(definition,options);options.logFn("destroyAll",params,options);resolve()}}}).then(function(){toEject=_this.defaults.defaultFilter.call(_this,resourceName,params);return options.beforeDestroy(options,toEject)}).then(function(){if(options.notify){definition.emit("DS.beforeDestroy",definition,toEject)}if(options.eagerEject){ejected=_this.ejectAll(resourceName,params)}return _this.getAdapter(options).destroyAll(definition,params,options)}).then(function(){return options.afterDestroy(options,toEject)}).then(function(){if(options.notify){definition.emit("DS.afterDestroy",definition,toEject)}return ejected||_this.ejectAll(resourceName,params)})["catch"](function(err){if(options&&options.eagerEject&&ejected){_this.inject(resourceName,ejected,{notify:false})}return DSUtils.Promise.reject(err)})}},function(module,exports,__webpack_require__){exports["default"]=find;function find(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.logFn("find",id,options);if(options.params){options.params=DSUtils.copy(options.params)}if(options.bypassCache||!options.cacheResponse){delete resource.completedQueries[id]}if((!options.findStrictCache||id in resource.completedQueries)&&_this.get(resourceName,id)&&!options.bypassCache){resolve(_this.get(resourceName,id))}else{delete resource.completedQueries[id];resolve()}}}}).then(function(item){if(!item){if(!(id in resource.pendingQueries)){var promise=undefined;var strategy=options.findStrategy||options.strategy;if(strategy==="fallback"){(function(){var makeFallbackCall=function(index){return _this.getAdapter((options.findFallbackAdapters||options.fallbackAdapters)[index]).find(definition,id,options)["catch"](function(err){index++;if(index<options.fallbackAdapters.length){return makeFallbackCall(index)}else{return DSUtils.Promise.reject(err)}})};promise=makeFallbackCall(0)})()}else{promise=_this.getAdapter(options).find(definition,id,options)}resource.pendingQueries[id]=promise.then(function(data){delete resource.pendingQueries[id];if(options.cacheResponse){var injected=_this.inject(resourceName,data,options.orig());resource.completedQueries[id]=new Date().getTime();resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);return injected}else{return _this.createInstance(resourceName,data,options.orig())}})}return resource.pendingQueries[id]}else{return item}})["catch"](function(err){if(resource){delete resource.pendingQueries[id]}return DSUtils.Promise.reject(err)})}},function(module,exports,__webpack_require__){exports["default"]=findAll;function processResults(data,resourceName,queryHash,options){var _this=this;var DSUtils=_this.utils;var resource=_this.s[resourceName];var idAttribute=_this.defs[resourceName].idAttribute;var date=new Date().getTime();data=data||[];delete resource.pendingQueries[queryHash];resource.completedQueries[queryHash]=date;resource.collectionModified=DSUtils.updateTimestamp(resource.collectionModified);var injected=_this.inject(resourceName,data,options.orig());if(DSUtils._a(injected)){DSUtils.forEach(injected,function(item){if(item){var id=item[idAttribute];if(id){resource.completedQueries[id]=date;resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id])}}})}else{options.errorFn("response is expected to be an array!");resource.completedQueries[injected[idAttribute]]=date}return injected}function findAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var queryHash=undefined;return new DSUtils.Promise(function(resolve,reject){params=params||{};if(!_this.defs[resourceName]){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._o(params)){reject(DSUtils._oErr("params"))}else{options=DSUtils._(definition,options);queryHash=DSUtils.toJson(params);options.logFn("findAll",params,options);if(options.params){options.params=DSUtils.copy(options.params)}if(options.bypassCache||!options.cacheResponse){delete resource.completedQueries[queryHash];delete resource.queryData[queryHash]}if(queryHash in resource.completedQueries){if(options.useFilter){resolve(_this.filter(resourceName,params,options.orig()))}else{resolve(resource.queryData[queryHash])}}else{resolve()}}}}).then(function(items){if(!(queryHash in resource.completedQueries)){if(!(queryHash in resource.pendingQueries)){var promise=undefined;var strategy=options.findAllStrategy||options.strategy;if(strategy==="fallback"){(function(){var makeFallbackCall=function(index){return _this.getAdapter((options.findAllFallbackAdapters||options.fallbackAdapters)[index]).findAll(definition,params,options)["catch"](function(err){index++;if(index<options.fallbackAdapters.length){return makeFallbackCall(index)}else{return DSUtils.Promise.reject(err)}})};promise=makeFallbackCall(0)})()}else{promise=_this.getAdapter(options).findAll(definition,params,options)}resource.pendingQueries[queryHash]=promise.then(function(data){delete resource.pendingQueries[queryHash];if(options.cacheResponse){resource.queryData[queryHash]=processResults.call(_this,data,resourceName,queryHash,options);resource.queryData[queryHash].$$injected=true;return resource.queryData[queryHash]}else{DSUtils.forEach(data,function(item,i){data[i]=_this.createInstance(resourceName,item,options.orig())});return data}})}return resource.pendingQueries[queryHash]}else{return items}})["catch"](function(err){if(resource){delete resource.pendingQueries[queryHash]}return DSUtils.Promise.reject(err)})}},function(module,exports,__webpack_require__){var _defineProperty=function(obj,key,value){return Object.defineProperty(obj,key,{value:value,enumerable:key==null||typeof Symbol=="undefined"||key.constructor!==Symbol,configurable:true,writable:true})};exports["default"]=loadRelations;function loadRelations(resourceName,instance,relations,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];return new DSUtils.Promise(function(resolve,reject){if(DSUtils._sn(instance)){instance=_this.get(resourceName,instance)}if(DSUtils._s(relations)){relations=[relations]}if(!definition){reject(new DSErrors.NER(resourceName))}else{if(!DSUtils._o(instance)){reject(new DSErrors.IA('"instance(id)" must be a string, number or object!'))}else{if(!DSUtils._a(relations)){reject(new DSErrors.IA('"relations" must be a string or an array!'))}else{(function(){var _options=DSUtils._(definition,options);if(!_options.hasOwnProperty("findBelongsTo")){_options.findBelongsTo=true}if(!_options.hasOwnProperty("findHasMany")){_options.findHasMany=true}_options.logFn("loadRelations",instance,relations,_options);var tasks=[];DSUtils.forEach(definition.relationList,function(def){var relationName=def.relation;var relationDef=definition.getResource(relationName);var __options=DSUtils._(relationDef,options);if(DSUtils.contains(relations,relationName)||DSUtils.contains(relations,def.localField)){var task=undefined;var params={};if(__options.allowSimpleWhere){params[def.foreignKey]=instance[definition.idAttribute]}else{params.where={};params.where[def.foreignKey]={"==":instance[definition.idAttribute]}}if(def.type==="hasMany"){if(def.localKeys){delete params[def.foreignKey];params.where=_defineProperty({},relationDef.idAttribute,{"in":instance[def.localKeys]})}task=_this.findAll(relationName,params,__options.orig())}else{if(def.type==="hasOne"){if(def.localKey&&instance[def.localKey]){task=_this.find(relationName,instance[def.localKey],__options.orig())}else{if(def.foreignKey){task=_this.findAll(relationName,params,__options.orig()).then(function(hasOnes){return hasOnes.length?hasOnes[0]:null})}}}else{if(instance[def.localKey]){task=_this.find(relationName,instance[def.localKey],__options.orig())}}}if(task){tasks.push(task)}}});resolve(tasks)})()}}}}).then(function(tasks){return DSUtils.Promise.all(tasks)}).then(function(){return instance})}},function(module,exports,__webpack_require__){exports["default"]=reap;function reap(resourceName,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else{options=DSUtils._(definition,options);if(!options.hasOwnProperty("notify")){options.notify=false}options.logFn("reap",options);var items=[];var now=new Date().getTime();var expiredItem=undefined;while((expiredItem=resource.expiresHeap.peek())&&expiredItem.expires<now){items.push(expiredItem.item);delete expiredItem.item;resource.expiresHeap.pop()}resolve(items)}}).then(function(items){if(options.isInterval||options.notify){definition.beforeReap(options,items);definition.emit("DS.beforeReap",definition,items)}if(options.reapAction==="inject"){(function(){var timestamp=new Date().getTime();DSUtils.forEach(items,function(item){resource.expiresHeap.push({item:item,timestamp:timestamp,expires:definition.maxAge?timestamp+definition.maxAge:Number.MAX_VALUE})})})()}else{if(options.reapAction==="eject"){DSUtils.forEach(items,function(item){_this.eject(resourceName,item[definition.idAttribute])})}else{if(options.reapAction==="refresh"){var _ret2=(function(){var tasks=[];DSUtils.forEach(items,function(item){tasks.push(_this.refresh(resourceName,item[definition.idAttribute]))});return{v:DSUtils.Promise.all(tasks)}})();if(typeof _ret2==="object"){return _ret2.v}}}}return items}).then(function(items){if(options.isInterval||options.notify){definition.afterReap(options,items);definition.emit("DS.afterReap",definition,items)}return items})}},function(module,exports,__webpack_require__){exports["default"]=save;function save(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];var item=undefined;var noChanges=undefined;return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new DSErrors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{if(!_this.get(resourceName,id)){reject(new DSErrors.R('id "'+id+'" not found in cache!'))}else{item=_this.get(resourceName,id);options=DSUtils._(definition,options);options.logFn("save",id,options);resolve(item)}}}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}if(options.changesOnly){var resource=_this.s[resourceName];if(DSUtils.w){resource.observers[id].deliver()}var toKeep=[];var changes=_this.changes(resourceName,id);for(var key in changes.added){toKeep.push(key)}for(key in changes.changed){toKeep.push(key)}changes=DSUtils.pick(attrs,toKeep);if(DSUtils.isEmpty(changes)){options.logFn("save - no changes",id,options);noChanges=true;return attrs}else{attrs=changes}}return _this.getAdapter(options).update(definition,id,attrs,options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(attrs){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}if(noChanges){return attrs}else{if(options.cacheResponse){var injected=_this.inject(definition.n,attrs,options.orig());var resource=_this.s[resourceName];var _id=injected[definition.idAttribute];resource.saved[_id]=DSUtils.updateTimestamp(resource.saved[_id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[_id]=DSUtils.copy(injected,null,null,null,definition.relationFields)}return injected}else{return _this.createInstance(resourceName,attrs,options.orig())}}})}},function(module,exports,__webpack_require__){exports["default"]=update;function update(resourceName,id,attrs,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new DSErrors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.logFn("update",id,attrs,options);resolve(attrs)}}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}return _this.getAdapter(options).update(definition,id,attrs,options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(attrs){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}if(options.cacheResponse){var injected=_this.inject(definition.n,attrs,options.orig());var resource=_this.s[resourceName];var _id=injected[definition.idAttribute];resource.saved[_id]=DSUtils.updateTimestamp(resource.saved[_id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[_id]=DSUtils.copy(injected,null,null,null,definition.relationFields)}return injected}else{return _this.createInstance(resourceName,attrs,options.orig())}})}},function(module,exports,__webpack_require__){exports["default"]=updateAll;function updateAll(resourceName,attrs,params,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new DSErrors.NER(resourceName))}else{options=DSUtils._(definition,options);options.logFn("updateAll",attrs,params,options);resolve(attrs)}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}return _this.getAdapter(options).updateAll(definition,attrs,params,options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(data){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}var origOptions=options.orig();if(options.cacheResponse){var _ret=(function(){var injected=_this.inject(definition.n,data,origOptions);var resource=_this.s[resourceName];DSUtils.forEach(injected,function(i){var id=i[definition.idAttribute];resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[id]=DSUtils.copy(i,null,null,null,definition.relationFields)}});return{v:injected}})();if(typeof _ret==="object"){return _ret.v}}else{var _ret2=(function(){var instances=[];DSUtils.forEach(data,function(item){instances.push(_this.createInstance(resourceName,item,origOptions))});return{v:instances}})();if(typeof _ret2==="object"){return _ret2.v}}})}},function(module,exports,__webpack_require__){var toString=__webpack_require__(26);function replaceAccents(str){str=toString(str);if(str.search(/[\xC0-\xFF]/g)>-1){str=str.replace(/[\xC0-\xC5]/g,"A").replace(/[\xC6]/g,"AE").replace(/[\xC7]/g,"C").replace(/[\xC8-\xCB]/g,"E").replace(/[\xCC-\xCF]/g,"I").replace(/[\xD0]/g,"D").replace(/[\xD1]/g,"N").replace(/[\xD2-\xD6\xD8]/g,"O").replace(/[\xD9-\xDC]/g,"U").replace(/[\xDD]/g,"Y").replace(/[\xDE]/g,"P").replace(/[\xE0-\xE5]/g,"a").replace(/[\xE6]/g,"ae").replace(/[\xE7]/g,"c").replace(/[\xE8-\xEB]/g,"e").replace(/[\xEC-\xEF]/g,"i").replace(/[\xF1]/g,"n").replace(/[\xF2-\xF6\xF8]/g,"o").replace(/[\xF9-\xFC]/g,"u").replace(/[\xFE]/g,"p").replace(/[\xFD\xFF]/g,"y")}return str}module.exports=replaceAccents},function(module,exports,__webpack_require__){var toString=__webpack_require__(26);var PATTERN=/[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g;function removeNonWord(str){str=toString(str);return str.replace(PATTERN,"")}module.exports=removeNonWord},function(module,exports,__webpack_require__){var toString=__webpack_require__(26);function lowerCase(str){str=toString(str);return str.toLowerCase()}module.exports=lowerCase}])});
modules/react-move/src/components/Move.js
Scratch-it/react-color
'use strict'; import React from 'react'; import ReactCSS from 'reactcss'; export class Move extends ReactCSS.Component { classes() { return { 'default': { outer: { opacity: this.props.inStartOpacity, transform: this.props.inStartTransform, transition: this.props.inStartTransition, }, }, }; } componentDidMount() { var animate = this.refs.outer; setTimeout((function() { animate.style.opacity = this.props.inEndOpacity; animate.style.transform = this.props.inEndTransform; animate.style.transition = this.props.inEndTransition; }).bind(this), this.props.inDelay); } render() { return ( <div is="outer" ref="outer" className="foobarbaz">{ this.props.children }</div> ); } } Move.defaultProps = { inStartOpacity: '0', inStartTransform: '', inStartTransition: 'all 400ms cubic-bezier(.55,0,.1,1)', inEndOpacity: '1', inEndTransform: '', inEndTransition: 'all 400ms cubic-bezier(.55,0,.1,1)', inDelay: 0, }; export default Move;
ajax/libs/react/0.11.0-rc1/react.min.js
Download/cdnjs
/** * React v0.11.0-rc1 * * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.React=e()}}(function(){return function e(t,n,r){function o(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);throw new Error("Cannot find module '"+a+"'")}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t){"use strict";var n=e("./focusNode"),r={componentDidMount:function(){this.props.autoFocus&&n(this.getDOMNode())}};t.exports=r},{"./focusNode":104}],2:[function(e,t){"use strict";function n(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function r(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}var o=e("./EventConstants"),i=e("./EventPropagators"),a=e("./ExecutionEnvironment"),s=e("./SyntheticInputEvent"),u=e("./keyOf"),c=a.canUseDOM&&"TextEvent"in window&&!("documentMode"in document||n()),l=32,p=String.fromCharCode(l),d=o.topLevelTypes,f={beforeInput:{phasedRegistrationNames:{bubbled:u({onBeforeInput:null}),captured:u({onBeforeInputCapture:null})},dependencies:[d.topCompositionEnd,d.topKeyPress,d.topTextInput,d.topPaste]}},h=null,v={eventTypes:f,extractEvents:function(e,t,n,o){var a;if(c)switch(e){case d.topKeyPress:var u=o.which;if(u!==l)return;a=String.fromCharCode(u);break;case d.topTextInput:if(a=o.data,a===p)return;break;default:return}else{switch(e){case d.topPaste:h=null;break;case d.topKeyPress:o.which&&!r(o)&&(h=String.fromCharCode(o.which));break;case d.topCompositionEnd:h=o.data}if(null===h)return;a=h}if(a){var v=s.getPooled(f.beforeInput,n,o);return v.data=a,h=null,i.accumulateTwoPhaseDispatches(v),v}}};t.exports=v},{"./EventConstants":15,"./EventPropagators":20,"./ExecutionEnvironment":21,"./SyntheticInputEvent":84,"./keyOf":125}],3:[function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={columnCount:!0,fillOpacity:!0,flex:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},o=["Webkit","ms","Moz","O"];Object.keys(r).forEach(function(e){o.forEach(function(t){r[n(t,e)]=r[e]})});var i={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},a={isUnitlessNumber:r,shorthandPropertyExpansions:i};t.exports=a},{}],4:[function(e,t){"use strict";var n=e("./CSSProperty"),r=e("./dangerousStyleValue"),o=e("./hyphenateStyleName"),i=e("./memoizeStringOnly"),a=i(function(e){return o(e)}),s={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];null!=o&&(t+=a(n)+":",t+=r(n,o)+";")}return t||null},setValueForStyles:function(e,t){var o=e.style;for(var i in t)if(t.hasOwnProperty(i)){var a=r(i,t[i]);if(a)o[i]=a;else{var s=n.shorthandPropertyExpansions[i];if(s)for(var u in s)o[u]="";else o[i]=""}}}};t.exports=s},{"./CSSProperty":3,"./dangerousStyleValue":99,"./hyphenateStyleName":116,"./memoizeStringOnly":127}],5:[function(e,t){"use strict";function n(){this._callbacks=null,this._contexts=null}var r=e("./PooledClass"),o=e("./invariant"),i=e("./mixInto");i(n,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){o(e.length===t.length),this._callbacks=null,this._contexts=null;for(var n=0,r=e.length;r>n;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{"./PooledClass":26,"./invariant":118,"./mixInto":131}],6:[function(e,t){"use strict";function n(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function r(e){var t=M.getPooled(P.change,_,e);C.accumulateTwoPhaseDispatches(t),R.batchedUpdates(o,t)}function o(e){y.enqueueEvents(e),y.processEventQueue()}function i(e,t){I=e,_=t,I.attachEvent("onchange",r)}function a(){I&&(I.detachEvent("onchange",r),I=null,_=null)}function s(e,t,n){return e===O.topChange?n:void 0}function u(e,t,n){e===O.topFocus?(a(),i(t,n)):e===O.topBlur&&a()}function c(e,t){I=e,_=t,T=e.value,N=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(I,"value",A),I.attachEvent("onpropertychange",p)}function l(){I&&(delete I.value,I.detachEvent("onpropertychange",p),I=null,_=null,T=null,N=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==T&&(T=t,r(e))}}function d(e,t,n){return e===O.topInput?n:void 0}function f(e,t,n){e===O.topFocus?(l(),c(t,n)):e===O.topBlur&&l()}function h(e){return e!==O.topSelectionChange&&e!==O.topKeyUp&&e!==O.topKeyDown||!I||I.value===T?void 0:(T=I.value,_)}function v(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function m(e,t,n){return e===O.topClick?n:void 0}var g=e("./EventConstants"),y=e("./EventPluginHub"),C=e("./EventPropagators"),E=e("./ExecutionEnvironment"),R=e("./ReactUpdates"),M=e("./SyntheticEvent"),D=e("./isEventSupported"),x=e("./isTextInputElement"),b=e("./keyOf"),O=g.topLevelTypes,P={change:{phasedRegistrationNames:{bubbled:b({onChange:null}),captured:b({onChangeCapture:null})},dependencies:[O.topBlur,O.topChange,O.topClick,O.topFocus,O.topInput,O.topKeyDown,O.topKeyUp,O.topSelectionChange]}},I=null,_=null,T=null,N=null,w=!1;E.canUseDOM&&(w=D("change")&&(!("documentMode"in document)||document.documentMode>8));var S=!1;E.canUseDOM&&(S=D("input")&&(!("documentMode"in document)||document.documentMode>9));var A={get:function(){return N.get.call(this)},set:function(e){T=""+e,N.set.call(this,e)}},k={eventTypes:P,extractEvents:function(e,t,r,o){var i,a;if(n(t)?w?i=s:a=u:x(t)?S?i=d:(i=h,a=f):v(t)&&(i=m),i){var c=i(e,t,r);if(c){var l=M.getPooled(P.change,c,o);return C.accumulateTwoPhaseDispatches(l),l}}a&&a(e,t,r)}};t.exports=k},{"./EventConstants":15,"./EventPluginHub":17,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactUpdates":74,"./SyntheticEvent":82,"./isEventSupported":119,"./isTextInputElement":121,"./keyOf":125}],7:[function(e,t){"use strict";var n=0,r={createReactRootIndex:function(){return n++}};t.exports=r},{}],8:[function(e,t){"use strict";function n(e){switch(e){case g.topCompositionStart:return C.compositionStart;case g.topCompositionEnd:return C.compositionEnd;case g.topCompositionUpdate:return C.compositionUpdate}}function r(e,t){return e===g.topKeyDown&&t.keyCode===h}function o(e,t){switch(e){case g.topKeyUp:return-1!==f.indexOf(t.keyCode);case g.topKeyDown:return t.keyCode!==h;case g.topKeyPress:case g.topMouseDown:case g.topBlur:return!0;default:return!1}}function i(e){this.root=e,this.startSelection=c.getSelection(e),this.startValue=this.getText()}var a=e("./EventConstants"),s=e("./EventPropagators"),u=e("./ExecutionEnvironment"),c=e("./ReactInputSelection"),l=e("./SyntheticCompositionEvent"),p=e("./getTextContentAccessor"),d=e("./keyOf"),f=[9,13,27,32],h=229,v=u.canUseDOM&&"CompositionEvent"in window,m=!v||"documentMode"in document&&document.documentMode>8&&document.documentMode<=11,g=a.topLevelTypes,y=null,C={compositionEnd:{phasedRegistrationNames:{bubbled:d({onCompositionEnd:null}),captured:d({onCompositionEndCapture:null})},dependencies:[g.topBlur,g.topCompositionEnd,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:d({onCompositionStart:null}),captured:d({onCompositionStartCapture:null})},dependencies:[g.topBlur,g.topCompositionStart,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:d({onCompositionUpdate:null}),captured:d({onCompositionUpdateCapture:null})},dependencies:[g.topBlur,g.topCompositionUpdate,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]}};i.prototype.getText=function(){return this.root.value||this.root[p()]},i.prototype.getData=function(){var e=this.getText(),t=this.startSelection.start,n=this.startValue.length-this.startSelection.end;return e.substr(t,e.length-n-t)};var E={eventTypes:C,extractEvents:function(e,t,a,u){var c,p;if(v?c=n(e):y?o(e,u)&&(c=C.compositionEnd):r(e,u)&&(c=C.compositionStart),m&&(y||c!==C.compositionStart?c===C.compositionEnd&&y&&(p=y.getData(),y=null):y=new i(t)),c){var d=l.getPooled(c,a,u);return p&&(d.data=p),s.accumulateTwoPhaseDispatches(d),d}}};t.exports=E},{"./EventConstants":15,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactInputSelection":56,"./SyntheticCompositionEvent":80,"./getTextContentAccessor":113,"./keyOf":125}],9:[function(e,t){"use strict";function n(e,t,n){e.insertBefore(t,e.childNodes[n]||null)}var r,o=e("./Danger"),i=e("./ReactMultiChildUpdateTypes"),a=e("./getTextContentAccessor"),s=e("./invariant"),u=a();r="textContent"===u?function(e,t){e.textContent=t}:function(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);if(t){var n=e.ownerDocument||document;e.appendChild(n.createTextNode(t))}};var c={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:r,processUpdates:function(e,t){for(var a,u=null,c=null,l=0;a=e[l];l++)if(a.type===i.MOVE_EXISTING||a.type===i.REMOVE_NODE){var p=a.fromIndex,d=a.parentNode.childNodes[p],f=a.parentID;s(d),u=u||{},u[f]=u[f]||[],u[f][p]=d,c=c||[],c.push(d)}var h=o.dangerouslyRenderMarkup(t);if(c)for(var v=0;v<c.length;v++)c[v].parentNode.removeChild(c[v]);for(var m=0;a=e[m];m++)switch(a.type){case i.INSERT_MARKUP:n(a.parentNode,h[a.markupIndex],a.toIndex);break;case i.MOVE_EXISTING:n(a.parentNode,u[a.parentID][a.fromIndex],a.toIndex);break;case i.TEXT_CONTENT:r(a.parentNode,a.textContent);break;case i.REMOVE_NODE:}}};t.exports=c},{"./Danger":12,"./ReactMultiChildUpdateTypes":61,"./getTextContentAccessor":113,"./invariant":118}],10:[function(e,t){"use strict";var n=e("./invariant"),r={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=e.Properties||{},o=e.DOMAttributeNames||{},a=e.DOMPropertyNames||{},s=e.DOMMutationMethods||{};e.isCustomAttribute&&i._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var u in t){n(!i.isStandardName.hasOwnProperty(u)),i.isStandardName[u]=!0;var c=u.toLowerCase();if(i.getPossibleStandardName[c]=u,o.hasOwnProperty(u)){var l=o[u];i.getPossibleStandardName[l]=u,i.getAttributeName[u]=l}else i.getAttributeName[u]=c;i.getPropertyName[u]=a.hasOwnProperty(u)?a[u]:u,i.getMutationMethod[u]=s.hasOwnProperty(u)?s[u]:null;var p=t[u];i.mustUseAttribute[u]=p&r.MUST_USE_ATTRIBUTE,i.mustUseProperty[u]=p&r.MUST_USE_PROPERTY,i.hasSideEffects[u]=p&r.HAS_SIDE_EFFECTS,i.hasBooleanValue[u]=p&r.HAS_BOOLEAN_VALUE,i.hasNumericValue[u]=p&r.HAS_NUMERIC_VALUE,i.hasPositiveNumericValue[u]=p&r.HAS_POSITIVE_NUMERIC_VALUE,i.hasOverloadedBooleanValue[u]=p&r.HAS_OVERLOADED_BOOLEAN_VALUE,n(!i.mustUseAttribute[u]||!i.mustUseProperty[u]),n(i.mustUseProperty[u]||!i.hasSideEffects[u]),n(!!i.hasBooleanValue[u]+!!i.hasNumericValue[u]+!!i.hasOverloadedBooleanValue[u]<=1)}}},o={},i={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<i._isCustomAttributeFunctions.length;t++){var n=i._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=o[e];return r||(o[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:r};t.exports=i},{"./invariant":118}],11:[function(e,t){"use strict";function n(e,t){return null==t||r.hasBooleanValue[e]&&!t||r.hasNumericValue[e]&&isNaN(t)||r.hasPositiveNumericValue[e]&&1>t||r.hasOverloadedBooleanValue[e]&&t===!1}var r=e("./DOMProperty"),o=e("./escapeTextForBrowser"),i=e("./memoizeStringOnly"),a=(e("./warning"),i(function(e){return o(e)+'="'})),s={createMarkupForID:function(e){return a(r.ID_ATTRIBUTE_NAME)+o(e)+'"'},createMarkupForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(e)&&r.isStandardName[e]){if(n(e,t))return"";var i=r.getAttributeName[e];return r.hasBooleanValue[e]||r.hasOverloadedBooleanValue[e]&&t===!0?o(i):a(i)+o(t)+'"'}return r.isCustomAttribute(e)?null==t?"":a(e)+o(t)+'"':null},setValueForProperty:function(e,t,o){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var i=r.getMutationMethod[t];if(i)i(e,o);else if(n(t,o))this.deleteValueForProperty(e,t);else if(r.mustUseAttribute[t])e.setAttribute(r.getAttributeName[t],""+o);else{var a=r.getPropertyName[t];r.hasSideEffects[t]&&e[a]===o||(e[a]=o)}}else r.isCustomAttribute(t)&&(null==o?e.removeAttribute(t):e.setAttribute(t,""+o))},deleteValueForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var n=r.getMutationMethod[t];if(n)n(e,void 0);else if(r.mustUseAttribute[t])e.removeAttribute(r.getAttributeName[t]);else{var o=r.getPropertyName[t],i=r.getDefaultValueForProperty(e.nodeName,o);r.hasSideEffects[t]&&e[o]===i||(e[o]=i)}}else r.isCustomAttribute(t)&&e.removeAttribute(t)}};t.exports=s},{"./DOMProperty":10,"./escapeTextForBrowser":102,"./memoizeStringOnly":127,"./warning":139}],12:[function(e,t){"use strict";function n(e){return e.substring(1,e.indexOf(" "))}var r=e("./ExecutionEnvironment"),o=e("./createNodesFromMarkup"),i=e("./emptyFunction"),a=e("./getMarkupWrap"),s=e("./invariant"),u=/^(<[^ \/>]+)/,c="data-danger-index",l={dangerouslyRenderMarkup:function(e){s(r.canUseDOM);for(var t,l={},p=0;p<e.length;p++)s(e[p]),t=n(e[p]),t=a(t)?t:"*",l[t]=l[t]||[],l[t][p]=e[p];var d=[],f=0;for(t in l)if(l.hasOwnProperty(t)){var h=l[t];for(var v in h)if(h.hasOwnProperty(v)){var m=h[v];h[v]=m.replace(u,"$1 "+c+'="'+v+'" ')}var g=o(h.join(""),i);for(p=0;p<g.length;++p){var y=g[p];y.hasAttribute&&y.hasAttribute(c)&&(v=+y.getAttribute(c),y.removeAttribute(c),s(!d.hasOwnProperty(v)),d[v]=y,f+=1)}}return s(f===d.length),s(d.length===e.length),d},dangerouslyReplaceNodeWithMarkup:function(e,t){s(r.canUseDOM),s(t),s("html"!==e.tagName.toLowerCase());var n=o(t,i)[0];e.parentNode.replaceChild(n,e)}};t.exports=l},{"./ExecutionEnvironment":21,"./createNodesFromMarkup":98,"./emptyFunction":100,"./getMarkupWrap":110,"./invariant":118}],13:[function(e,t){"use strict";var n=e("./keyOf"),r=[n({ResponderEventPlugin:null}),n({SimpleEventPlugin:null}),n({TapEventPlugin:null}),n({EnterLeaveEventPlugin:null}),n({ChangeEventPlugin:null}),n({SelectEventPlugin:null}),n({CompositionEventPlugin:null}),n({BeforeInputEventPlugin:null}),n({AnalyticsEventPlugin:null}),n({MobileSafariClickEventPlugin:null})];t.exports=r},{"./keyOf":125}],14:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./EventPropagators"),o=e("./SyntheticMouseEvent"),i=e("./ReactMount"),a=e("./keyOf"),s=n.topLevelTypes,u=i.getFirstReactDOM,c={mouseEnter:{registrationName:a({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:a({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},l=[null,null],p={eventTypes:c,extractEvents:function(e,t,n,a){if(e===s.topMouseOver&&(a.relatedTarget||a.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var p;if(t.window===t)p=t;else{var d=t.ownerDocument;p=d?d.defaultView||d.parentWindow:window}var f,h;if(e===s.topMouseOut?(f=t,h=u(a.relatedTarget||a.toElement)||p):(f=p,h=t),f===h)return null;var v=f?i.getID(f):"",m=h?i.getID(h):"",g=o.getPooled(c.mouseLeave,v,a);g.type="mouseleave",g.target=f,g.relatedTarget=h;var y=o.getPooled(c.mouseEnter,m,a);return y.type="mouseenter",y.target=h,y.relatedTarget=f,r.accumulateEnterLeaveDispatches(g,y,v,m),l[0]=g,l[1]=y,l}};t.exports=p},{"./EventConstants":15,"./EventPropagators":20,"./ReactMount":59,"./SyntheticMouseEvent":86,"./keyOf":125}],15:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({bubbled:null,captured:null}),o=n({topBlur:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topReset:null,topScroll:null,topSelectionChange:null,topSubmit:null,topTextInput:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),i={topLevelTypes:o,PropagationPhases:r};t.exports=i},{"./keyMirror":124}],16:[function(e,t){var n=e("./emptyFunction"),r={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,r){return e.addEventListener?(e.addEventListener(t,r,!0),{remove:function(){e.removeEventListener(t,r,!0)}}):{remove:n}},registerDefault:function(){}};t.exports=r},{"./emptyFunction":100}],17:[function(e,t){"use strict";var n=e("./EventPluginRegistry"),r=e("./EventPluginUtils"),o=e("./accumulate"),i=e("./forEachAccumulated"),a=e("./invariant"),s=(e("./isEventSupported"),e("./monitorCodeUse"),{}),u=null,c=function(e){if(e){var t=r.executeDispatch,o=n.getPluginModuleForEvent(e);o&&o.executeDispatch&&(t=o.executeDispatch),r.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},l=null,p={injection:{injectMount:r.injection.injectMount,injectInstanceHandle:function(e){l=e},getInstanceHandle:function(){return l},injectEventPluginOrder:n.injectEventPluginOrder,injectEventPluginsByName:n.injectEventPluginsByName},eventNameDispatchConfigs:n.eventNameDispatchConfigs,registrationNameModules:n.registrationNameModules,putListener:function(e,t,n){a(!n||"function"==typeof n);var r=s[t]||(s[t]={});r[e]=n},getListener:function(e,t){var n=s[t];return n&&n[e]},deleteListener:function(e,t){var n=s[t];n&&delete n[e]},deleteAllListeners:function(e){for(var t in s)delete s[t][e]},extractEvents:function(e,t,r,i){for(var a,s=n.plugins,u=0,c=s.length;c>u;u++){var l=s[u];if(l){var p=l.extractEvents(e,t,r,i);p&&(a=o(a,p))}}return a},enqueueEvents:function(e){e&&(u=o(u,e))},processEventQueue:function(){var e=u;u=null,i(e,c),a(!u)},__purge:function(){s={}},__getListenerBank:function(){return s}};t.exports=p},{"./EventPluginRegistry":18,"./EventPluginUtils":19,"./accumulate":92,"./forEachAccumulated":105,"./invariant":118,"./isEventSupported":119,"./monitorCodeUse":132}],18:[function(e,t){"use strict";function n(){if(a)for(var e in s){var t=s[e],n=a.indexOf(e);if(i(n>-1),!u.plugins[n]){i(t.extractEvents),u.plugins[n]=t;var o=t.eventTypes;for(var c in o)i(r(o[c],t,c))}}}function r(e,t,n){i(!u.eventNameDispatchConfigs.hasOwnProperty(n)),u.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var a in r)if(r.hasOwnProperty(a)){var s=r[a];o(s,t,n)}return!0}return e.registrationName?(o(e.registrationName,t,n),!0):!1}function o(e,t,n){i(!u.registrationNameModules[e]),u.registrationNameModules[e]=t,u.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var i=e("./invariant"),a=null,s={},u={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){i(!a),a=Array.prototype.slice.call(e),n()},injectEventPluginsByName:function(e){var t=!1;for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];s.hasOwnProperty(r)&&s[r]===o||(i(!s[r]),s[r]=o,t=!0)}t&&n()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return u.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=u.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){a=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];u.plugins.length=0;var t=u.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=u.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};t.exports=u},{"./invariant":118}],19:[function(e,t){"use strict";function n(e){return e===v.topMouseUp||e===v.topTouchEnd||e===v.topTouchCancel}function r(e){return e===v.topMouseMove||e===v.topTouchMove}function o(e){return e===v.topMouseDown||e===v.topTouchStart}function i(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)t(e,n[o],r[o]);else n&&t(e,n,r)}function a(e,t,n){e.currentTarget=h.Mount.getNode(n);var r=t(e,n);return e.currentTarget=null,r}function s(e,t){i(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function u(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=u(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function l(e){var t=e._dispatchListeners,n=e._dispatchIDs;f(!Array.isArray(t));var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function p(e){return!!e._dispatchListeners}var d=e("./EventConstants"),f=e("./invariant"),h={Mount:null,injectMount:function(e){h.Mount=e}},v=d.topLevelTypes,m={isEndish:n,isMoveish:r,isStartish:o,executeDirectDispatch:l,executeDispatch:a,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:c,hasDispatches:p,injection:h,useTouchEvents:!1};t.exports=m},{"./EventConstants":15,"./invariant":118}],20:[function(e,t){"use strict";function n(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return v(e,r)}function r(e,t,r){var o=t?h.bubbled:h.captured,i=n(e,r,o);i&&(r._dispatchListeners=d(r._dispatchListeners,i),r._dispatchIDs=d(r._dispatchIDs,e))}function o(e){e&&e.dispatchConfig.phasedRegistrationNames&&p.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,r,e)}function i(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=v(e,r);o&&(n._dispatchListeners=d(n._dispatchListeners,o),n._dispatchIDs=d(n._dispatchIDs,e))}}function a(e){e&&e.dispatchConfig.registrationName&&i(e.dispatchMarker,null,e)}function s(e){f(e,o)}function u(e,t,n,r){p.injection.getInstanceHandle().traverseEnterLeave(n,r,i,e,t)}function c(e){f(e,a)}var l=e("./EventConstants"),p=e("./EventPluginHub"),d=e("./accumulate"),f=e("./forEachAccumulated"),h=l.PropagationPhases,v=p.getListener,m={accumulateTwoPhaseDispatches:s,accumulateDirectDispatches:c,accumulateEnterLeaveDispatches:u};t.exports=m},{"./EventConstants":15,"./EventPluginHub":17,"./accumulate":92,"./forEachAccumulated":105}],21:[function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};t.exports=r},{}],22:[function(e,t){"use strict";var n,r=e("./DOMProperty"),o=e("./ExecutionEnvironment"),i=r.injection.MUST_USE_ATTRIBUTE,a=r.injection.MUST_USE_PROPERTY,s=r.injection.HAS_BOOLEAN_VALUE,u=r.injection.HAS_SIDE_EFFECTS,c=r.injection.HAS_NUMERIC_VALUE,l=r.injection.HAS_POSITIVE_NUMERIC_VALUE,p=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(o.canUseDOM){var d=document.implementation;n=d&&d.hasFeature&&d.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var f={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,accessKey:null,action:null,allowFullScreen:i|s,allowTransparency:i,alt:null,async:s,autoComplete:null,autoPlay:s,cellPadding:null,cellSpacing:null,charSet:i,checked:a|s,className:n?i:a,cols:i|l,colSpan:null,content:null,contentEditable:null,contextMenu:i,controls:a|s,coords:null,crossOrigin:null,data:null,dateTime:i,defer:s,dir:null,disabled:i|s,download:p,draggable:null,encType:null,form:i,formNoValidate:s,frameBorder:i,height:i,hidden:i|s,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:a,label:null,lang:null,list:null,loop:a|s,max:null,maxLength:i,mediaGroup:null,method:null,min:null,multiple:a|s,muted:a|s,name:null,noValidate:s,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:a|s,rel:null,required:s,role:i,rows:i|l,rowSpan:null,sandbox:null,scope:null,scrollLeft:a,scrolling:null,scrollTop:a,seamless:i|s,selected:a|s,shape:null,size:i|l,span:l,spellCheck:null,src:null,srcDoc:a,srcSet:null,start:c,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:a|u,width:i,wmode:i,autoCapitalize:null,autoCorrect:null,itemProp:i,itemScope:i|s,itemType:i,property:null},DOMAttributeNames:{className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"enctype",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};t.exports=f},{"./DOMProperty":10,"./ExecutionEnvironment":21}],23:[function(e,t){"use strict";function n(e){u(null==e.props.checkedLink||null==e.props.valueLink)}function r(e){n(e),u(null==e.props.value&&null==e.props.onChange)}function o(e){n(e),u(null==e.props.checked&&null==e.props.onChange)}function i(e){this.props.valueLink.requestChange(e.target.value)}function a(e){this.props.checkedLink.requestChange(e.target.checked)}var s=e("./ReactPropTypes"),u=e("./invariant"),c={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},l={Mixin:{propTypes:{value:function(e,t){return!e[t]||c[e.type]||e.onChange||e.readOnly||e.disabled?void 0:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t){return!e[t]||e.onChange||e.readOnly||e.disabled?void 0:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:s.func}},getValue:function(e){return e.props.valueLink?(r(e),e.props.valueLink.value):e.props.value},getChecked:function(e){return e.props.checkedLink?(o(e),e.props.checkedLink.value):e.props.checked},getOnChange:function(e){return e.props.valueLink?(r(e),i):e.props.checkedLink?(o(e),a):e.props.onChange}};t.exports=l},{"./ReactPropTypes":67,"./invariant":118}],24:[function(e,t){"use strict";function n(e){e.remove()}var r=e("./ReactBrowserEventEmitter"),o=e("./accumulate"),i=e("./forEachAccumulated"),a=e("./invariant"),s={trapBubbledEvent:function(e,t){a(this.isMounted());var n=r.trapBubbledEvent(e,t,this.getDOMNode());this._localEventListeners=o(this._localEventListeners,n)},componentWillUnmount:function(){this._localEventListeners&&i(this._localEventListeners,n)}};t.exports=s},{"./ReactBrowserEventEmitter":29,"./accumulate":92,"./forEachAccumulated":105,"./invariant":118}],25:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./emptyFunction"),o=n.topLevelTypes,i={eventTypes:null,extractEvents:function(e,t,n,i){if(e===o.topTouchStart){var a=i.target;a&&!a.onclick&&(a.onclick=r)}}};t.exports=i},{"./EventConstants":15,"./emptyFunction":100}],26:[function(e,t){"use strict";var n=e("./invariant"),r=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},o=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},i=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},a=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},s=function(e){var t=this;n(e instanceof t),e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},u=10,c=r,l=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||c,n.poolSize||(n.poolSize=u),n.release=s,n},p={addPoolingTo:l,oneArgumentPooler:r,twoArgumentPooler:o,threeArgumentPooler:i,fiveArgumentPooler:a};t.exports=p},{"./invariant":118}],27:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),r=e("./EventPluginUtils"),o=e("./ReactChildren"),i=e("./ReactComponent"),a=e("./ReactCompositeComponent"),s=e("./ReactContext"),u=e("./ReactCurrentOwner"),c=e("./ReactDescriptor"),l=e("./ReactDOM"),p=e("./ReactDOMComponent"),d=e("./ReactDefaultInjection"),f=e("./ReactInstanceHandles"),h=e("./ReactMount"),v=e("./ReactMultiChild"),m=e("./ReactPerf"),g=e("./ReactPropTypes"),y=e("./ReactServerRendering"),C=e("./ReactTextComponent"),E=e("./onlyChild");d.inject();var R={Children:{map:o.map,forEach:o.forEach,only:E},DOM:l,PropTypes:g,initializeTouchEvents:function(e){r.useTouchEvents=e},createClass:a.createClass,createDescriptor:function(e){var t=Array.prototype.slice.call(arguments,1);return e.apply(null,t)},constructAndRenderComponent:h.constructAndRenderComponent,constructAndRenderComponentByID:h.constructAndRenderComponentByID,renderComponent:m.measure("React","renderComponent",h.renderComponent),renderComponentToString:y.renderComponentToString,renderComponentToStaticMarkup:y.renderComponentToStaticMarkup,unmountComponentAtNode:h.unmountComponentAtNode,isValidClass:c.isValidFactory,isValidComponent:c.isValidDescriptor,withContext:s.withContext,__internals:{Component:i,CurrentOwner:u,DOMComponent:p,DOMPropertyOperations:n,InstanceHandles:f,Mount:h,MultiChild:v,TextComponent:C}};R.version="0.11.0-rc1",t.exports=R},{"./DOMPropertyOperations":11,"./EventPluginUtils":19,"./ReactChildren":30,"./ReactComponent":31,"./ReactCompositeComponent":33,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactDOM":36,"./ReactDOMComponent":38,"./ReactDefaultInjection":48,"./ReactDescriptor":49,"./ReactInstanceHandles":57,"./ReactMount":59,"./ReactMultiChild":60,"./ReactPerf":63,"./ReactPropTypes":67,"./ReactServerRendering":71,"./ReactTextComponent":73,"./onlyChild":133}],28:[function(e,t){"use strict";var n=e("./ReactEmptyComponent"),r=e("./ReactMount"),o=e("./invariant"),i={getDOMNode:function(){return o(this.isMounted()),n.isNullComponentID(this._rootNodeID)?null:r.getNode(this._rootNodeID)}};t.exports=i},{"./ReactEmptyComponent":51,"./ReactMount":59,"./invariant":118}],29:[function(e,t){"use strict";function n(e){return Object.prototype.hasOwnProperty.call(e,h)||(e[h]=d++,l[e[h]]={}),l[e[h]]}var r=e("./EventConstants"),o=e("./EventPluginHub"),i=e("./EventPluginRegistry"),a=e("./ReactEventEmitterMixin"),s=e("./ViewportMetrics"),u=e("./isEventSupported"),c=e("./merge"),l={},p=!1,d=0,f={topBlur:"blur",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topScroll:"scroll",topSelectionChange:"selectionchange",topTextInput:"textInput",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topWheel:"wheel"},h="_reactListenersID"+String(Math.random()).slice(2),v=c(a,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(v.handleTopLevel),v.ReactEventListener=e }},setEnabled:function(e){v.ReactEventListener&&v.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!v.ReactEventListener||!v.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var o=t,a=n(o),s=i.registrationNameDependencies[e],c=r.topLevelTypes,l=0,p=s.length;p>l;l++){var d=s[l];a.hasOwnProperty(d)&&a[d]||(d===c.topWheel?u("wheel")?v.ReactEventListener.trapBubbledEvent(c.topWheel,"wheel",o):u("mousewheel")?v.ReactEventListener.trapBubbledEvent(c.topWheel,"mousewheel",o):v.ReactEventListener.trapBubbledEvent(c.topWheel,"DOMMouseScroll",o):d===c.topScroll?u("scroll",!0)?v.ReactEventListener.trapCapturedEvent(c.topScroll,"scroll",o):v.ReactEventListener.trapBubbledEvent(c.topScroll,"scroll",v.ReactEventListener.WINDOW_HANDLE):d===c.topFocus||d===c.topBlur?(u("focus",!0)?(v.ReactEventListener.trapCapturedEvent(c.topFocus,"focus",o),v.ReactEventListener.trapCapturedEvent(c.topBlur,"blur",o)):u("focusin")&&(v.ReactEventListener.trapBubbledEvent(c.topFocus,"focusin",o),v.ReactEventListener.trapBubbledEvent(c.topBlur,"focusout",o)),a[c.topBlur]=!0,a[c.topFocus]=!0):f.hasOwnProperty(d)&&v.ReactEventListener.trapBubbledEvent(d,f[d],o),a[d]=!0)}},trapBubbledEvent:function(e,t,n){return v.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return v.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!p){var e=s.refreshScrollValues;v.ReactEventListener.monitorScrollValue(e),p=!0}},eventNameDispatchConfigs:o.eventNameDispatchConfigs,registrationNameModules:o.registrationNameModules,putListener:o.putListener,getListener:o.getListener,deleteListener:o.deleteListener,deleteAllListeners:o.deleteAllListeners});t.exports=v},{"./EventConstants":15,"./EventPluginHub":17,"./EventPluginRegistry":18,"./ReactEventEmitterMixin":53,"./ViewportMetrics":91,"./isEventSupported":119,"./merge":128}],30:[function(e,t){"use strict";function n(e,t){this.forEachFunction=e,this.forEachContext=t}function r(e,t,n,r){var o=e;o.forEachFunction.call(o.forEachContext,t,r)}function o(e,t,o){if(null==e)return e;var i=n.getPooled(t,o);p(e,r,i),n.release(i)}function i(e,t,n){this.mapResult=e,this.mapFunction=t,this.mapContext=n}function a(e,t,n,r){var o=e,i=o.mapResult,a=!i.hasOwnProperty(n);if(a){var s=o.mapFunction.call(o.mapContext,t,r);i[n]=s}}function s(e,t,n){if(null==e)return e;var r={},o=i.getPooled(r,t,n);return p(e,a,o),i.release(o),r}function u(){return null}function c(e){return p(e,u,null)}var l=e("./PooledClass"),p=e("./traverseAllChildren"),d=(e("./warning"),l.twoArgumentPooler),f=l.threeArgumentPooler;l.addPoolingTo(n,d),l.addPoolingTo(i,f);var h={forEach:o,map:s,count:c};t.exports=h},{"./PooledClass":26,"./traverseAllChildren":138,"./warning":139}],31:[function(e,t){"use strict";var n=e("./ReactDescriptor"),r=e("./ReactOwner"),o=e("./ReactUpdates"),i=e("./invariant"),a=e("./keyMirror"),s=e("./merge"),u=a({MOUNTED:null,UNMOUNTED:null}),c=!1,l=null,p=null,d={injection:{injectEnvironment:function(e){i(!c),p=e.mountImageIntoNode,l=e.unmountIDFromEnvironment,d.BackendIDOperations=e.BackendIDOperations,c=!0}},LifeCycle:u,BackendIDOperations:null,Mixin:{isMounted:function(){return this._lifeCycleState===u.MOUNTED},setProps:function(e,t){var n=this._pendingDescriptor||this._descriptor;this.replaceProps(s(n.props,e),t)},replaceProps:function(e,t){i(this.isMounted()),i(0===this._mountDepth),this._pendingDescriptor=n.cloneAndReplaceProps(this._pendingDescriptor||this._descriptor,e),o.enqueueUpdate(this,t)},_setPropsInternal:function(e,t){var r=this._pendingDescriptor||this._descriptor;this._pendingDescriptor=n.cloneAndReplaceProps(r,s(r.props,e)),o.enqueueUpdate(this,t)},construct:function(e){this.props=e.props,this._owner=e._owner,this._lifeCycleState=u.UNMOUNTED,this._pendingCallbacks=null,this._descriptor=e,this._pendingDescriptor=null},mountComponent:function(e,t,n){i(!this.isMounted());var o=this._descriptor.props;if(null!=o.ref){var a=this._descriptor._owner;r.addComponentAsRefTo(this,o.ref,a)}this._rootNodeID=e,this._lifeCycleState=u.MOUNTED,this._mountDepth=n},unmountComponent:function(){i(this.isMounted());var e=this.props;null!=e.ref&&r.removeComponentAsRefFrom(this,e.ref,this._owner),l(this._rootNodeID),this._rootNodeID=null,this._lifeCycleState=u.UNMOUNTED},receiveComponent:function(e,t){i(this.isMounted()),this._pendingDescriptor=e,this.performUpdateIfNecessary(t)},performUpdateIfNecessary:function(e){if(null!=this._pendingDescriptor){var t=this._descriptor,n=this._pendingDescriptor;this._descriptor=n,this.props=n.props,this._owner=n._owner,this._pendingDescriptor=null,this.updateComponent(e,t)}},updateComponent:function(e,t){var n=this._descriptor;(n._owner!==t._owner||n.props.ref!==t.props.ref)&&(null!=t.props.ref&&r.removeComponentAsRefFrom(this,t.props.ref,t._owner),null!=n.props.ref&&r.addComponentAsRefTo(this,n.props.ref,n._owner))},mountComponentIntoNode:function(e,t,n){var r=o.ReactReconcileTransaction.getPooled();r.perform(this._mountComponentIntoNode,this,e,t,r,n),o.ReactReconcileTransaction.release(r)},_mountComponentIntoNode:function(e,t,n,r){var o=this.mountComponent(e,n,0);p(o,t,r)},isOwnedBy:function(e){return this._owner===e},getSiblingByRef:function(e){var t=this._owner;return t&&t.refs?t.refs[e]:null}}};t.exports=d},{"./ReactDescriptor":49,"./ReactOwner":62,"./ReactUpdates":74,"./invariant":118,"./keyMirror":124,"./merge":128}],32:[function(e,t){"use strict";var n=e("./ReactDOMIDOperations"),r=e("./ReactMarkupChecksum"),o=e("./ReactMount"),i=e("./ReactPerf"),a=e("./ReactReconcileTransaction"),s=e("./getReactRootElementInContainer"),u=e("./invariant"),c=e("./setInnerHTML"),l=1,p=9,d={ReactReconcileTransaction:a,BackendIDOperations:n,unmountIDFromEnvironment:function(e){o.purgeID(e)},mountImageIntoNode:i.measure("ReactComponentBrowserEnvironment","mountImageIntoNode",function(e,t,n){if(u(t&&(t.nodeType===l||t.nodeType===p)),n){if(r.canReuseMarkup(e,s(t)))return;u(t.nodeType!==p)}u(t.nodeType!==p),c(t,e)})};t.exports=d},{"./ReactDOMIDOperations":40,"./ReactMarkupChecksum":58,"./ReactMount":59,"./ReactPerf":63,"./ReactReconcileTransaction":69,"./getReactRootElementInContainer":112,"./invariant":118,"./setInnerHTML":134}],33:[function(e,t){"use strict";function n(e){var t=e._owner||null;return t&&t.constructor&&t.constructor.displayName?" Check the render method of `"+t.constructor.displayName+"`.":""}function r(e,t){for(var n in t)t.hasOwnProperty(n)&&D("function"==typeof t[n])}function o(e,t){var n=N.hasOwnProperty(t)?N[t]:null;A.hasOwnProperty(t)&&D(n===_.OVERRIDE_BASE),e.hasOwnProperty(t)&&D(n===_.DEFINE_MANY||n===_.DEFINE_MANY_MERGED)}function i(e){var t=e._compositeLifeCycleState;D(e.isMounted()||t===S.MOUNTING),D(t!==S.RECEIVING_STATE),D(t!==S.UNMOUNTING)}function a(e,t){D(!h.isValidFactory(t)),D(!h.isValidDescriptor(t));var n=e.prototype;for(var r in t){var i=t[r];if(t.hasOwnProperty(r))if(o(n,r),w.hasOwnProperty(r))w[r](e,i);else{var a=N.hasOwnProperty(r),s=n.hasOwnProperty(r),u=i&&i.__reactDontBind,p="function"==typeof i,d=p&&!a&&!s&&!u;if(d)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[r]=i,n[r]=i;else if(s){var f=N[r];D(a&&(f===_.DEFINE_MANY_MERGED||f===_.DEFINE_MANY)),f===_.DEFINE_MANY_MERGED?n[r]=c(n[r],i):f===_.DEFINE_MANY&&(n[r]=l(n[r],i))}else n[r]=i}}}function s(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in e,i=r;if(o){var a=e[n],s=typeof a,u=typeof r;D("function"===s&&"function"===u),i=l(a,r)}e[n]=i}}}function u(e,t){return D(e&&t&&"object"==typeof e&&"object"==typeof t),P(t,function(t,n){D(void 0===e[n]),e[n]=t}),e}function c(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);return null==n?r:null==r?n:u(n,r)}}function l(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}var p=e("./ReactComponent"),d=e("./ReactContext"),f=e("./ReactCurrentOwner"),h=e("./ReactDescriptor"),v=(e("./ReactDescriptorValidator"),e("./ReactEmptyComponent")),m=e("./ReactErrorUtils"),g=e("./ReactOwner"),y=e("./ReactPerf"),C=e("./ReactPropTransferer"),E=e("./ReactPropTypeLocations"),R=(e("./ReactPropTypeLocationNames"),e("./ReactUpdates")),M=e("./instantiateReactComponent"),D=e("./invariant"),x=e("./keyMirror"),b=e("./merge"),O=e("./mixInto"),P=(e("./monitorCodeUse"),e("./mapObject")),I=e("./shouldUpdateReactComponent"),_=(e("./warning"),x({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null})),T=[],N={mixins:_.DEFINE_MANY,statics:_.DEFINE_MANY,propTypes:_.DEFINE_MANY,contextTypes:_.DEFINE_MANY,childContextTypes:_.DEFINE_MANY,getDefaultProps:_.DEFINE_MANY_MERGED,getInitialState:_.DEFINE_MANY_MERGED,getChildContext:_.DEFINE_MANY_MERGED,render:_.DEFINE_ONCE,componentWillMount:_.DEFINE_MANY,componentDidMount:_.DEFINE_MANY,componentWillReceiveProps:_.DEFINE_MANY,shouldComponentUpdate:_.DEFINE_ONCE,componentWillUpdate:_.DEFINE_MANY,componentDidUpdate:_.DEFINE_MANY,componentWillUnmount:_.DEFINE_MANY,updateComponent:_.OVERRIDE_BASE},w={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)a(e,t[n])},childContextTypes:function(e,t){r(e,t,E.childContext),e.childContextTypes=b(e.childContextTypes,t)},contextTypes:function(e,t){r(e,t,E.context),e.contextTypes=b(e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps=e.getDefaultProps?c(e.getDefaultProps,t):t},propTypes:function(e,t){r(e,t,E.prop),e.propTypes=b(e.propTypes,t)},statics:function(e,t){s(e,t)}},S=x({MOUNTING:null,UNMOUNTING:null,RECEIVING_PROPS:null,RECEIVING_STATE:null}),A={construct:function(){p.Mixin.construct.apply(this,arguments),g.Mixin.construct.apply(this,arguments),this.state=null,this._pendingState=null,this.context=null,this._compositeLifeCycleState=null},isMounted:function(){return p.Mixin.isMounted.call(this)&&this._compositeLifeCycleState!==S.MOUNTING},mountComponent:y.measure("ReactCompositeComponent","mountComponent",function(e,t,n){p.Mixin.mountComponent.call(this,e,t,n),this._compositeLifeCycleState=S.MOUNTING,this.__reactAutoBindMap&&this._bindAutoBindMethods(),this.context=this._processContext(this._descriptor._context),this.props=this._processProps(this.props),this.state=this.getInitialState?this.getInitialState():null,D("object"==typeof this.state&&!Array.isArray(this.state)),this._pendingState=null,this._pendingForceUpdate=!1,this.componentWillMount&&(this.componentWillMount(),this._pendingState&&(this.state=this._pendingState,this._pendingState=null)),this._renderedComponent=M(this._renderValidatedComponent()),this._compositeLifeCycleState=null;var r=this._renderedComponent.mountComponent(e,t,n+1);return this.componentDidMount&&t.getReactMountReady().enqueue(this.componentDidMount,this),r}),unmountComponent:function(){this._compositeLifeCycleState=S.UNMOUNTING,this.componentWillUnmount&&this.componentWillUnmount(),this._compositeLifeCycleState=null,this._renderedComponent.unmountComponent(),this._renderedComponent=null,p.Mixin.unmountComponent.call(this)},setState:function(e,t){D("object"==typeof e||null==e),this.replaceState(b(this._pendingState||this.state,e),t)},replaceState:function(e,t){i(this),this._pendingState=e,R.enqueueUpdate(this,t)},_processContext:function(e){var t=null,n=this.constructor.contextTypes;if(n){t={};for(var r in n)t[r]=e[r]}return t},_processChildContext:function(e){var t=this.getChildContext&&this.getChildContext();if(this.constructor.displayName||"ReactCompositeComponent",t){D("object"==typeof this.constructor.childContextTypes);for(var n in t)D(n in this.constructor.childContextTypes);return b(e,t)}return e},_processProps:function(e){var t,n=this.constructor.defaultProps;if(n){t=b(e);for(var r in n)"undefined"==typeof t[r]&&(t[r]=n[r])}else t=e;return t},_checkPropTypes:function(e,t,r){var o=this.constructor.displayName;for(var i in e)if(e.hasOwnProperty(i)){var a=e[i](t,i,o,r);a instanceof Error&&n(this)}},performUpdateIfNecessary:function(e){var t=this._compositeLifeCycleState;if(t!==S.MOUNTING&&t!==S.RECEIVING_PROPS&&(null!=this._pendingDescriptor||null!=this._pendingState||this._pendingForceUpdate)){var n=this.context,r=this.props,o=this._descriptor;null!=this._pendingDescriptor&&(o=this._pendingDescriptor,n=this._processContext(o._context),r=this._processProps(o.props),this._pendingDescriptor=null,this._compositeLifeCycleState=S.RECEIVING_PROPS,this.componentWillReceiveProps&&this.componentWillReceiveProps(r,n)),this._compositeLifeCycleState=S.RECEIVING_STATE;var i=this._pendingState||this.state;this._pendingState=null;try{var a=this._pendingForceUpdate||!this.shouldComponentUpdate||this.shouldComponentUpdate(r,i,n);a?(this._pendingForceUpdate=!1,this._performComponentUpdate(o,r,i,n,e)):(this._descriptor=o,this.props=r,this.state=i,this.context=n,this._owner=o._owner)}finally{this._compositeLifeCycleState=null}}},_performComponentUpdate:function(e,t,n,r,o){var i=this._descriptor,a=this.props,s=this.state,u=this.context;this.componentWillUpdate&&this.componentWillUpdate(t,n,r),this._descriptor=e,this.props=t,this.state=n,this.context=r,this._owner=e._owner,this.updateComponent(o,i),this.componentDidUpdate&&o.getReactMountReady().enqueue(this.componentDidUpdate.bind(this,a,s,u),this)},receiveComponent:function(e,t){(e!==this._descriptor||null==e._owner)&&p.Mixin.receiveComponent.call(this,e,t)},updateComponent:y.measure("ReactCompositeComponent","updateComponent",function(e,t){p.Mixin.updateComponent.call(this,e,t);var n=this._renderedComponent,r=n._descriptor,o=this._renderValidatedComponent();if(I(r,o))n.receiveComponent(o,e);else{var i=this._rootNodeID,a=n._rootNodeID;n.unmountComponent(),this._renderedComponent=M(o);var s=this._renderedComponent.mountComponent(i,e,this._mountDepth+1);p.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(a,s)}}),forceUpdate:function(e){var t=this._compositeLifeCycleState;D(this.isMounted()||t===S.MOUNTING),D(t!==S.RECEIVING_STATE&&t!==S.UNMOUNTING),this._pendingForceUpdate=!0,R.enqueueUpdate(this,e)},_renderValidatedComponent:y.measure("ReactCompositeComponent","_renderValidatedComponent",function(){var e,t=d.current;d.current=this._processChildContext(this._descriptor._context),f.current=this;try{e=this.render(),null===e||e===!1?(e=v.getEmptyComponent(),v.registerNullComponentID(this._rootNodeID)):v.deregisterNullComponentID(this._rootNodeID)}finally{d.current=t,f.current=null}return D(h.isValidDescriptor(e)),e}),_bindAutoBindMethods:function(){for(var e in this.__reactAutoBindMap)if(this.__reactAutoBindMap.hasOwnProperty(e)){var t=this.__reactAutoBindMap[e];this[e]=this._bindAutoBindMethod(m.guard(t,this.constructor.displayName+"."+e))}},_bindAutoBindMethod:function(e){var t=this,n=function(){return e.apply(t,arguments)};return n}},k=function(){};O(k,p.Mixin),O(k,g.Mixin),O(k,C.Mixin),O(k,A);var U={LifeCycle:S,Base:k,createClass:function(e){var t=function(e,t){this.construct(e,t)};t.prototype=new k,t.prototype.constructor=t,T.forEach(a.bind(null,t)),a(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),D(t.prototype.render);for(var n in N)t.prototype[n]||(t.prototype[n]=null);var r=h.createFactory(t);return r},injection:{injectMixin:function(e){T.push(e)}}};t.exports=U},{"./ReactComponent":31,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactDescriptor":49,"./ReactDescriptorValidator":50,"./ReactEmptyComponent":51,"./ReactErrorUtils":52,"./ReactOwner":62,"./ReactPerf":63,"./ReactPropTransferer":64,"./ReactPropTypeLocationNames":65,"./ReactPropTypeLocations":66,"./ReactUpdates":74,"./instantiateReactComponent":117,"./invariant":118,"./keyMirror":124,"./mapObject":126,"./merge":128,"./mixInto":131,"./monitorCodeUse":132,"./shouldUpdateReactComponent":136,"./warning":139}],34:[function(e,t){"use strict";var n=e("./merge"),r={current:{},withContext:function(e,t){var o,i=r.current;r.current=n(i,e);try{o=t()}finally{r.current=i}return o}};t.exports=r},{"./merge":128}],35:[function(e,t){"use strict";var n={current:null};t.exports=n},{}],36:[function(e,t){"use strict";function n(e,t){var n=function(e){this.construct(e)};n.prototype=new o(t,e),n.prototype.constructor=n,n.displayName=t;var i=r.createFactory(n);return i}var r=e("./ReactDescriptor"),o=(e("./ReactDescriptorValidator"),e("./ReactDOMComponent")),i=e("./mergeInto"),a=e("./mapObject"),s=a({a:!1,abbr:!1,address:!1,area:!0,article:!1,aside:!1,audio:!1,b:!1,base:!0,bdi:!1,bdo:!1,big:!1,blockquote:!1,body:!1,br:!0,button:!1,canvas:!1,caption:!1,cite:!1,code:!1,col:!0,colgroup:!1,data:!1,datalist:!1,dd:!1,del:!1,details:!1,dfn:!1,div:!1,dl:!1,dt:!1,em:!1,embed:!0,fieldset:!1,figcaption:!1,figure:!1,footer:!1,form:!1,h1:!1,h2:!1,h3:!1,h4:!1,h5:!1,h6:!1,head:!1,header:!1,hr:!0,html:!1,i:!1,iframe:!1,img:!0,input:!0,ins:!1,kbd:!1,keygen:!0,label:!1,legend:!1,li:!1,link:!0,main:!1,map:!1,mark:!1,menu:!1,menuitem:!1,meta:!0,meter:!1,nav:!1,noscript:!1,object:!1,ol:!1,optgroup:!1,option:!1,output:!1,p:!1,param:!0,pre:!1,progress:!1,q:!1,rp:!1,rt:!1,ruby:!1,s:!1,samp:!1,script:!1,section:!1,select:!1,small:!1,source:!0,span:!1,strong:!1,style:!1,sub:!1,summary:!1,sup:!1,table:!1,tbody:!1,td:!1,textarea:!1,tfoot:!1,th:!1,thead:!1,time:!1,title:!1,tr:!1,track:!0,u:!1,ul:!1,"var":!1,video:!1,wbr:!0,circle:!1,defs:!1,ellipse:!1,g:!1,line:!1,linearGradient:!1,mask:!1,path:!1,pattern:!1,polygon:!1,polyline:!1,radialGradient:!1,rect:!1,stop:!1,svg:!1,text:!1,tspan:!1},n),u={injectComponentClasses:function(e){i(s,e)}};s.injection=u,t.exports=s},{"./ReactDOMComponent":38,"./ReactDescriptor":49,"./ReactDescriptorValidator":50,"./mapObject":126,"./mergeInto":130}],37:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),r=e("./ReactBrowserComponentMixin"),o=e("./ReactCompositeComponent"),i=e("./ReactDOM"),a=e("./keyMirror"),s=i.button,u=a({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),c=o.createClass({displayName:"ReactDOMButton",mixins:[n,r],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&u[t]||(e[t]=this.props[t]);return s(e,this.props.children)}});t.exports=c},{"./AutoFocusMixin":1,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./keyMirror":124}],38:[function(e,t){"use strict";function n(e){e&&(v(null==e.children||null==e.dangerouslySetInnerHTML),v(null==e.style||"object"==typeof e.style))}function r(e,t,n,r){var o=p.findReactContainerForID(e);if(o){var i=o.nodeType===x?o.ownerDocument:o;E(t,i)}r.getPutListenerQueue().enqueuePutListener(e,t,n)}function o(e,t){this._tagOpen="<"+e,this._tagClose=t?"":"</"+e+">",this.tagName=e.toUpperCase()}var i=e("./CSSPropertyOperations"),a=e("./DOMProperty"),s=e("./DOMPropertyOperations"),u=e("./ReactBrowserComponentMixin"),c=e("./ReactComponent"),l=e("./ReactBrowserEventEmitter"),p=e("./ReactMount"),d=e("./ReactMultiChild"),f=e("./ReactPerf"),h=e("./escapeTextForBrowser"),v=e("./invariant"),m=e("./keyOf"),g=e("./merge"),y=e("./mixInto"),C=l.deleteListener,E=l.listenTo,R=l.registrationNameModules,M={string:!0,number:!0},D=m({style:null}),x=1;o.Mixin={mountComponent:f.measure("ReactDOMComponent","mountComponent",function(e,t,r){return c.Mixin.mountComponent.call(this,e,t,r),n(this.props),this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t)+this._tagClose}),_createOpenTagMarkupAndPutListeners:function(e){var t=this.props,n=this._tagOpen;for(var o in t)if(t.hasOwnProperty(o)){var a=t[o];if(null!=a)if(R.hasOwnProperty(o))r(this._rootNodeID,o,a,e);else{o===D&&(a&&(a=t.style=g(t.style)),a=i.createMarkupForStyles(a));var u=s.createMarkupForProperty(o,a);u&&(n+=" "+u)}}if(e.renderToStaticMarkup)return n+">";var c=s.createMarkupForID(this._rootNodeID);return n+" "+c+">"},_createContentMarkup:function(e){var t=this.props.dangerouslySetInnerHTML;if(null!=t){if(null!=t.__html)return t.__html}else{var n=M[typeof this.props.children]?this.props.children:null,r=null!=n?null:this.props.children;if(null!=n)return h(n);if(null!=r){var o=this.mountChildren(r,e);return o.join("")}}return""},receiveComponent:function(e,t){(e!==this._descriptor||null==e._owner)&&c.Mixin.receiveComponent.call(this,e,t)},updateComponent:f.measure("ReactDOMComponent","updateComponent",function(e,t){n(this._descriptor.props),c.Mixin.updateComponent.call(this,e,t),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e)}),_updateDOMProperties:function(e,t){var n,o,i,s=this.props;for(n in e)if(!s.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===D){var u=e[n];for(o in u)u.hasOwnProperty(o)&&(i=i||{},i[o]="")}else R.hasOwnProperty(n)?C(this._rootNodeID,n):(a.isStandardName[n]||a.isCustomAttribute(n))&&c.BackendIDOperations.deletePropertyByID(this._rootNodeID,n);for(n in s){var l=s[n],p=e[n];if(s.hasOwnProperty(n)&&l!==p)if(n===D)if(l&&(l=s.style=g(l)),p){for(o in p)!p.hasOwnProperty(o)||l&&l.hasOwnProperty(o)||(i=i||{},i[o]="");for(o in l)l.hasOwnProperty(o)&&p[o]!==l[o]&&(i=i||{},i[o]=l[o])}else i=l;else R.hasOwnProperty(n)?r(this._rootNodeID,n,l,t):(a.isStandardName[n]||a.isCustomAttribute(n))&&c.BackendIDOperations.updatePropertyByID(this._rootNodeID,n,l)}i&&c.BackendIDOperations.updateStylesByID(this._rootNodeID,i)},_updateDOMChildren:function(e,t){var n=this.props,r=M[typeof e.children]?e.children:null,o=M[typeof n.children]?n.children:null,i=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,a=n.dangerouslySetInnerHTML&&n.dangerouslySetInnerHTML.__html,s=null!=r?null:e.children,u=null!=o?null:n.children,l=null!=r||null!=i,p=null!=o||null!=a;null!=s&&null==u?this.updateChildren(null,t):l&&!p&&this.updateTextContent(""),null!=o?r!==o&&this.updateTextContent(""+o):null!=a?i!==a&&c.BackendIDOperations.updateInnerHTMLByID(this._rootNodeID,a):null!=u&&this.updateChildren(u,t)},unmountComponent:function(){this.unmountChildren(),l.deleteAllListeners(this._rootNodeID),c.Mixin.unmountComponent.call(this)}},y(o,c.Mixin),y(o,o.Mixin),y(o,d.Mixin),y(o,u),t.exports=o},{"./CSSPropertyOperations":4,"./DOMProperty":10,"./DOMPropertyOperations":11,"./ReactBrowserComponentMixin":28,"./ReactBrowserEventEmitter":29,"./ReactComponent":31,"./ReactMount":59,"./ReactMultiChild":60,"./ReactPerf":63,"./escapeTextForBrowser":102,"./invariant":118,"./keyOf":125,"./merge":128,"./mixInto":131}],39:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),o=e("./ReactBrowserComponentMixin"),i=e("./ReactCompositeComponent"),a=e("./ReactDOM"),s=a.form,u=i.createClass({displayName:"ReactDOMForm",mixins:[o,r],render:function(){return this.transferPropsTo(s(null,this.props.children))},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(n.topLevelTypes.topSubmit,"submit")}});t.exports=u},{"./EventConstants":15,"./LocalEventTrapMixin":24,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36}],40:[function(e,t){"use strict";var n=e("./CSSPropertyOperations"),r=e("./DOMChildrenOperations"),o=e("./DOMPropertyOperations"),i=e("./ReactMount"),a=e("./ReactPerf"),s=e("./invariant"),u=e("./setInnerHTML"),c={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},l={updatePropertyByID:a.measure("ReactDOMIDOperations","updatePropertyByID",function(e,t,n){var r=i.getNode(e);s(!c.hasOwnProperty(t)),null!=n?o.setValueForProperty(r,t,n):o.deleteValueForProperty(r,t)}),deletePropertyByID:a.measure("ReactDOMIDOperations","deletePropertyByID",function(e,t,n){var r=i.getNode(e);s(!c.hasOwnProperty(t)),o.deleteValueForProperty(r,t,n)}),updateStylesByID:a.measure("ReactDOMIDOperations","updateStylesByID",function(e,t){var r=i.getNode(e);n.setValueForStyles(r,t)}),updateInnerHTMLByID:a.measure("ReactDOMIDOperations","updateInnerHTMLByID",function(e,t){var n=i.getNode(e);u(n,t)}),updateTextContentByID:a.measure("ReactDOMIDOperations","updateTextContentByID",function(e,t){var n=i.getNode(e);r.updateTextContent(n,t)}),dangerouslyReplaceNodeWithMarkupByID:a.measure("ReactDOMIDOperations","dangerouslyReplaceNodeWithMarkupByID",function(e,t){var n=i.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)}),dangerouslyProcessChildrenUpdates:a.measure("ReactDOMIDOperations","dangerouslyProcessChildrenUpdates",function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=i.getNode(e[n].parentID);r.processUpdates(e,t)})};t.exports=l},{"./CSSPropertyOperations":4,"./DOMChildrenOperations":9,"./DOMPropertyOperations":11,"./ReactMount":59,"./ReactPerf":63,"./invariant":118,"./setInnerHTML":134}],41:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),o=e("./ReactBrowserComponentMixin"),i=e("./ReactCompositeComponent"),a=e("./ReactDOM"),s=a.img,u=i.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[o,r],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(n.topLevelTypes.topError,"error")}});t.exports=u},{"./EventConstants":15,"./LocalEventTrapMixin":24,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36}],42:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),r=e("./DOMPropertyOperations"),o=e("./LinkedValueUtils"),i=e("./ReactBrowserComponentMixin"),a=e("./ReactCompositeComponent"),s=e("./ReactDOM"),u=e("./ReactMount"),c=e("./invariant"),l=e("./merge"),p=s.input,d={},f=a.createClass({displayName:"ReactDOMInput",mixins:[n,o.Mixin,i],getInitialState:function(){var e=this.props.defaultValue;return{checked:this.props.defaultChecked||!1,value:null!=e?e:null}},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=l(this.props);e.defaultChecked=null,e.defaultValue=null;var t=o.getValue(this);e.value=null!=t?t:this.state.value;var n=o.getChecked(this);return e.checked=null!=n?n:this.state.checked,e.onChange=this._handleChange,p(e,this.props.children)},componentDidMount:function(){var e=u.getID(this.getDOMNode());d[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=u.getID(e);delete d[t]},componentDidUpdate:function(){var e=this.getDOMNode();null!=this.props.checked&&r.setValueForProperty(e,"checked",this.props.checked||!1);var t=o.getValue(this);null!=t&&r.setValueForProperty(e,"value",""+t)},_handleChange:function(e){var t,n=o.getOnChange(this);n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1),this.setState({checked:e.target.checked,value:e.target.value});var r=this.props.name;if("radio"===this.props.type&&null!=r){for(var i=this.getDOMNode(),a=i;a.parentNode;)a=a.parentNode;for(var s=a.querySelectorAll("input[name="+JSON.stringify(""+r)+'][type="radio"]'),l=0,p=s.length;p>l;l++){var f=s[l];if(f!==i&&f.form===i.form){var h=u.getID(f);c(h);var v=d[h];c(v),v.setState({checked:!1})}}}return t}});t.exports=f},{"./AutoFocusMixin":1,"./DOMPropertyOperations":11,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactMount":59,"./invariant":118,"./merge":128}],43:[function(e,t){"use strict";var n=e("./ReactBrowserComponentMixin"),r=e("./ReactCompositeComponent"),o=e("./ReactDOM"),i=(e("./warning"),o.option),a=r.createClass({displayName:"ReactDOMOption",mixins:[n],componentWillMount:function(){},render:function(){return i(this.props,this.props.children)}});t.exports=a},{"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./warning":139}],44:[function(e,t){"use strict";function n(e,t){if(null!=e[t])if(e.multiple){if(!Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be an array if `multiple` is true.")}else if(Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be a scalar value if `multiple` is false.")}function r(e,t){var n,r,o,i=e.props.multiple,a=null!=t?t:e.state.value,s=e.getDOMNode().options;if(i)for(n={},r=0,o=a.length;o>r;++r)n[""+a[r]]=!0;else n=""+a;for(r=0,o=s.length;o>r;r++){var u=i?n.hasOwnProperty(s[r].value):s[r].value===n;u!==s[r].selected&&(s[r].selected=u)}}var o=e("./AutoFocusMixin"),i=e("./LinkedValueUtils"),a=e("./ReactBrowserComponentMixin"),s=e("./ReactCompositeComponent"),u=e("./ReactDOM"),c=e("./merge"),l=u.select,p=s.createClass({displayName:"ReactDOMSelect",mixins:[o,i.Mixin,a],propTypes:{defaultValue:n,value:n},getInitialState:function(){return{value:this.props.defaultValue||(this.props.multiple?[]:"")}},componentWillReceiveProps:function(e){!this.props.multiple&&e.multiple?this.setState({value:[this.state.value]}):this.props.multiple&&!e.multiple&&this.setState({value:this.state.value[0]})},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=c(this.props);return e.onChange=this._handleChange,e.value=null,l(e,this.props.children)},componentDidMount:function(){r(this,i.getValue(this))},componentDidUpdate:function(e){var t=i.getValue(this),n=!!e.multiple,o=!!this.props.multiple;(null!=t||n!==o)&&r(this,t)},_handleChange:function(e){var t,n=i.getOnChange(this);n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1);var r;if(this.props.multiple){r=[];for(var o=e.target.options,a=0,s=o.length;s>a;a++)o[a].selected&&r.push(o[a].value)}else r=e.target.value;return this.setState({value:r}),t}});t.exports=p},{"./AutoFocusMixin":1,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./merge":128}],45:[function(e,t){"use strict";function n(e,t,n,r){return e===n&&t===r}function r(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length,a=i+r;return{start:i,end:a}}function o(e){var t=window.getSelection();if(0===t.rangeCount)return null;var r=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,s=t.getRangeAt(0),u=n(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=u?0:s.toString().length,l=s.cloneRange();l.selectNodeContents(e),l.setEnd(s.startContainer,s.startOffset);var p=n(l.startContainer,l.startOffset,l.endContainer,l.endOffset),d=p?0:l.toString().length,f=d+c,h=document.createRange();h.setStart(r,o),h.setEnd(i,a);var v=h.collapsed;return h.detach(),{start:v?f:d,end:v?d:f}}function i(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function a(e,t){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),i="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var s=u(e,o),l=u(e,i);if(s&&l){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(l.node,l.offset)):(p.setEnd(l.node,l.offset),n.addRange(p)),p.detach()}}var s=e("./ExecutionEnvironment"),u=e("./getNodeForCharacterOffset"),c=e("./getTextContentAccessor"),l=s.canUseDOM&&document.selection,p={getOffsets:l?r:o,setOffsets:l?i:a};t.exports=p},{"./ExecutionEnvironment":21,"./getNodeForCharacterOffset":111,"./getTextContentAccessor":113}],46:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),r=e("./DOMPropertyOperations"),o=e("./LinkedValueUtils"),i=e("./ReactBrowserComponentMixin"),a=e("./ReactCompositeComponent"),s=e("./ReactDOM"),u=e("./invariant"),c=e("./merge"),l=(e("./warning"),s.textarea),p=a.createClass({displayName:"ReactDOMTextarea",mixins:[n,o.Mixin,i],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&(u(null==e),Array.isArray(t)&&(u(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=o.getValue(this);return{initialValue:""+(null!=n?n:e)}},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=c(this.props);return u(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,l(e,this.state.initialValue)},componentDidUpdate:function(){var e=o.getValue(this); if(null!=e){var t=this.getDOMNode();r.setValueForProperty(t,"value",""+e)}},_handleChange:function(e){var t,n=o.getOnChange(this);return n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1),this.setState({value:e.target.value}),t}});t.exports=p},{"./AutoFocusMixin":1,"./DOMPropertyOperations":11,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./invariant":118,"./merge":128,"./warning":139}],47:[function(e,t){"use strict";function n(){this.reinitializeTransaction()}var r=e("./ReactUpdates"),o=e("./Transaction"),i=e("./emptyFunction"),a=e("./mixInto"),s={initialize:i,close:function(){p.isBatchingUpdates=!1}},u={initialize:i,close:r.flushBatchedUpdates.bind(r)},c=[u,s];a(n,o.Mixin),a(n,{getTransactionWrappers:function(){return c}});var l=new n,p={isBatchingUpdates:!1,batchedUpdates:function(e,t,n){var r=p.isBatchingUpdates;p.isBatchingUpdates=!0,r?e(t,n):l.perform(e,null,t,n)}};t.exports=p},{"./ReactUpdates":74,"./Transaction":90,"./emptyFunction":100,"./mixInto":131}],48:[function(e,t){"use strict";function n(){x.EventEmitter.injectReactEventListener(D),x.EventPluginHub.injectEventPluginOrder(s),x.EventPluginHub.injectInstanceHandle(b),x.EventPluginHub.injectMount(O),x.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:_,EnterLeaveEventPlugin:u,ChangeEventPlugin:o,CompositionEventPlugin:a,MobileSafariClickEventPlugin:p,SelectEventPlugin:P,BeforeInputEventPlugin:r}),x.DOM.injectComponentClasses({button:m,form:g,img:y,input:C,option:E,select:R,textarea:M,html:N(v.html),head:N(v.head),body:N(v.body)}),x.CompositeComponent.injectMixin(d),x.DOMProperty.injectDOMPropertyConfig(l),x.DOMProperty.injectDOMPropertyConfig(T),x.EmptyComponent.injectEmptyComponent(v.noscript),x.Updates.injectReconcileTransaction(f.ReactReconcileTransaction),x.Updates.injectBatchingStrategy(h),x.RootIndex.injectCreateReactRootIndex(c.canUseDOM?i.createReactRootIndex:I.createReactRootIndex),x.Component.injectEnvironment(f)}var r=e("./BeforeInputEventPlugin"),o=e("./ChangeEventPlugin"),i=e("./ClientReactRootIndex"),a=e("./CompositionEventPlugin"),s=e("./DefaultEventPluginOrder"),u=e("./EnterLeaveEventPlugin"),c=e("./ExecutionEnvironment"),l=e("./HTMLDOMPropertyConfig"),p=e("./MobileSafariClickEventPlugin"),d=e("./ReactBrowserComponentMixin"),f=e("./ReactComponentBrowserEnvironment"),h=e("./ReactDefaultBatchingStrategy"),v=e("./ReactDOM"),m=e("./ReactDOMButton"),g=e("./ReactDOMForm"),y=e("./ReactDOMImg"),C=e("./ReactDOMInput"),E=e("./ReactDOMOption"),R=e("./ReactDOMSelect"),M=e("./ReactDOMTextarea"),D=e("./ReactEventListener"),x=e("./ReactInjection"),b=e("./ReactInstanceHandles"),O=e("./ReactMount"),P=e("./SelectEventPlugin"),I=e("./ServerReactRootIndex"),_=e("./SimpleEventPlugin"),T=e("./SVGDOMPropertyConfig"),N=e("./createFullPageComponent");t.exports={inject:n}},{"./BeforeInputEventPlugin":2,"./ChangeEventPlugin":6,"./ClientReactRootIndex":7,"./CompositionEventPlugin":8,"./DefaultEventPluginOrder":13,"./EnterLeaveEventPlugin":14,"./ExecutionEnvironment":21,"./HTMLDOMPropertyConfig":22,"./MobileSafariClickEventPlugin":25,"./ReactBrowserComponentMixin":28,"./ReactComponentBrowserEnvironment":32,"./ReactDOM":36,"./ReactDOMButton":37,"./ReactDOMForm":39,"./ReactDOMImg":41,"./ReactDOMInput":42,"./ReactDOMOption":43,"./ReactDOMSelect":44,"./ReactDOMTextarea":46,"./ReactDefaultBatchingStrategy":47,"./ReactEventListener":54,"./ReactInjection":55,"./ReactInstanceHandles":57,"./ReactMount":59,"./SVGDOMPropertyConfig":75,"./SelectEventPlugin":76,"./ServerReactRootIndex":77,"./SimpleEventPlugin":78,"./createFullPageComponent":97}],49:[function(e,t){"use strict";function n(e,t){if("function"==typeof t)for(var n in t)if(t.hasOwnProperty(n)){var r=t[n];e[n]="function"==typeof r?r.bind(t):r}}var r=e("./ReactContext"),o=e("./ReactCurrentOwner"),i=e("./merge"),a=(e("./warning"),function(){});a.createFactory=function(e){var t=Object.create(a.prototype),s=function(e,n){null==e?e={}:"object"==typeof e&&(e=i(e));var a=arguments.length-1;if(1===a)e.children=n;else if(a>1){for(var s=Array(a),u=0;a>u;u++)s[u]=arguments[u+1];e.children=s}var c=Object.create(t);return c._owner=o.current,c._context=r.current,c.props=e,c};return s.prototype=t,s.type=e,t.type=e,n(s,e),t.constructor=s,s},a.cloneAndReplaceProps=function(e,t){var n=Object.create(e.constructor.prototype);return n._owner=e._owner,n._context=e._context,n.props=t,n},a.isValidFactory=function(e){return"function"==typeof e&&e.prototype instanceof a},a.isValidDescriptor=function(e){return e instanceof a},t.exports=a},{"./ReactContext":34,"./ReactCurrentOwner":35,"./merge":128,"./warning":139}],50:[function(e,t){"use strict";function n(){var e=p.current;return e&&e.constructor.displayName||void 0}function r(e,t){e._store.validated||null!=e.props.key||(e._store.validated=!0,i("react_key_warning",'Each child in an array should have a unique "key" prop.',e,t))}function o(e,t,n){m.test(e)&&i("react_numeric_key_warning","Child objects should have non-numeric keys so ordering is preserved.",t,n)}function i(e,t,r,o){var i=n(),a=o.displayName,s=i||a,u=f[e];if(!u.hasOwnProperty(s)){u[s]=!0,t+=i?" Check the render method of "+i+".":" Check the renderComponent call using <"+a+">.";var c=null;r._owner&&r._owner!==p.current&&(c=r._owner.constructor.displayName,t+=" It was passed a child from "+c+"."),t+=" See http://fb.me/react-warning-keys for more information.",d(e,{component:s,componentOwner:c}),console.warn(t)}}function a(){var e=n()||"";h.hasOwnProperty(e)||(h[e]=!0,d("react_object_map_children"))}function s(e,t){if(Array.isArray(e))for(var n=0;n<e.length;n++){var i=e[n];c.isValidDescriptor(i)&&r(i,t)}else if(c.isValidDescriptor(e))e._store.validated=!0;else if(e&&"object"==typeof e){a();for(var s in e)o(s,e[s],t)}}function u(e,t,n,r){for(var o in t)if(t.hasOwnProperty(o)){var i;try{i=t[o](n,o,e,r)}catch(a){i=a}i instanceof Error&&!(i.message in v)&&(v[i.message]=!0,d("react_failed_descriptor_type_check",{message:i.message}))}}var c=e("./ReactDescriptor"),l=e("./ReactPropTypeLocations"),p=e("./ReactCurrentOwner"),d=e("./monitorCodeUse"),f={react_key_warning:{},react_numeric_key_warning:{}},h={},v={},m=/^\d+$/,g={createFactory:function(e,t,n){var r=function(){for(var r=e.apply(this,arguments),o=1;o<arguments.length;o++)s(arguments[o],r.type);var i=r.type.displayName;return t&&u(i,t,r.props,l.prop),n&&u(i,n,r._context,l.context),r};r.prototype=e.prototype,r.type=e.type;for(var o in e)e.hasOwnProperty(o)&&(r[o]=e[o]);return r}};t.exports=g},{"./ReactCurrentOwner":35,"./ReactDescriptor":49,"./ReactPropTypeLocations":66,"./monitorCodeUse":132}],51:[function(e,t){"use strict";function n(){return s(a),a()}function r(e){u[e]=!0}function o(e){delete u[e]}function i(e){return u[e]}var a,s=e("./invariant"),u={},c={injectEmptyComponent:function(e){a=e}},l={deregisterNullComponentID:o,getEmptyComponent:n,injection:c,isNullComponentID:i,registerNullComponentID:r};t.exports=l},{"./invariant":118}],52:[function(e,t){"use strict";var n={guard:function(e){return e}};t.exports=n},{}],53:[function(e,t){"use strict";function n(e){r.enqueueEvents(e),r.processEventQueue()}var r=e("./EventPluginHub"),o={handleTopLevel:function(e,t,o,i){var a=r.extractEvents(e,t,o,i);n(a)}};t.exports=o},{"./EventPluginHub":17}],54:[function(e,t){"use strict";function n(e){var t=l.getID(e),n=c.getReactRootIDFromNodeID(t),r=l.findReactContainerForID(n),o=l.getFirstReactDOM(r);return o}function r(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function o(e){for(var t=l.getFirstReactDOM(d(e.nativeEvent))||window,r=t;r;)e.ancestors.push(r),r=n(r);for(var o=0,i=e.ancestors.length;i>o;o++){t=e.ancestors[o];var a=l.getID(t)||"";v._handleTopLevel(e.topLevelType,t,a,e.nativeEvent)}}function i(e){var t=f(window);e(t)}var a=e("./EventListener"),s=e("./ExecutionEnvironment"),u=e("./PooledClass"),c=e("./ReactInstanceHandles"),l=e("./ReactMount"),p=e("./ReactUpdates"),d=e("./getEventTarget"),f=e("./getUnboundedScrollPosition"),h=e("./mixInto");h(r,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),u.addPoolingTo(r,u.twoArgumentPooler);var v={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:s.canUseDOM?window:null,setHandleTopLevel:function(e){v._handleTopLevel=e},setEnabled:function(e){v._enabled=!!e},isEnabled:function(){return v._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?a.listen(r,t,v.dispatchEvent.bind(null,e)):void 0},trapCapturedEvent:function(e,t,n){var r=n;return r?a.capture(r,t,v.dispatchEvent.bind(null,e)):void 0},monitorScrollValue:function(e){var t=i.bind(null,e);a.listen(window,"scroll",t),a.listen(window,"resize",t)},dispatchEvent:function(e,t){if(v._enabled){var n=r.getPooled(e,t);try{p.batchedUpdates(o,n)}finally{r.release(n)}}}};t.exports=v},{"./EventListener":16,"./ExecutionEnvironment":21,"./PooledClass":26,"./ReactInstanceHandles":57,"./ReactMount":59,"./ReactUpdates":74,"./getEventTarget":109,"./getUnboundedScrollPosition":114,"./mixInto":131}],55:[function(e,t){"use strict";var n=e("./DOMProperty"),r=e("./EventPluginHub"),o=e("./ReactComponent"),i=e("./ReactCompositeComponent"),a=e("./ReactDOM"),s=e("./ReactEmptyComponent"),u=e("./ReactBrowserEventEmitter"),c=e("./ReactPerf"),l=e("./ReactRootIndex"),p=e("./ReactUpdates"),d={Component:o.injection,CompositeComponent:i.injection,DOMProperty:n.injection,EmptyComponent:s.injection,EventPluginHub:r.injection,DOM:a.injection,EventEmitter:u.injection,Perf:c.injection,RootIndex:l.injection,Updates:p.injection};t.exports=d},{"./DOMProperty":10,"./EventPluginHub":17,"./ReactBrowserEventEmitter":29,"./ReactComponent":31,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactEmptyComponent":51,"./ReactPerf":63,"./ReactRootIndex":70,"./ReactUpdates":74}],56:[function(e,t){"use strict";function n(e){return o(document.documentElement,e)}var r=e("./ReactDOMSelection"),o=e("./containsNode"),i=e("./focusNode"),a=e("./getActiveElement"),s={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=a();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=a(),r=e.focusedElem,o=e.selectionRange;t!==r&&n(r)&&(s.hasSelectionCapabilities(r)&&s.setSelection(r,o),i(r))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=r.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,o=t.end;if("undefined"==typeof o&&(o=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(o,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",o-n),i.select()}else r.setOffsets(e,t)}};t.exports=s},{"./ReactDOMSelection":45,"./containsNode":94,"./focusNode":104,"./getActiveElement":106}],57:[function(e,t){"use strict";function n(e){return d+e.toString(36)}function r(e,t){return e.charAt(t)===d||t===e.length}function o(e){return""===e||e.charAt(0)===d&&e.charAt(e.length-1)!==d}function i(e,t){return 0===t.indexOf(e)&&r(t,e.length)}function a(e){return e?e.substr(0,e.lastIndexOf(d)):""}function s(e,t){if(p(o(e)&&o(t)),p(i(e,t)),e===t)return e;for(var n=e.length+f,a=n;a<t.length&&!r(t,a);a++);return t.substr(0,a)}function u(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var i=0,a=0;n>=a;a++)if(r(e,a)&&r(t,a))i=a;else if(e.charAt(a)!==t.charAt(a))break;var s=e.substr(0,i);return p(o(s)),s}function c(e,t,n,r,o,u){e=e||"",t=t||"",p(e!==t);var c=i(t,e);p(c||i(e,t));for(var l=0,d=c?a:s,f=e;;f=d(f,t)){var v;if(o&&f===e||u&&f===t||(v=n(f,c,r)),v===!1||f===t)break;p(l++<h)}}var l=e("./ReactRootIndex"),p=e("./invariant"),d=".",f=d.length,h=100,v={createReactRootID:function(){return n(l.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===d&&e.length>1){var t=e.indexOf(d,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var i=u(e,t);i!==e&&c(e,i,n,r,!1,!0),i!==t&&c(i,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(c("",e,t,n,!0,!1),c(e,"",t,n,!1,!0))},traverseAncestors:function(e,t,n){c("",e,t,n,!0,!1)},_getFirstCommonAncestorID:u,_getNextDescendantID:s,isAncestorIDOf:i,SEPARATOR:d};t.exports=v},{"./ReactRootIndex":70,"./invariant":118}],58:[function(e,t){"use strict";var n=e("./adler32"),r={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=n(e);return e.replace(">"," "+r.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var o=t.getAttribute(r.CHECKSUM_ATTR_NAME);o=o&&parseInt(o,10);var i=n(e);return i===o}};t.exports=r},{"./adler32":93}],59:[function(e,t){"use strict";function n(e){var t=g(e);return t&&T.getID(t)}function r(e){var t=o(e);if(t)if(D.hasOwnProperty(t)){var n=D[t];n!==e&&(C(!s(n,t)),D[t]=e)}else D[t]=e;return t}function o(e){return e&&e.getAttribute&&e.getAttribute(M)||""}function i(e,t){var n=o(e);n!==t&&delete D[n],e.setAttribute(M,t),D[t]=e}function a(e){return D.hasOwnProperty(e)&&s(D[e],e)||(D[e]=T.findReactNodeByID(e)),D[e]}function s(e,t){if(e){C(o(e)===t);var n=T.findReactContainerForID(t);if(n&&m(n,e))return!0}return!1}function u(e){delete D[e]}function c(e){var t=D[e];return t&&s(t,e)?void(_=t):!1}function l(e){_=null,h.traverseAncestors(e,c);var t=_;return _=null,t}var p=e("./DOMProperty"),d=e("./ReactBrowserEventEmitter"),f=(e("./ReactCurrentOwner"),e("./ReactDescriptor")),h=e("./ReactInstanceHandles"),v=e("./ReactPerf"),m=e("./containsNode"),g=e("./getReactRootElementInContainer"),y=e("./instantiateReactComponent"),C=e("./invariant"),E=e("./shouldUpdateReactComponent"),R=(e("./warning"),h.SEPARATOR),M=p.ID_ATTRIBUTE_NAME,D={},x=1,b=9,O={},P={},I=[],_=null,T={_instancesByReactRootID:O,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){var o=t.props;return T.scrollMonitor(n,function(){e.replaceProps(o,r)}),e},_registerComponent:function(e,t){C(t&&(t.nodeType===x||t.nodeType===b)),d.ensureScrollValueMonitoring();var n=T.registerContainer(t);return O[n]=e,n},_renderNewRootComponent:v.measure("ReactMount","_renderNewRootComponent",function(e,t,n){var r=y(e),o=T._registerComponent(r,t);return r.mountComponentIntoNode(o,t,n),r}),renderComponent:function(e,t,r){C(f.isValidDescriptor(e));var o=O[n(t)];if(o){var i=o._descriptor;if(E(i,e))return T._updateRootComponent(o,e,t,r);T.unmountComponentAtNode(t)}var a=g(t),s=a&&T.isRenderedByReact(a),u=s&&!o,c=T._renderNewRootComponent(e,t,u);return r&&r.call(c),c},constructAndRenderComponent:function(e,t,n){return T.renderComponent(e(t),n)},constructAndRenderComponentByID:function(e,t,n){var r=document.getElementById(n);return C(r),T.constructAndRenderComponent(e,t,r)},registerContainer:function(e){var t=n(e);return t&&(t=h.getReactRootIDFromNodeID(t)),t||(t=h.createReactRootID()),P[t]=e,t},unmountComponentAtNode:function(e){var t=n(e),r=O[t];return r?(T.unmountComponentFromNode(r,e),delete O[t],delete P[t],!0):!1},unmountComponentFromNode:function(e,t){for(e.unmountComponent(),t.nodeType===b&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var t=h.getReactRootIDFromNodeID(e),n=P[t];return n},findReactNodeByID:function(e){var t=T.findReactContainerForID(e);return T.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=T.getID(e);return t?t.charAt(0)===R:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(T.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=I,r=0,o=l(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var i,a=n[r++];a;){var s=T.getID(a);s?t===s?i=a:h.isAncestorIDOf(s,t)&&(n.length=r=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,C(!1)},getReactRootID:n,getID:r,setID:i,getNode:a,purgeID:u};t.exports=T},{"./DOMProperty":10,"./ReactBrowserEventEmitter":29,"./ReactCurrentOwner":35,"./ReactDescriptor":49,"./ReactInstanceHandles":57,"./ReactPerf":63,"./containsNode":94,"./getReactRootElementInContainer":112,"./instantiateReactComponent":117,"./invariant":118,"./shouldUpdateReactComponent":136,"./warning":139}],60:[function(e,t){"use strict";function n(e,t,n){h.push({parentID:e,parentNode:null,type:c.INSERT_MARKUP,markupIndex:v.push(t)-1,textContent:null,fromIndex:null,toIndex:n})}function r(e,t,n){h.push({parentID:e,parentNode:null,type:c.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:n})}function o(e,t){h.push({parentID:e,parentNode:null,type:c.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function i(e,t){h.push({parentID:e,parentNode:null,type:c.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function a(){h.length&&(u.BackendIDOperations.dangerouslyProcessChildrenUpdates(h,v),s())}function s(){h.length=0,v.length=0}var u=e("./ReactComponent"),c=e("./ReactMultiChildUpdateTypes"),l=e("./flattenChildren"),p=e("./instantiateReactComponent"),d=e("./shouldUpdateReactComponent"),f=0,h=[],v=[],m={Mixin:{mountChildren:function(e,t){var n=l(e),r=[],o=0;this._renderedChildren=n;for(var i in n){var a=n[i];if(n.hasOwnProperty(i)){var s=p(a);n[i]=s;var u=this._rootNodeID+i,c=s.mountComponent(u,t,this._mountDepth+1);s._mountIndex=o,r.push(c),o++}}return r},updateTextContent:function(e){f++;var t=!0;try{var n=this._renderedChildren;for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setTextContent(e),t=!1}finally{f--,f||(t?s():a())}},updateChildren:function(e,t){f++;var n=!0;try{this._updateChildren(e,t),n=!1}finally{f--,f||(n?s():a())}},_updateChildren:function(e,t){var n=l(e),r=this._renderedChildren;if(n||r){var o,i=0,a=0;for(o in n)if(n.hasOwnProperty(o)){var s=r&&r[o],u=s&&s._descriptor,c=n[o];if(d(u,c))this.moveChild(s,a,i),i=Math.max(s._mountIndex,i),s.receiveComponent(c,t),s._mountIndex=a;else{s&&(i=Math.max(s._mountIndex,i),this._unmountChildByName(s,o));var f=p(c);this._mountChildByNameAtIndex(f,o,a,t)}a++}for(o in r)!r.hasOwnProperty(o)||n&&n[o]||this._unmountChildByName(r[o],o)}},unmountChildren:function(){var e=this._renderedChildren;for(var t in e){var n=e[t];n.unmountComponent&&n.unmountComponent()}this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&r(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){n(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){o(this._rootNodeID,e._mountIndex)},setTextContent:function(e){i(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r){var o=this._rootNodeID+t,i=e.mountComponent(o,r,this._mountDepth+1);e._mountIndex=n,this.createChild(e,i),this._renderedChildren=this._renderedChildren||{},this._renderedChildren[t]=e},_unmountChildByName:function(e,t){this.removeChild(e),e._mountIndex=null,e.unmountComponent(),delete this._renderedChildren[t]}}};t.exports=m},{"./ReactComponent":31,"./ReactMultiChildUpdateTypes":61,"./flattenChildren":103,"./instantiateReactComponent":117,"./shouldUpdateReactComponent":136}],61:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});t.exports=r},{"./keyMirror":124}],62:[function(e,t){"use strict";var n=e("./emptyObject"),r=e("./invariant"),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){r(o.isValidOwner(n)),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(o.isValidOwner(n)),n.refs[t]===e&&n.detachRef(t)},Mixin:{construct:function(){this.refs=n},attachRef:function(e,t){r(t.isOwnedBy(this));var o=this.refs===n?this.refs={}:this.refs;o[e]=t},detachRef:function(e){delete this.refs[e]}}};t.exports=o},{"./emptyObject":101,"./invariant":118}],63:[function(e,t){"use strict";function n(e,t,n){return n}var r={enableMeasure:!1,storedMeasure:n,measure:function(e,t,n){return n},injection:{injectMeasure:function(e){r.storedMeasure=e}}};t.exports=r},{}],64:[function(e,t){"use strict";function n(e){return function(t,n,r){t[n]=t.hasOwnProperty(n)?e(t[n],r):r}}function r(e,t){for(var n in t)if(t.hasOwnProperty(n)){var r=c[n];r&&c.hasOwnProperty(n)?r(e,n,t[n]):e.hasOwnProperty(n)||(e[n]=t[n])}return e}var o=e("./emptyFunction"),i=e("./invariant"),a=e("./joinClasses"),s=e("./merge"),u=n(function(e,t){return s(t,e)}),c={children:o,className:n(a),key:o,ref:o,style:u},l={TransferStrategies:c,mergeProps:function(e,t){return r(s(e),t)},Mixin:{transferPropsTo:function(e){return i(e._owner===this),r(e.props,this.props),e}}};t.exports=l},{"./emptyFunction":100,"./invariant":118,"./joinClasses":123,"./merge":128}],65:[function(e,t){"use strict";var n={};t.exports=n},{}],66:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({prop:null,context:null,childContext:null});t.exports=r},{"./keyMirror":124}],67:[function(e,t){"use strict";function n(e){function t(t,n,r,o,i){if(o=o||C,null!=n[r])return e(n,r,o,i);var a=g[i];return t?new Error("Required "+a+" `"+r+"` was not specified in "+("`"+o+"`.")):void 0}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function r(e){function t(t,n,r,o){var i=t[n],a=h(i);if(a!==e){var s=g[o],u=v(i);return new Error("Invalid "+s+" `"+n+"` of type `"+u+"` "+("supplied to `"+r+"`, expected `"+e+"`."))}}return n(t)}function o(){return n(y.thatReturns())}function i(e){function t(t,n,r,o){var i=t[n];if(!Array.isArray(i)){var a=g[o],s=h(i);return new Error("Invalid "+a+" `"+n+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an array."))}for(var u=0;u<i.length;u++){var c=e(i,u,r,o);if(c instanceof Error)return c}}return n(t)}function a(){function e(e,t,n,r){if(!m.isValidDescriptor(e[t])){var o=g[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a React component."))}}return n(e)}function s(e){function t(t,n,r,o){if(!(t[n]instanceof e)){var i=g[o],a=e.name||C;return new Error("Invalid "+i+" `"+n+"` supplied to "+("`"+r+"`, expected instance of `"+a+"`."))}}return n(t)}function u(e){function t(t,n,r,o){for(var i=t[n],a=0;a<e.length;a++)if(i===e[a])return;var s=g[o],u=JSON.stringify(e);return new Error("Invalid "+s+" `"+n+"` of value `"+i+"` "+("supplied to `"+r+"`, expected one of "+u+"."))}return n(t)}function c(e){function t(t,n,r,o){var i=t[n],a=h(i);if("object"!==a){var s=g[o];return new Error("Invalid "+s+" `"+n+"` of type "+("`"+a+"` supplied to `"+r+"`, expected an object."))}for(var u in i)if(i.hasOwnProperty(u)){var c=e(i,u,r,o);if(c instanceof Error)return c}}return n(t)}function l(e){function t(t,n,r,o){for(var i=0;i<e.length;i++){var a=e[i];if(null==a(t,n,r,o))return}var s=g[o];return new Error("Invalid "+s+" `"+n+"` supplied to "+("`"+r+"`."))}return n(t)}function p(){function e(e,t,n,r){if(!f(e[t])){var o=g[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a renderable prop."))}}return n(e)}function d(e){function t(t,n,r,o){var i=t[n],a=h(i);if("object"!==a){var s=g[o];return new Error("Invalid "+s+" `"+n+"` of type `"+a+"` "+("supplied to `"+r+"`, expected `object`."))}for(var u in e){var c=e[u];if(c){var l=c(i,u,r,o);if(l)return l}}}return n(t,"expected `object`")}function f(e){switch(typeof e){case"number":case"string":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(f);if(m.isValidDescriptor(e))return!0;for(var t in e)if(!f(e[t]))return!1;return!0;default:return!1}}function h(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function v(e){var t=h(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var m=e("./ReactDescriptor"),g=e("./ReactPropTypeLocationNames"),y=e("./emptyFunction"),C="<<anonymous>>",E={array:r("array"),bool:r("boolean"),func:r("function"),number:r("number"),object:r("object"),string:r("string"),any:o(),arrayOf:i,component:a(),instanceOf:s,objectOf:c,oneOf:u,oneOfType:l,renderable:p(),shape:d};t.exports=E},{"./ReactDescriptor":49,"./ReactPropTypeLocationNames":65,"./emptyFunction":100}],68:[function(e,t){"use strict";function n(){this.listenersToPut=[]}var r=e("./PooledClass"),o=e("./ReactBrowserEventEmitter"),i=e("./mixInto");i(n,{enqueuePutListener:function(e,t,n){this.listenersToPut.push({rootNodeID:e,propKey:t,propValue:n})},putListeners:function(){for(var e=0;e<this.listenersToPut.length;e++){var t=this.listenersToPut[e];o.putListener(t.rootNodeID,t.propKey,t.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{"./PooledClass":26,"./ReactBrowserEventEmitter":29,"./mixInto":131}],69:[function(e,t){"use strict";function n(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=r.getPooled(null),this.putListenerQueue=s.getPooled()}var r=e("./CallbackQueue"),o=e("./PooledClass"),i=e("./ReactBrowserEventEmitter"),a=e("./ReactInputSelection"),s=e("./ReactPutListenerQueue"),u=e("./Transaction"),c=e("./mixInto"),l={initialize:a.getSelectionInformation,close:a.restoreSelection},p={initialize:function(){var e=i.isEnabled();return i.setEnabled(!1),e},close:function(e){i.setEnabled(e)}},d={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},f={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},h=[f,l,p,d],v={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){r.release(this.reactMountReady),this.reactMountReady=null,s.release(this.putListenerQueue),this.putListenerQueue=null}};c(n,u.Mixin),c(n,v),o.addPoolingTo(n),t.exports=n},{"./CallbackQueue":5,"./PooledClass":26,"./ReactBrowserEventEmitter":29,"./ReactInputSelection":56,"./ReactPutListenerQueue":68,"./Transaction":90,"./mixInto":131}],70:[function(e,t){"use strict";var n={injectCreateReactRootIndex:function(e){r.createReactRootIndex=e}},r={createReactRootIndex:null,injection:n};t.exports=r},{}],71:[function(e,t){"use strict";function n(e){c(o.isValidDescriptor(e)),c(!(2===arguments.length&&"function"==typeof arguments[1]));var t;try{var n=i.createReactRootID();return t=s.getPooled(!1),t.perform(function(){var r=u(e),o=r.mountComponent(n,t,0);return a.addChecksumToMarkup(o)},null)}finally{s.release(t)}}function r(e){c(o.isValidDescriptor(e));var t;try{var n=i.createReactRootID();return t=s.getPooled(!0),t.perform(function(){var r=u(e);return r.mountComponent(n,t,0)},null)}finally{s.release(t)}}var o=e("./ReactDescriptor"),i=e("./ReactInstanceHandles"),a=e("./ReactMarkupChecksum"),s=e("./ReactServerRenderingTransaction"),u=e("./instantiateReactComponent"),c=e("./invariant");t.exports={renderComponentToString:n,renderComponentToStaticMarkup:r}},{"./ReactDescriptor":49,"./ReactInstanceHandles":57,"./ReactMarkupChecksum":58,"./ReactServerRenderingTransaction":72,"./instantiateReactComponent":117,"./invariant":118}],72:[function(e,t){"use strict";function n(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=o.getPooled(null),this.putListenerQueue=i.getPooled()}var r=e("./PooledClass"),o=e("./CallbackQueue"),i=e("./ReactPutListenerQueue"),a=e("./Transaction"),s=e("./emptyFunction"),u=e("./mixInto"),c={initialize:function(){this.reactMountReady.reset()},close:s},l={initialize:function(){this.putListenerQueue.reset()},close:s},p=[l,c],d={getTransactionWrappers:function(){return p},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null,i.release(this.putListenerQueue),this.putListenerQueue=null}};u(n,a.Mixin),u(n,d),r.addPoolingTo(n),t.exports=n},{"./CallbackQueue":5,"./PooledClass":26,"./ReactPutListenerQueue":68,"./Transaction":90,"./emptyFunction":100,"./mixInto":131}],73:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),r=e("./ReactBrowserComponentMixin"),o=e("./ReactComponent"),i=e("./ReactDescriptor"),a=e("./escapeTextForBrowser"),s=e("./mixInto"),u=function(e){this.construct(e)};s(u,o.Mixin),s(u,r),s(u,{mountComponent:function(e,t,r){o.Mixin.mountComponent.call(this,e,t,r);var i=a(this.props);return t.renderToStaticMarkup?i:"<span "+n.createMarkupForID(e)+">"+i+"</span>"},receiveComponent:function(e){var t=e.props;t!==this.props&&(this.props=t,o.BackendIDOperations.updateTextContentByID(this._rootNodeID,t))}}),t.exports=i.createFactory(u)},{"./DOMPropertyOperations":11,"./ReactBrowserComponentMixin":28,"./ReactComponent":31,"./ReactDescriptor":49,"./escapeTextForBrowser":102,"./mixInto":131}],74:[function(e,t){"use strict";function n(){d(R.ReactReconcileTransaction&&v)}function r(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=u.getPooled(null),this.reconcileTransaction=R.ReactReconcileTransaction.getPooled()}function o(e,t,r){n(),v.batchedUpdates(e,t,r)}function i(e,t){return e._mountDepth-t._mountDepth}function a(e){var t=e.dirtyComponentsLength;d(t===h.length),h.sort(i);for(var n=0;t>n;n++){var r=h[n];if(r.isMounted()){var o=r._pendingCallbacks;if(r._pendingCallbacks=null,r.performUpdateIfNecessary(e.reconcileTransaction),o)for(var a=0;a<o.length;a++)e.callbackQueue.enqueue(o[a],r)}}}function s(e,t){return d(!t||"function"==typeof t),n(),v.isBatchingUpdates?(h.push(e),void(t&&(e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t]))):void v.batchedUpdates(s,e,t)}var u=e("./CallbackQueue"),c=e("./PooledClass"),l=(e("./ReactCurrentOwner"),e("./ReactPerf")),p=e("./Transaction"),d=e("./invariant"),f=e("./mixInto"),h=(e("./warning"),[]),v=null,m={initialize:function(){this.dirtyComponentsLength=h.length},close:function(){this.dirtyComponentsLength!==h.length?(h.splice(0,this.dirtyComponentsLength),C()):h.length=0}},g={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},y=[m,g];f(r,p.Mixin),f(r,{getTransactionWrappers:function(){return y},destructor:function(){this.dirtyComponentsLength=null,u.release(this.callbackQueue),this.callbackQueue=null,R.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return p.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),c.addPoolingTo(r);var C=l.measure("ReactUpdates","flushBatchedUpdates",function(){for(;h.length;){var e=r.getPooled();e.perform(a,null,e),r.release(e)}}),E={injectReconcileTransaction:function(e){d(e),R.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){d(e),d("function"==typeof e.batchedUpdates),d("boolean"==typeof e.isBatchingUpdates),v=e}},R={ReactReconcileTransaction:null,batchedUpdates:o,enqueueUpdate:s,flushBatchedUpdates:C,injection:E};t.exports=R},{"./CallbackQueue":5,"./PooledClass":26,"./ReactCurrentOwner":35,"./ReactPerf":63,"./Transaction":90,"./invariant":118,"./mixInto":131,"./warning":139}],75:[function(e,t){"use strict";var n=e("./DOMProperty"),r=n.injection.MUST_USE_ATTRIBUTE,o={Properties:{cx:r,cy:r,d:r,dx:r,dy:r,fill:r,fillOpacity:r,fontFamily:r,fontSize:r,fx:r,fy:r,gradientTransform:r,gradientUnits:r,markerEnd:r,markerMid:r,markerStart:r,offset:r,opacity:r,patternContentUnits:r,patternUnits:r,points:r,preserveAspectRatio:r,r:r,rx:r,ry:r,spreadMethod:r,stopColor:r,stopOpacity:r,stroke:r,strokeDasharray:r,strokeLinecap:r,strokeOpacity:r,strokeWidth:r,textAnchor:r,transform:r,version:r,viewBox:r,x1:r,x2:r,x:r,y1:r,y2:r,y:r},DOMAttributeNames:{fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox"}}; t.exports=o},{"./DOMProperty":10}],76:[function(e,t){"use strict";function n(e){if("selectionStart"in e&&a.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(document.selection){var t=document.selection.createRange();return{parentElement:t.parentElement(),text:t.text,top:t.boundingTop,left:t.boundingLeft}}var n=window.getSelection();return{anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}}function r(e){if(!g&&null!=h&&h==u()){var t=n(h);if(!m||!p(m,t)){m=t;var r=s.getPooled(f.select,v,e);return r.type="select",r.target=h,i.accumulateTwoPhaseDispatches(r),r}}}var o=e("./EventConstants"),i=e("./EventPropagators"),a=e("./ReactInputSelection"),s=e("./SyntheticEvent"),u=e("./getActiveElement"),c=e("./isTextInputElement"),l=e("./keyOf"),p=e("./shallowEqual"),d=o.topLevelTypes,f={select:{phasedRegistrationNames:{bubbled:l({onSelect:null}),captured:l({onSelectCapture:null})},dependencies:[d.topBlur,d.topContextMenu,d.topFocus,d.topKeyDown,d.topMouseDown,d.topMouseUp,d.topSelectionChange]}},h=null,v=null,m=null,g=!1,y={eventTypes:f,extractEvents:function(e,t,n,o){switch(e){case d.topFocus:(c(t)||"true"===t.contentEditable)&&(h=t,v=n,m=null);break;case d.topBlur:h=null,v=null,m=null;break;case d.topMouseDown:g=!0;break;case d.topContextMenu:case d.topMouseUp:return g=!1,r(o);case d.topSelectionChange:case d.topKeyDown:case d.topKeyUp:return r(o)}}};t.exports=y},{"./EventConstants":15,"./EventPropagators":20,"./ReactInputSelection":56,"./SyntheticEvent":82,"./getActiveElement":106,"./isTextInputElement":121,"./keyOf":125,"./shallowEqual":135}],77:[function(e,t){"use strict";var n=Math.pow(2,53),r={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};t.exports=r},{}],78:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./EventPluginUtils"),o=e("./EventPropagators"),i=e("./SyntheticClipboardEvent"),a=e("./SyntheticEvent"),s=e("./SyntheticFocusEvent"),u=e("./SyntheticKeyboardEvent"),c=e("./SyntheticMouseEvent"),l=e("./SyntheticDragEvent"),p=e("./SyntheticTouchEvent"),d=e("./SyntheticUIEvent"),f=e("./SyntheticWheelEvent"),h=e("./invariant"),v=e("./keyOf"),m=n.topLevelTypes,g={blur:{phasedRegistrationNames:{bubbled:v({onBlur:!0}),captured:v({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:v({onClick:!0}),captured:v({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:v({onContextMenu:!0}),captured:v({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:v({onCopy:!0}),captured:v({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:v({onCut:!0}),captured:v({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:v({onDoubleClick:!0}),captured:v({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:v({onDrag:!0}),captured:v({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:v({onDragEnd:!0}),captured:v({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:v({onDragEnter:!0}),captured:v({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:v({onDragExit:!0}),captured:v({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:v({onDragLeave:!0}),captured:v({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:v({onDragOver:!0}),captured:v({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:v({onDragStart:!0}),captured:v({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:v({onDrop:!0}),captured:v({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:v({onFocus:!0}),captured:v({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:v({onInput:!0}),captured:v({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:v({onKeyDown:!0}),captured:v({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:v({onKeyPress:!0}),captured:v({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:v({onKeyUp:!0}),captured:v({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:v({onLoad:!0}),captured:v({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:v({onError:!0}),captured:v({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:v({onMouseDown:!0}),captured:v({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:v({onMouseMove:!0}),captured:v({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:v({onMouseOut:!0}),captured:v({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:v({onMouseOver:!0}),captured:v({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:v({onMouseUp:!0}),captured:v({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:v({onPaste:!0}),captured:v({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:v({onReset:!0}),captured:v({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:v({onScroll:!0}),captured:v({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:v({onSubmit:!0}),captured:v({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:v({onTouchCancel:!0}),captured:v({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:v({onTouchEnd:!0}),captured:v({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:v({onTouchMove:!0}),captured:v({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:v({onTouchStart:!0}),captured:v({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:v({onWheel:!0}),captured:v({onWheelCapture:!0})}}},y={topBlur:g.blur,topClick:g.click,topContextMenu:g.contextMenu,topCopy:g.copy,topCut:g.cut,topDoubleClick:g.doubleClick,topDrag:g.drag,topDragEnd:g.dragEnd,topDragEnter:g.dragEnter,topDragExit:g.dragExit,topDragLeave:g.dragLeave,topDragOver:g.dragOver,topDragStart:g.dragStart,topDrop:g.drop,topError:g.error,topFocus:g.focus,topInput:g.input,topKeyDown:g.keyDown,topKeyPress:g.keyPress,topKeyUp:g.keyUp,topLoad:g.load,topMouseDown:g.mouseDown,topMouseMove:g.mouseMove,topMouseOut:g.mouseOut,topMouseOver:g.mouseOver,topMouseUp:g.mouseUp,topPaste:g.paste,topReset:g.reset,topScroll:g.scroll,topSubmit:g.submit,topTouchCancel:g.touchCancel,topTouchEnd:g.touchEnd,topTouchMove:g.touchMove,topTouchStart:g.touchStart,topWheel:g.wheel};for(var C in y)y[C].dependencies=[C];var E={eventTypes:g,executeDispatch:function(e,t,n){var o=r.executeDispatch(e,t,n);o===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,r){var v=y[e];if(!v)return null;var g;switch(e){case m.topInput:case m.topLoad:case m.topError:case m.topReset:case m.topSubmit:g=a;break;case m.topKeyPress:if(0===r.charCode)return null;case m.topKeyDown:case m.topKeyUp:g=u;break;case m.topBlur:case m.topFocus:g=s;break;case m.topClick:if(2===r.button)return null;case m.topContextMenu:case m.topDoubleClick:case m.topMouseDown:case m.topMouseMove:case m.topMouseOut:case m.topMouseOver:case m.topMouseUp:g=c;break;case m.topDrag:case m.topDragEnd:case m.topDragEnter:case m.topDragExit:case m.topDragLeave:case m.topDragOver:case m.topDragStart:case m.topDrop:g=l;break;case m.topTouchCancel:case m.topTouchEnd:case m.topTouchMove:case m.topTouchStart:g=p;break;case m.topScroll:g=d;break;case m.topWheel:g=f;break;case m.topCopy:case m.topCut:case m.topPaste:g=i}h(g);var C=g.getPooled(v,n,r);return o.accumulateTwoPhaseDispatches(C),C}};t.exports=E},{"./EventConstants":15,"./EventPluginUtils":19,"./EventPropagators":20,"./SyntheticClipboardEvent":79,"./SyntheticDragEvent":81,"./SyntheticEvent":82,"./SyntheticFocusEvent":83,"./SyntheticKeyboardEvent":85,"./SyntheticMouseEvent":86,"./SyntheticTouchEvent":87,"./SyntheticUIEvent":88,"./SyntheticWheelEvent":89,"./invariant":118,"./keyOf":125}],79:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":82}],80:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={data:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":82}],81:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticMouseEvent"),o={dataTransfer:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticMouseEvent":86}],82:[function(e,t){"use strict";function n(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var r=this.constructor.Interface;for(var i in r)if(r.hasOwnProperty(i)){var a=r[i];this[i]=a?a(n):n[i]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;this.isDefaultPrevented=s?o.thatReturnsTrue:o.thatReturnsFalse,this.isPropagationStopped=o.thatReturnsFalse}var r=e("./PooledClass"),o=e("./emptyFunction"),i=e("./getEventTarget"),a=e("./merge"),s=e("./mergeInto"),u={type:null,target:i,currentTarget:o.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};s(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=o.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=o.thatReturnsTrue},persist:function(){this.isPersistent=o.thatReturnsTrue},isPersistent:o.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),n.Interface=u,n.augmentClass=function(e,t){var n=this,o=Object.create(n.prototype);s(o,e.prototype),e.prototype=o,e.prototype.constructor=e,e.Interface=a(n.Interface,t),e.augmentClass=n.augmentClass,r.addPoolingTo(e,r.threeArgumentPooler)},r.addPoolingTo(n,r.threeArgumentPooler),t.exports=n},{"./PooledClass":26,"./emptyFunction":100,"./getEventTarget":109,"./merge":128,"./mergeInto":130}],83:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o={relatedTarget:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticUIEvent":88}],84:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={data:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":82}],85:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./getEventKey"),i=e("./getEventModifierState"),a={key:o,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:i,charCode:function(e){return"keypress"===e.type?"charCode"in e?e.charCode:e.keyCode:0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return e.keyCode||e.charCode}};r.augmentClass(n,a),t.exports=n},{"./SyntheticUIEvent":88,"./getEventKey":107,"./getEventModifierState":108}],86:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./ViewportMetrics"),i=e("./getEventModifierState"),a={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getEventModifierState:i,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+o.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+o.currentScrollTop}};r.augmentClass(n,a),t.exports=n},{"./SyntheticUIEvent":88,"./ViewportMetrics":91,"./getEventModifierState":108}],87:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./getEventModifierState"),i={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:o};r.augmentClass(n,i),t.exports=n},{"./SyntheticUIEvent":88,"./getEventModifierState":108}],88:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o=e("./getEventTarget"),i={view:function(e){if(e.view)return e.view;var t=o(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};r.augmentClass(n,i),t.exports=n},{"./SyntheticEvent":82,"./getEventTarget":109}],89:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticMouseEvent"),o={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticMouseEvent":86}],90:[function(e,t){"use strict";var n=e("./invariant"),r={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,r,o,i,a,s,u){n(!this.isInTransaction());var c,l;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),l=e.call(t,r,o,i,a,s,u),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return l},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=o.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===o.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(i){}}}},closeAll:function(e){n(this.isInTransaction());for(var t=this.transactionWrappers,r=e;r<t.length;r++){var i,a=t[r],s=this.wrapperInitData[r];try{i=!0,s!==o.OBSERVED_ERROR&&a.close&&a.close.call(this,s),i=!1}finally{if(i)try{this.closeAll(r+1)}catch(u){}}}this.wrapperInitData.length=0}},o={Mixin:r,OBSERVED_ERROR:{}};t.exports=o},{"./invariant":118}],91:[function(e,t){"use strict";var n=e("./getUnboundedScrollPosition"),r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(){var e=n(window);r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};t.exports=r},{"./getUnboundedScrollPosition":114}],92:[function(e,t){"use strict";function n(e,t){if(r(null!=t),null==e)return t;var n=Array.isArray(e),o=Array.isArray(t);return n?e.concat(t):o?[e].concat(t):[e,t]}var r=e("./invariant");t.exports=n},{"./invariant":118}],93:[function(e,t){"use strict";function n(e){for(var t=1,n=0,o=0;o<e.length;o++)t=(t+e.charCodeAt(o))%r,n=(n+t)%r;return t|n<<16}var r=65521;t.exports=n},{}],94:[function(e,t){function n(e,t){return e&&t?e===t?!0:r(e)?!1:r(t)?n(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var r=e("./isTextNode");t.exports=n},{"./isTextNode":122}],95:[function(e,t){function n(e,t,n,r,o,i){e=e||{};for(var a,s=[t,n,r,o,i],u=0;s[u];){a=s[u++];for(var c in a)e[c]=a[c];a.hasOwnProperty&&a.hasOwnProperty("toString")&&"undefined"!=typeof a.toString&&e.toString!==a.toString&&(e.toString=a.toString)}return e}t.exports=n},{}],96:[function(e,t){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function r(e){return n(e)?Array.isArray(e)?e.slice():o(e):[e]}var o=e("./toArray");t.exports=r},{"./toArray":137}],97:[function(e,t){"use strict";function n(e){var t=r.createClass({displayName:"ReactFullPageComponent"+(e.type.displayName||""),componentWillUnmount:function(){o(!1)},render:function(){return this.transferPropsTo(e(null,this.props.children))}});return t}var r=e("./ReactCompositeComponent"),o=e("./invariant");t.exports=n},{"./ReactCompositeComponent":33,"./invariant":118}],98:[function(e,t){function n(e){var t=e.match(c);return t&&t[1].toLowerCase()}function r(e,t){var r=u;s(!!u);var o=n(e),c=o&&a(o);if(c){r.innerHTML=c[1]+e+c[2];for(var l=c[0];l--;)r=r.lastChild}else r.innerHTML=e;var p=r.getElementsByTagName("script");p.length&&(s(t),i(p).forEach(t));for(var d=i(r.childNodes);r.lastChild;)r.removeChild(r.lastChild);return d}var o=e("./ExecutionEnvironment"),i=e("./createArrayFrom"),a=e("./getMarkupWrap"),s=e("./invariant"),u=o.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;t.exports=r},{"./ExecutionEnvironment":21,"./createArrayFrom":96,"./getMarkupWrap":110,"./invariant":118}],99:[function(e,t){"use strict";function n(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||o.hasOwnProperty(e)&&o[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var r=e("./CSSProperty"),o=r.isUnitlessNumber;t.exports=n},{"./CSSProperty":3}],100:[function(e,t){function n(e){return function(){return e}}function r(){}var o=e("./copyProperties");o(r,{thatReturns:n,thatReturnsFalse:n(!1),thatReturnsTrue:n(!0),thatReturnsNull:n(null),thatReturnsThis:function(){return this},thatReturnsArgument:function(e){return e}}),t.exports=r},{"./copyProperties":95}],101:[function(e,t){"use strict";var n={};t.exports=n},{}],102:[function(e,t){"use strict";function n(e){return o[e]}function r(e){return(""+e).replace(i,n)}var o={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},i=/[&><"']/g;t.exports=r},{}],103:[function(e,t){"use strict";function n(e,t,n){var r=e,o=!r.hasOwnProperty(n);o&&null!=t&&(r[n]=t)}function r(e){if(null==e)return e;var t={};return o(e,n,t),t}{var o=e("./traverseAllChildren");e("./warning")}t.exports=r},{"./traverseAllChildren":138,"./warning":139}],104:[function(e,t){"use strict";function n(e){e.disabled||e.focus()}t.exports=n},{}],105:[function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=n},{}],106:[function(e,t){function n(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=n},{}],107:[function(e,t){"use strict";function n(e){if(e.key){var t=o[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n="charCode"in e?e.charCode:e.keyCode;return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?i[e.keyCode]||"Unidentified":void r(!1)}var r=e("./invariant"),o={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},i={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};t.exports=n},{"./invariant":118}],108:[function(e,t){"use strict";function n(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=o[e.toLowerCase()];return r&&n[r]}function r(){return n}var o={alt:"altKey",control:"ctrlKey",meta:"metaKey",shift:"shiftKey"};t.exports=r},{}],109:[function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=n},{}],110:[function(e,t){function n(e){return o(!!i),p.hasOwnProperty(e)||(e="*"),a.hasOwnProperty(e)||(i.innerHTML="*"===e?"<link />":"<"+e+"></"+e+">",a[e]=!i.firstChild),a[e]?p[e]:null}var r=e("./ExecutionEnvironment"),o=e("./invariant"),i=r.canUseDOM?document.createElement("div"):null,a={circle:!0,defs:!0,ellipse:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},s=[1,'<select multiple="true">',"</select>"],u=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],l=[1,"<svg>","</svg>"],p={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:u,colgroup:u,tbody:u,tfoot:u,thead:u,td:c,th:c,circle:l,defs:l,ellipse:l,g:l,line:l,linearGradient:l,path:l,polygon:l,polyline:l,radialGradient:l,rect:l,stop:l,text:l};t.exports=n},{"./ExecutionEnvironment":21,"./invariant":118}],111:[function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function r(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function o(e,t){for(var o=n(e),i=0,a=0;o;){if(3==o.nodeType){if(a=i+o.textContent.length,t>=i&&a>=t)return{node:o,offset:t-i};i=a}o=n(r(o))}}t.exports=o},{}],112:[function(e,t){"use strict";function n(e){return e?e.nodeType===r?e.documentElement:e.firstChild:null}var r=9;t.exports=n},{}],113:[function(e,t){"use strict";function n(){return!o&&r.canUseDOM&&(o="textContent"in document.documentElement?"textContent":"innerText"),o}var r=e("./ExecutionEnvironment"),o=null;t.exports=n},{"./ExecutionEnvironment":21}],114:[function(e,t){"use strict";function n(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=n},{}],115:[function(e,t){function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;t.exports=n},{}],116:[function(e,t){"use strict";function n(e){return r(e).replace(o,"-ms-")}var r=e("./hyphenate"),o=/^ms-/;t.exports=n},{"./hyphenate":115}],117:[function(e,t){"use strict";function n(e){return e&&"function"==typeof e.type&&"function"==typeof e.type.prototype.mountComponent&&"function"==typeof e.type.prototype.receiveComponent}function r(e){return o(n(e)),new e.type(e)}var o=e("./invariant");t.exports=r},{"./invariant":118}],118:[function(e,t){"use strict";var n=function(e,t,n,r,o,i,a,s){if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,s],l=0;u=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return c[l++]}))}throw u.framesToPop=1,u}};t.exports=n},{}],119:[function(e,t){"use strict";function n(e,t){if(!o.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,i=n in document;if(!i){var a=document.createElement("div");a.setAttribute(n,"return;"),i="function"==typeof a[n]}return!i&&r&&"wheel"===e&&(i=document.implementation.hasFeature("Events.wheel","3.0")),i}var r,o=e("./ExecutionEnvironment");o.canUseDOM&&(r=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=n},{"./ExecutionEnvironment":21}],120:[function(e,t){function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=n},{}],121:[function(e,t){"use strict";function n(e){return e&&("INPUT"===e.nodeName&&r[e.type]||"TEXTAREA"===e.nodeName)}var r={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=n},{}],122:[function(e,t){function n(e){return r(e)&&3==e.nodeType}var r=e("./isNode");t.exports=n},{"./isNode":120}],123:[function(e,t){"use strict";function n(e){e||(e="");var t,n=arguments.length;if(n>1)for(var r=1;n>r;r++)t=arguments[r],t&&(e+=" "+t);return e}t.exports=n},{}],124:[function(e,t){"use strict";var n=e("./invariant"),r=function(e){var t,r={};n(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(r[t]=t);return r};t.exports=r},{"./invariant":118}],125:[function(e,t){var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=n},{}],126:[function(e,t){"use strict";function n(e,t,n){if(!e)return null;var r=0,o={};for(var i in e)e.hasOwnProperty(i)&&(o[i]=t.call(n,e[i],i,r++));return o}t.exports=n},{}],127:[function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)?t[n]:t[n]=e.call(this,n)}}t.exports=n},{}],128:[function(e,t){"use strict";var n=e("./mergeInto"),r=function(e,t){var r={};return n(r,e),n(r,t),r};t.exports=r},{"./mergeInto":130}],129:[function(e,t){"use strict";var n=e("./invariant"),r=e("./keyMirror"),o=36,i=function(e){return"object"!=typeof e||null===e},a={MAX_MERGE_DEPTH:o,isTerminal:i,normalizeMergeArg:function(e){return void 0===e||null===e?{}:e},checkMergeArrayArgs:function(e,t){n(Array.isArray(e)&&Array.isArray(t))},checkMergeObjectArgs:function(e,t){a.checkMergeObjectArg(e),a.checkMergeObjectArg(t)},checkMergeObjectArg:function(e){n(!i(e)&&!Array.isArray(e))},checkMergeIntoObjectArg:function(e){n(!(i(e)&&"function"!=typeof e||Array.isArray(e)))},checkMergeLevel:function(e){n(o>e)},checkArrayStrategy:function(e){n(void 0===e||e in a.ArrayStrategies)},ArrayStrategies:r({Clobber:!0,IndexByIndex:!0})};t.exports=a},{"./invariant":118,"./keyMirror":124}],130:[function(e,t){"use strict";function n(e,t){if(i(e),null!=t){o(t);for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}}var r=e("./mergeHelpers"),o=r.checkMergeObjectArg,i=r.checkMergeIntoObjectArg;t.exports=n},{"./mergeHelpers":129}],131:[function(e,t){"use strict";var n=function(e,t){var n;for(n in t)t.hasOwnProperty(n)&&(e.prototype[n]=t[n])};t.exports=n},{}],132:[function(e,t){"use strict";function n(e){r(e&&!/[^a-z0-9_]/.test(e))}var r=e("./invariant");t.exports=n},{"./invariant":118}],133:[function(e,t){"use strict";function n(e){return o(r.isValidDescriptor(e)),e}var r=e("./ReactDescriptor"),o=e("./invariant");t.exports=n},{"./ReactDescriptor":49,"./invariant":118}],134:[function(e,t){"use strict";var n=e("./ExecutionEnvironment"),r=function(e,t){e.innerHTML=t};if(n.canUseDOM){var o=document.createElement("div");o.innerHTML=" ",""===o.innerHTML&&(r=function(e,t){e.parentNode&&e.parentNode.replaceChild(e,e),t.match(/^[ \r\n\t\f]/)||"<"===t[0]&&(-1!==t.indexOf("<noscript")||-1!==t.indexOf("<script")||-1!==t.indexOf("<style")||-1!==t.indexOf("<meta")||-1!==t.indexOf("<link"))?(e.innerHTML=""+t,e.firstChild.deleteData(0,1)):e.innerHTML=t})}t.exports=r},{"./ExecutionEnvironment":21}],135:[function(e,t){"use strict";function n(e,t){if(e===t)return!0;var n;for(n in e)if(e.hasOwnProperty(n)&&(!t.hasOwnProperty(n)||e[n]!==t[n]))return!1;for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}t.exports=n},{}],136:[function(e,t){"use strict";function n(e,t){return e&&t&&e.type===t.type&&(e.props&&e.props.key)===(t.props&&t.props.key)&&e._owner===t._owner?!0:!1}t.exports=n},{}],137:[function(e,t){function n(e){var t=e.length;if(r(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),r("number"==typeof t),r(0===t||t-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var o=Array(t),i=0;t>i;i++)o[i]=e[i];return o}var r=e("./invariant");t.exports=n},{"./invariant":118}],138:[function(e,t){"use strict";function n(e){return d[e]}function r(e,t){return e&&e.props&&null!=e.props.key?i(e.props.key):t.toString(36)}function o(e){return(""+e).replace(f,n)}function i(e){return"$"+o(e)}function a(e,t,n){return null==e?0:h(e,"",0,t,n)}var s=e("./ReactInstanceHandles"),u=e("./ReactTextComponent"),c=e("./invariant"),l=s.SEPARATOR,p=":",d={"=":"=0",".":"=1",":":"=2"},f=/[=.:]/g,h=function(e,t,n,o,a){var s=0;if(Array.isArray(e))for(var d=0;d<e.length;d++){var f=e[d],v=t+(t?p:l)+r(f,d),m=n+s;s+=h(f,v,m,o,a)}else{var g=typeof e,y=""===t,C=y?l+r(e,0):t;if(null==e||"boolean"===g)o(a,null,C,n),s=1;else if(e.type&&e.type.prototype&&e.type.prototype.mountComponentIntoNode)o(a,e,C,n),s=1;else if("object"===g){c(!e||1!==e.nodeType);for(var E in e)e.hasOwnProperty(E)&&(s+=h(e[E],t+(t?p:l)+i(E)+p+r(e[E],0),n+s,o,a))}else if("string"===g){var R=u(e);o(a,R,C,n),s+=1}else if("number"===g){var M=u(""+e);o(a,M,C,n),s+=1}}return s};t.exports=a},{"./ReactInstanceHandles":57,"./ReactTextComponent":73,"./invariant":118}],139:[function(e,t){"use strict";var n=e("./emptyFunction"),r=n;t.exports=r},{"./emptyFunction":100}]},{},[27])(27)});
src/components/icons/QueueAdd.js
niekert/soundify
import React from 'react'; import PropTypes from 'prop-types'; const QueueAdd = ({ fill, ...props }) => <svg fill={fill} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" {...props} > <path d="M0 0h24v24H0z" fill="none" /> <path d="M14 10H2v2h12v-2zm0-4H2v2h12V6zm4 8v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zM2 16h8v-2H2v2z" /> </svg>; QueueAdd.propTypes = { fill: PropTypes.string, }; QueueAdd.defaultProps = { fill: 'currentColor', }; export default QueueAdd;
ajax/libs/dc/2.0.0-alpha.3/dc.js
dominic/cdnjs
/*! * dc 2.0.0-alpha.3 * http://dc-js.github.io/dc.js/ * Copyright 2012 Nick Zhu and other contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function() { function _dc(d3, crossfilter) { 'use strict'; /** #### Version 2.0.0-alpha.3 The entire dc.js library is scoped under the **dc** name space. It does not introduce anything else into the global name space. #### Function Chaining Most dc functions are designed to allow function chaining, meaning they return the current chart instance whenever it is appropriate. This way chart configuration can be written in the following style: ```js chart.width(300) .height(300) .filter('sunday') ``` The getter forms of functions do not participate in function chaining because they necessarily return values that are not the chart. (Although some, such as `.svg` and `.xAxis`, return values that are chainable d3 objects.) **/ /*jshint -W062*/ /*jshint -W079*/ var dc = { version: '2.0.0-alpha.3', constants: { CHART_CLASS: 'dc-chart', DEBUG_GROUP_CLASS: 'debug', STACK_CLASS: 'stack', DESELECTED_CLASS: 'deselected', SELECTED_CLASS: 'selected', NODE_INDEX_NAME: '__index__', GROUP_INDEX_NAME: '__group_index__', DEFAULT_CHART_GROUP: '__default_chart_group__', EVENT_DELAY: 40, NEGLIGIBLE_NUMBER: 1e-10 }, _renderlet: null }; dc.chartRegistry = function () { // chartGroup:string => charts:array var _chartMap = {}; function initializeChartGroup(group) { if (!group) { group = dc.constants.DEFAULT_CHART_GROUP; } if (!_chartMap[group]) { _chartMap[group] = []; } return group; } return { has: function (chart) { for (var e in _chartMap) { if (_chartMap[e].indexOf(chart) >= 0) { return true; } } return false; }, register: function (chart, group) { group = initializeChartGroup(group); _chartMap[group].push(chart); }, deregister: function (chart, group) { group = initializeChartGroup(group); for (var i = 0; i < _chartMap[group].length; i++) { if (_chartMap[group][i].anchorName() === chart.anchorName()) { _chartMap[group].splice(i, 1); break; } } }, clear: function (group) { if (group) { delete _chartMap[group]; } else { _chartMap = {}; } }, list: function (group) { group = initializeChartGroup(group); return _chartMap[group]; } }; }(); /*jshint +W062 */ /*jshint +W079*/ dc.registerChart = function (chart, group) { dc.chartRegistry.register(chart, group); }; dc.deregisterChart = function (chart, group) { dc.chartRegistry.deregister(chart, group); }; dc.hasChart = function (chart) { return dc.chartRegistry.has(chart); }; dc.deregisterAllCharts = function (group) { dc.chartRegistry.clear(group); }; /** ## Utilities **/ /** #### dc.filterAll([chartGroup]) Clear all filters on all charts within the given chart group. If the chart group is not given then only charts that belong to the default chart group will be reset. **/ dc.filterAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].filterAll(); } }; /** #### dc.refocusAll([chartGroup]) Reset zoom level / focus on all charts that belong to the given chart group. If the chart group is not given then only charts that belong to the default chart group will be reset. **/ dc.refocusAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { if (charts[i].focus) { charts[i].focus(); } } }; /** #### dc.renderAll([chartGroup]) Re-render all charts belong to the given chart group. If the chart group is not given then only charts that belong to the default chart group will be re-rendered. **/ dc.renderAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].render(); } if (dc._renderlet !== null) { dc._renderlet(group); } }; /** #### dc.redrawAll([chartGroup]) Redraw all charts belong to the given chart group. If the chart group is not given then only charts that belong to the default chart group will be re-drawn. Redraw is different from re-render since when redrawing dc tries to update the graphic incrementally, using transitions, instead of starting from scratch. **/ dc.redrawAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].redraw(); } if (dc._renderlet !== null) { dc._renderlet(group); } }; /** #### dc.disableTransitions If this boolean is set truthy, all transitions will be disabled, and changes to the charts will happen immediately. Default: false **/ dc.disableTransitions = false; dc.transition = function (selections, duration, callback) { if (duration <= 0 || duration === undefined || dc.disableTransitions) { return selections; } var s = selections .transition() .duration(duration); if (typeof(callback) === 'function') { callback(s); } return s; }; dc.units = {}; /** #### dc.units.integers `dc.units.integers` is the default value for `xUnits` for the [Coordinate Grid Chart](#coordinate-grid-chart) and should be used when the x values are a sequence of integers. It is a function that counts the number of integers in the range supplied in its start and end parameters. ```js chart.xUnits(dc.units.integers) // already the default ``` **/ dc.units.integers = function (s, e) { return Math.abs(e - s); }; /** #### dc.units.ordinal This argument can be passed to the `xUnits` function of the to specify ordinal units for the x axis. Usually this parameter is used in combination with passing `d3.scale.ordinal()` to `.x`. It just returns the domain passed to it, which for ordinal charts is an array of all values. ```js chart.xUnits(dc.units.ordinal) .x(d3.scale.ordinal()) ``` **/ dc.units.ordinal = function (s, e, domain) { return domain; }; /** #### dc.units.fp.precision(precision) This function generates an argument for the [Coordinate Grid Chart's](#coordinate-grid-chart) `xUnits` function specifying that the x values are floating-point numbers with the given precision. The returned function determines how many values at the given precision will fit into the range supplied in its start and end parameters. ```js // specify values (and ticks) every 0.1 units chart.xUnits(dc.units.fp.precision(0.1) // there are 500 units between 0.5 and 1 if the precision is 0.001 var thousandths = dc.units.fp.precision(0.001); thousandths(0.5, 1.0) // returns 500 ``` **/ dc.units.fp = {}; dc.units.fp.precision = function (precision) { var _f = function (s, e) { var d = Math.abs((e - s) / _f.resolution); if (dc.utils.isNegligible(d - Math.floor(d))) { return Math.floor(d); } else { return Math.ceil(d); } }; _f.resolution = precision; return _f; }; dc.round = {}; dc.round.floor = function (n) { return Math.floor(n); }; dc.round.ceil = function (n) { return Math.ceil(n); }; dc.round.round = function (n) { return Math.round(n); }; dc.override = function (obj, functionName, newFunction) { var existingFunction = obj[functionName]; obj['_' + functionName] = existingFunction; obj[functionName] = newFunction; }; dc.renderlet = function (_) { if (!arguments.length) { return dc._renderlet; } dc._renderlet = _; return dc; }; dc.instanceOfChart = function (o) { return o instanceof Object && o.__dcFlag__ && true; }; dc.errors = {}; dc.errors.Exception = function (msg) { var _msg = msg || 'Unexpected internal error'; this.message = _msg; this.toString = function () { return _msg; }; }; dc.errors.InvalidStateException = function () { dc.errors.Exception.apply(this, arguments); }; dc.dateFormat = d3.time.format('%m/%d/%Y'); dc.printers = {}; dc.printers.filters = function (filters) { var s = ''; for (var i = 0; i < filters.length; ++i) { if (i > 0) { s += ', '; } s += dc.printers.filter(filters[i]); } return s; }; dc.printers.filter = function (filter) { var s = ''; if (typeof filter !== 'undefined' && filter !== null) { if (filter instanceof Array) { if (filter.length >= 2) { s = '[' + dc.utils.printSingleValue(filter[0]) + ' -> ' + dc.utils.printSingleValue(filter[1]) + ']'; } else if (filter.length >= 1) { s = dc.utils.printSingleValue(filter[0]); } } else { s = dc.utils.printSingleValue(filter); } } return s; }; dc.pluck = function (n, f) { if (!f) { return function (d) { return d[n]; }; } return function (d, i) { return f.call(d, d[n], i); }; }; dc.utils = {}; dc.utils.printSingleValue = function (filter) { var s = '' + filter; if (filter instanceof Date) { s = dc.dateFormat(filter); } else if (typeof(filter) === 'string') { s = filter; } else if (dc.utils.isFloat(filter)) { s = dc.utils.printSingleValue.fformat(filter); } else if (dc.utils.isInteger(filter)) { s = Math.round(filter); } return s; }; dc.utils.printSingleValue.fformat = d3.format('.2f'); // FIXME: these assume than any string r is a percentage (whether or not it // includes %). They also generate strange results if l is a string. dc.utils.add = function (l, r) { if (typeof r === 'string') { r = r.replace('%', ''); } if (l instanceof Date) { if (typeof r === 'string') { r = +r; } var d = new Date(); d.setTime(l.getTime()); d.setDate(l.getDate() + r); return d; } else if (typeof r === 'string') { var percentage = (+r / 100); return l > 0 ? l * (1 + percentage) : l * (1 - percentage); } else { return l + r; } }; dc.utils.subtract = function (l, r) { if (typeof r === 'string') { r = r.replace('%', ''); } if (l instanceof Date) { if (typeof r === 'string') { r = +r; } var d = new Date(); d.setTime(l.getTime()); d.setDate(l.getDate() - r); return d; } else if (typeof r === 'string') { var percentage = (+r / 100); return l < 0 ? l * (1 + percentage) : l * (1 - percentage); } else { return l - r; } }; dc.utils.isNumber = function (n) { return n === +n; }; dc.utils.isFloat = function (n) { return n === +n && n !== (n | 0); }; dc.utils.isInteger = function (n) { return n === +n && n === (n | 0); }; dc.utils.isNegligible = function (n) { return !dc.utils.isNumber(n) || (n < dc.constants.NEGLIGIBLE_NUMBER && n > -dc.constants.NEGLIGIBLE_NUMBER); }; dc.utils.clamp = function (val, min, max) { return val < min ? min : (val > max ? max : val); }; var _idCounter = 0; dc.utils.uniqueId = function () { return ++_idCounter; }; dc.utils.nameToId = function (name) { return name.toLowerCase().replace(/[\s]/g, '_').replace(/[\.']/g, ''); }; dc.utils.appendOrSelect = function (parent, selector, tag) { tag = tag || selector; var element = parent.select(selector); if (element.empty()) { element = parent.append(tag); } return element; }; dc.utils.safeNumber = function (n) { return dc.utils.isNumber(+n) ? +n : 0;}; dc.logger = {}; dc.logger.enableDebugLog = false; dc.logger.warn = function (msg) { if (console) { if (console.warn) { console.warn(msg); } else if (console.log) { console.log(msg); } } return dc.logger; }; dc.logger.debug = function (msg) { if (dc.logger.enableDebugLog && console) { if (console.debug) { console.debug(msg); } else if (console.log) { console.log(msg); } } return dc.logger; }; dc.events = { current: null }; /** #### dc.events.trigger(function[, delay]) This function triggers a throttled event function with a specified delay (in milli-seconds). Events that are triggered repetitively due to user interaction such brush dragging might flood the library and invoke more renders than can be executed in time. Using this function to wrap your event function allows the library to smooth out the rendering by throttling events and only responding to the most recent event. ```js chart.renderlet(function(chart){ // smooth the rendering through event throttling dc.events.trigger(function(){ // focus some other chart to the range selected by user on this chart someOtherChart.focus(chart.filter()); }); }) ``` **/ dc.events.trigger = function (closure, delay) { if (!delay) { closure(); return; } dc.events.current = closure; setTimeout(function () { if (closure === dc.events.current) { closure(); } }, delay); }; dc.filters = {}; /** ## Filters The dc.js filters are functions which are passed into crossfilter to chose which records will be accumulated to produce values for the charts. In the crossfilter model, any filters applied on one dimension will affect all the other dimensions but not that one. dc always applies a filter function to the dimension; the function combines multiple filters and if any of them accept a record, it is filtered in. These filter constructors are used as appropriate by the various charts to implement brushing. We mention below which chart uses which filter. In some cases, many instances of a filter will be added. **/ /** #### dc.filters.RangedFilter(low, high) RangedFilter is a filter which accepts keys between `low` and `high`. It is used to implement X axis brushing for the [coordinate grid charts](#coordinate-grid-mixin). **/ dc.filters.RangedFilter = function (low, high) { var range = new Array(low, high); range.isFiltered = function (value) { return value >= this[0] && value < this[1]; }; return range; }; /** #### dc.filters.TwoDimensionalFilter(array) TwoDimensionalFilter is a filter which accepts a single two-dimensional value. It is used by the [heat map chart](#heat-map) to include particular cells as they are clicked. (Rows and columns are filtered by filtering all the cells in the row or column.) **/ dc.filters.TwoDimensionalFilter = function (array) { if (array === null) { return null; } var filter = array; filter.isFiltered = function (value) { return value.length && value.length === filter.length && value[0] === filter[0] && value[1] === filter[1]; }; return filter; }; /** #### dc.filters.RangedTwoDimensionalFilter(array) The RangedTwoDimensionalFilter allows filtering all values which fit within a rectangular region. It is used by the [scatter plot](#scatter-plot) to implement rectangular brushing. It takes two two-dimensional points in the form `[[x1,y1],[x2,y2]]`, and normalizes them so that `x1 <= x2` and `y1 <- y2`. It then returns a filter which accepts any points which are in the rectangular range including the lower values but excluding the higher values. If an array of two values are given to the RangedTwoDimensionalFilter, it interprets the values as two x coordinates `x1` and `x2` and returns a filter which accepts any points for which `x1 <= x < x2`. **/ dc.filters.RangedTwoDimensionalFilter = function (array) { if (array === null) { return null; } var filter = array; var fromBottomLeft; if (filter[0] instanceof Array) { fromBottomLeft = [ [Math.min(array[0][0], array[1][0]), Math.min(array[0][1], array[1][1])], [Math.max(array[0][0], array[1][0]), Math.max(array[0][1], array[1][1])] ]; } else { fromBottomLeft = [[array[0], -Infinity], [array[1], Infinity]]; } filter.isFiltered = function (value) { var x, y; if (value instanceof Array) { if (value.length !== 2) { return false; } x = value[0]; y = value[1]; } else { x = value; y = fromBottomLeft[0][1]; } return x >= fromBottomLeft[0][0] && x < fromBottomLeft[1][0] && y >= fromBottomLeft[0][1] && y < fromBottomLeft[1][1]; }; return filter; }; /** ## Base Mixin Base Mixin is an abstract functional object representing a basic dc chart object for all chart and widget implementations. Methods from the Base Mixin are inherited and available on all chart implementation in the DC library. **/ dc.baseMixin = function (_chart) { _chart.__dcFlag__ = dc.utils.uniqueId(); var _dimension; var _group; var _anchor; var _root; var _svg; var _minWidth = 200; var _defaultWidth = function (element) { var width = element && element.getBoundingClientRect && element.getBoundingClientRect().width; return (width && width > _minWidth) ? width : _minWidth; }; var _width = _defaultWidth; var _minHeight = 200; var _defaultHeight = function (element) { var height = element && element.getBoundingClientRect && element.getBoundingClientRect().height; return (height && height > _minHeight) ? height : _minHeight; }; var _height = _defaultHeight; var _keyAccessor = dc.pluck('key'); var _valueAccessor = dc.pluck('value'); var _label = dc.pluck('key'); var _ordering = dc.pluck('key'); var _orderSort; var _renderLabel = false; var _title = function (d) { return _chart.keyAccessor()(d) + ': ' + _chart.valueAccessor()(d); }; var _renderTitle = true; var _transitionDuration = 750; var _filterPrinter = dc.printers.filters; var _renderlets = []; var _mandatoryAttributes = ['dimension', 'group']; var _chartGroup = dc.constants.DEFAULT_CHART_GROUP; var _listeners = d3.dispatch( 'preRender', 'postRender', 'preRedraw', 'postRedraw', 'filtered', 'zoomed'); var _legend; var _filters = []; var _filterHandler = function (dimension, filters) { dimension.filter(null); if (filters.length === 0) { dimension.filter(null); } else { dimension.filterFunction(function (d) { for (var i = 0; i < filters.length; i++) { var filter = filters[i]; if (filter.isFiltered && filter.isFiltered(d)) { return true; } else if (filter <= d && filter >= d) { return true; } } return false; }); } return filters; }; var _data = function (group) { return group.all(); }; /** #### .width([value]) Set or get the width attribute of a chart. See `.height` below for further description of the behavior. **/ _chart.width = function (w) { if (!arguments.length) { return _width(_root.node()); } _width = d3.functor(w || _defaultWidth); return _chart; }; /** #### .height([value]) Set or get the height attribute of a chart. The height is applied to the SVG element generated by the chart when rendered (or rerendered). If a value is given, then it will be used to calculate the new height and the chart returned for method chaining. The value can either be a numeric, a function, or falsy. If no value is specified then the value of the current height attribute will be returned. By default, without an explicit height being given, the chart will select the width of its anchor element. If that isn't possible it defaults to 200. Setting the value falsy will return the chart to the default behavior Examples: ```js chart.height(250); // Set the chart's height to 250px; chart.height(function(anchor) { return doSomethingWith(anchor); }); // set the chart's height with a function chart.height(null); // reset the height to the default auto calculation ``` **/ _chart.height = function (h) { if (!arguments.length) { return _height(_root.node()); } _height = d3.functor(h || _defaultHeight); return _chart; }; /** #### .minWidth([value]) Set or get the minimum width attribute of a chart. This only applicable if the width is calculated by dc. **/ _chart.minWidth = function (w) { if (!arguments.length) { return _minWidth; } _minWidth = w; return _chart; }; /** #### .minHeight([value]) Set or get the minimum height attribute of a chart. This only applicable if the height is calculated by dc. **/ _chart.minHeight = function (w) { if (!arguments.length) { return _minHeight; } _minHeight = w; return _chart; }; /** #### .dimension([value]) - **mandatory** Set or get the dimension attribute of a chart. In dc a dimension can be any valid [crossfilter dimension](https://github.com/square/crossfilter/wiki/API-Reference#wiki-dimension). If a value is given, then it will be used as the new dimension. If no value is specified then the current dimension will be returned. **/ _chart.dimension = function (d) { if (!arguments.length) { return _dimension; } _dimension = d; _chart.expireCache(); return _chart; }; /** #### .data([callback]) Set the data callback or retrieve the chart's data set. The data callback is passed the chart's group and by default will return `group.all()`. This behavior may be modified to, for instance, return only the top 5 groups: ``` chart.data(function(group) { return group.top(5); }); ``` **/ _chart.data = function (d) { if (!arguments.length) { return _data.call(_chart, _group); } _data = d3.functor(d); _chart.expireCache(); return _chart; }; /** #### .group([value, [name]]) - **mandatory** Set or get the group attribute of a chart. In dc a group is a [crossfilter group](https://github.com/square/crossfilter/wiki/API-Reference#wiki-group). Usually the group should be created from the particular dimension associated with the same chart. If a value is given, then it will be used as the new group. If no value specified then the current group will be returned. If `name` is specified then it will be used to generate legend label. **/ _chart.group = function (g, name) { if (!arguments.length) { return _group; } _group = g; _chart._groupName = name; _chart.expireCache(); return _chart; }; /** #### .ordering([orderFunction]) Get or set an accessor to order ordinal charts **/ _chart.ordering = function (o) { if (!arguments.length) { return _ordering; } _ordering = o; _orderSort = crossfilter.quicksort.by(_ordering); _chart.expireCache(); return _chart; }; _chart._computeOrderedGroups = function (data) { var dataCopy = data.slice(0); if (dataCopy.length <= 1) { return dataCopy; } if (!_orderSort) { _orderSort = crossfilter.quicksort.by(_ordering); } return _orderSort(dataCopy, 0, dataCopy.length); }; /** #### .filterAll() Clear all filters associated with this chart. **/ _chart.filterAll = function () { return _chart.filter(null); }; /** #### .select(selector) Execute d3 single selection in the chart's scope using the given selector and return the d3 selection. Roughly the same as: ```js d3.select('#chart-id').select(selector); ``` This function is **not chainable** since it does not return a chart instance; however the d3 selection result can be chained to d3 function calls. **/ _chart.select = function (s) { return _root.select(s); }; /** #### .selectAll(selector) Execute in scope d3 selectAll using the given selector and return d3 selection result. Roughly the same as: ```js d3.select('#chart-id').selectAll(selector); ``` This function is **not chainable** since it does not return a chart instance; however the d3 selection result can be chained to d3 function calls. **/ _chart.selectAll = function (s) { return _root ? _root.selectAll(s) : null; }; /** #### .anchor([anchorChart|anchorSelector|anchorNode], [chartGroup]) Set the svg root to either be an existing chart's root; or any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. Optionally registers the chart within the chartGroup. This class is called internally on chart initialization, but be called again to relocate the chart. However, it will orphan any previously created SVG elements. **/ _chart.anchor = function (a, chartGroup) { if (!arguments.length) { return _anchor; } if (dc.instanceOfChart(a)) { _anchor = a.anchor(); _root = a.root(); } else { _anchor = a; _root = d3.select(_anchor); _root.classed(dc.constants.CHART_CLASS, true); dc.registerChart(_chart, chartGroup); } _chartGroup = chartGroup; return _chart; }; /** #### .anchorName() Returns the dom id for the chart's anchored location. **/ _chart.anchorName = function () { var a = _chart.anchor(); if (a && a.id) { return a.id; } if (a && a.replace) { return a.replace('#', ''); } return '' + _chart.chartID(); }; /** #### .root([rootElement]) Returns the root element where a chart resides. Usually it will be the parent div element where the svg was created. You can also pass in a new root element however this is usually handled by dc internally. Resetting the root element on a chart outside of dc internals may have unexpected consequences. **/ _chart.root = function (r) { if (!arguments.length) { return _root; } _root = r; return _chart; }; /** #### .svg([svgElement]) Returns the top svg element for this specific chart. You can also pass in a new svg element, however this is usually handled by dc internally. Resetting the svg element on a chart outside of dc internals may have unexpected consequences. **/ _chart.svg = function (_) { if (!arguments.length) { return _svg; } _svg = _; return _chart; }; /** #### .resetSvg() Remove the chart's SVG elements from the dom and recreate the container SVG element. **/ _chart.resetSvg = function () { _chart.select('svg').remove(); return generateSvg(); }; function generateSvg() { _svg = _chart.root().append('svg') .attr('width', _chart.width()) .attr('height', _chart.height()); return _svg; } /** #### .filterPrinter([filterPrinterFunction]) Set or get the filter printer function. The filter printer function is used to generate human friendly text for filter value(s) associated with the chart instance. By default dc charts use a default filter printer `dc.printers.filter` that provides simple printing support for both single value and ranged filters. **/ _chart.filterPrinter = function (_) { if (!arguments.length) { return _filterPrinter; } _filterPrinter = _; return _chart; }; /** #### .turnOnControls() & .turnOffControls() Turn on/off optional control elements within the root element. dc currently supports the following html control elements. * root.selectAll('.reset') - elements are turned on if the chart has an active filter. This type of control element is usually used to store a reset link to allow user to reset filter on a certain chart. This element will be turned off automatically if the filter is cleared. * root.selectAll('.filter') elements are turned on if the chart has an active filter. The text content of this element is then replaced with the current filter value using the filter printer function. This type of element will be turned off automatically if the filter is cleared. **/ _chart.turnOnControls = function () { if (_root) { _chart.selectAll('.reset').style('display', null); _chart.selectAll('.filter').text(_filterPrinter(_chart.filters())).style('display', null); } return _chart; }; _chart.turnOffControls = function () { if (_root) { _chart.selectAll('.reset').style('display', 'none'); _chart.selectAll('.filter').style('display', 'none').text(_chart.filter()); } return _chart; }; /** #### .transitionDuration([duration]) Set or get the animation transition duration(in milliseconds) for this chart instance. Default duration is 750ms. **/ _chart.transitionDuration = function (d) { if (!arguments.length) { return _transitionDuration; } _transitionDuration = d; return _chart; }; _chart._mandatoryAttributes = function (_) { if (!arguments.length) { return _mandatoryAttributes; } _mandatoryAttributes = _; return _chart; }; function checkForMandatoryAttributes(a) { if (!_chart[a] || !_chart[a]()) { throw new dc.errors.InvalidStateException('Mandatory attribute chart.' + a + ' is missing on chart[#' + _chart.anchorName() + ']'); } } /** #### .render() Invoking this method will force the chart to re-render everything from scratch. Generally it should only be used to render the chart for the first time on the page or if you want to make sure everything is redrawn from scratch instead of relying on the default incremental redrawing behaviour. **/ _chart.render = function () { _listeners.preRender(_chart); if (_mandatoryAttributes) { _mandatoryAttributes.forEach(checkForMandatoryAttributes); } var result = _chart._doRender(); if (_legend) { _legend.render(); } _chart._activateRenderlets('postRender'); return result; }; _chart._activateRenderlets = function (event) { if (_chart.transitionDuration() > 0 && _svg) { _svg.transition().duration(_chart.transitionDuration()) .each('end', function () { runAllRenderlets(); if (event) { _listeners[event](_chart); } }); } else { runAllRenderlets(); if (event) { _listeners[event](_chart); } } }; /** #### .redraw() Calling redraw will cause the chart to re-render data changes incrementally. If there is no change in the underlying data dimension then calling this method will have no effect on the chart. Most chart interaction in dc will automatically trigger this method through internal events (in particular [dc.redrawAll](#dcredrawallchartgroup)); therefore, you only need to manually invoke this function if data is manipulated outside of dc's control (for example if data is loaded in the background using `crossfilter.add()`). **/ _chart.redraw = function () { _listeners.preRedraw(_chart); var result = _chart._doRedraw(); if (_legend) { _legend.render(); } _chart._activateRenderlets('postRedraw'); return result; }; _chart.redrawGroup = function () { dc.redrawAll(_chart.chartGroup()); }; _chart.renderGroup = function () { dc.renderAll(_chart.chartGroup()); }; _chart._invokeFilteredListener = function (f) { if (f !== undefined) { _listeners.filtered(_chart, f); } }; _chart._invokeZoomedListener = function () { _listeners.zoomed(_chart); }; var _hasFilterHandler = function (filters, filter) { if (filter === null || typeof(filter) === 'undefined') { return filters.length > 0; } return filters.some(function (f) { return filter <= f && filter >= f; }); }; /** #### .hasFilterHandler([function]) Set or get the has filter handler. The has filter handler is a function that checks to see if the chart's current filters include a specific filter. Using a custom has filter handler allows you to change the way filters are checked for and replaced. ```js // default has filter handler function (filters, filter) { if (filter === null || typeof(filter) === 'undefined') { return filters.length > 0; } return filters.some(function (f) { return filter <= f && filter >= f; }); } // custom filter handler (no-op) chart.hasFilterHandler(function(filters, filter) { return false; }); ``` **/ _chart.hasFilterHandler = function (_) { if (!arguments.length) { return _hasFilterHandler; } _hasFilterHandler = _; return _chart; }; /** #### .hasFilter([filter]) Check whether any active filter or a specific filter is associated with particular chart instance. This function is **not chainable**. **/ _chart.hasFilter = function (filter) { return _hasFilterHandler(_filters, filter); }; var _removeFilterHandler = function (filters, filter) { for (var i = 0; i < filters.length; i++) { if (filters[i] <= filter && filters[i] >= filter) { filters.splice(i, 1); break; } } return filters; }; /** #### .removeFilterHandler([function]) Set or get the remove filter handler. The remove filter handler is a function that removes a filter from the chart's current filters. Using a custom remove filter handler allows you to change how filters are removed or perform additional work when removing a filter, e.g. when using a filter server other than crossfilter. Any changes should modify the `filters` array argument and return that array. ```js // default remove filter handler function (filters, filter) { for (var i = 0; i < filters.length; i++) { if (filters[i] <= filter && filters[i] >= filter) { filters.splice(i, 1); break; } } return filters; } // custom filter handler (no-op) chart.removeFilterHandler(function(filters, filter) { return filters; }); ``` **/ _chart.removeFilterHandler = function (_) { if (!arguments.length) { return _removeFilterHandler; } _removeFilterHandler = _; return _chart; }; var _addFilterHandler = function (filters, filter) { filters.push(filter); return filters; }; /** #### .addFilterHandler([function]) Set or get the add filter handler. The add filter handler is a function that adds a filter to the chart's filter list. Using a custom add filter handler allows you to change the way filters are added or perform additional work when adding a filter, e.g. when using a filter server other than crossfilter. Any changes should modify the `filters` array argument and return that array. ```js // default add filter handler function (filters, filter) { filters.push(filter); return filters; } // custom filter handler (no-op) chart.addFilterHandler(function(filters, filter) { return filters; }); ``` **/ _chart.addFilterHandler = function (_) { if (!arguments.length) { return _addFilterHandler; } _addFilterHandler = _; return _chart; }; var _resetFilterHandler = function (filters) { return []; }; /** #### .resetFilterHandler([function]) Set or get the reset filter handler. The reset filter handler is a function that resets the chart's filter list by returning a new list. Using a custom reset filter handler allows you to change the way filters are reset, or perform additional work when resetting the filters, e.g. when using a filter server other than crossfilter. This function should return an array. ```js // default remove filter handler function (filters) { return []; } // custom filter handler (no-op) chart.resetFilterHandler(function(filters) { return filters; }); ``` **/ _chart.resetFilterHandler = function (_) { if (!arguments.length) { return _resetFilterHandler; } _resetFilterHandler = _; return _chart; }; function applyFilters() { if (_chart.dimension() && _chart.dimension().filter) { var fs = _filterHandler(_chart.dimension(), _filters); _filters = fs ? fs : _filters; } } _chart.replaceFilter = function (_) { _filters = []; _chart.filter(_); }; /** #### .filter([filterValue]) Filter the chart by the given value or return the current filter if the input parameter is missing. ```js // filter by a single string chart.filter('Sunday'); // filter by a single age chart.filter(18); ``` **/ _chart.filter = function (_) { if (!arguments.length) { return _filters.length > 0 ? _filters[0] : null; } if (_ instanceof Array && _[0] instanceof Array && !_.isFiltered) { _[0].forEach(function (d) { if (_chart.hasFilter(d)) { _removeFilterHandler(_filters, d); } else { _addFilterHandler(_filters, d); } }); } else if (_ === null) { _filters = _resetFilterHandler(_filters); } else { if (_chart.hasFilter(_)) { _removeFilterHandler(_filters, _); } else { _addFilterHandler(_filters, _); } } applyFilters(); _chart._invokeFilteredListener(_); if (_root !== null && _chart.hasFilter()) { _chart.turnOnControls(); } else { _chart.turnOffControls(); } return _chart; }; /** #### .filters() Returns all current filters. This method does not perform defensive cloning of the internal filter array before returning, therefore any modification of the returned array will effect the chart's internal filter storage. **/ _chart.filters = function () { return _filters; }; _chart.highlightSelected = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, true); d3.select(e).classed(dc.constants.DESELECTED_CLASS, false); }; _chart.fadeDeselected = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, false); d3.select(e).classed(dc.constants.DESELECTED_CLASS, true); }; _chart.resetHighlight = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, false); d3.select(e).classed(dc.constants.DESELECTED_CLASS, false); }; /** #### .onClick(datum) This function is passed to d3 as the onClick handler for each chart. The default behavior is to filter on the clicked datum (passed to the callback) and redraw the chart group. **/ _chart.onClick = function (d) { var filter = _chart.keyAccessor()(d); dc.events.trigger(function () { _chart.filter(filter); _chart.redrawGroup(); }); }; /** #### .filterHandler([function]) Set or get the filter handler. The filter handler is a function that performs the filter action on a specific dimension. Using a custom filter handler allows you to perform additional logic before or after filtering. ```js // default filter handler function(dimension, filter){ dimension.filter(filter); // perform filtering return filter; // return the actual filter value } // custom filter handler chart.filterHandler(function(dimension, filter){ var newFilter = filter + 10; dimension.filter(newFilter); return newFilter; // set the actual filter value to the new value }); ``` **/ _chart.filterHandler = function (_) { if (!arguments.length) { return _filterHandler; } _filterHandler = _; return _chart; }; // abstract function stub _chart._doRender = function () { // do nothing in base, should be overridden by sub-function return _chart; }; _chart._doRedraw = function () { // do nothing in base, should be overridden by sub-function return _chart; }; _chart.legendables = function () { // do nothing in base, should be overridden by sub-function return []; }; _chart.legendHighlight = function () { // do nothing in base, should be overridden by sub-function }; _chart.legendReset = function () { // do nothing in base, should be overridden by sub-function }; _chart.legendToggle = function () { // do nothing in base, should be overriden by sub-function }; _chart.isLegendableHidden = function () { // do nothing in base, should be overridden by sub-function return false; }; /** #### .keyAccessor([keyAccessorFunction]) Set or get the key accessor function. The key accessor function is used to retrieve the key value from the crossfilter group. Key values are used differently in different charts, for example keys correspond to slices in a pie chart and x axis positions in a grid coordinate chart. ```js // default key accessor chart.keyAccessor(function(d) { return d.key; }); // custom key accessor for a multi-value crossfilter reduction chart.keyAccessor(function(p) { return p.value.absGain; }); ``` **/ _chart.keyAccessor = function (_) { if (!arguments.length) { return _keyAccessor; } _keyAccessor = _; return _chart; }; /** #### .valueAccessor([valueAccessorFunction]) Set or get the value accessor function. The value accessor function is used to retrieve the value from the crossfilter group. Group values are used differently in different charts, for example values correspond to slice sizes in a pie chart and y axis positions in a grid coordinate chart. ```js // default value accessor chart.valueAccessor(function(d) { return d.value; }); // custom value accessor for a multi-value crossfilter reduction chart.valueAccessor(function(p) { return p.value.percentageGain; }); ``` **/ _chart.valueAccessor = function (_) { if (!arguments.length) { return _valueAccessor; } _valueAccessor = _; return _chart; }; /** #### .label([labelFunction]) Set or get the label function. The chart class will use this function to render labels for each child element in the chart, e.g. slices in a pie chart or bubbles in a bubble chart. Not every chart supports the label function for example bar chart and line chart do not use this function at all. ```js // default label function just return the key chart.label(function(d) { return d.key; }); // label function has access to the standard d3 data binding and can get quite complicated chart.label(function(d) { return d.data.key + '(' + Math.floor(d.data.value / all.value() * 100) + '%)'; }); ``` **/ _chart.label = function (_) { if (!arguments.length) { return _label; } _label = _; _renderLabel = true; return _chart; }; /** #### .renderLabel(boolean) Turn on/off label rendering **/ _chart.renderLabel = function (_) { if (!arguments.length) { return _renderLabel; } _renderLabel = _; return _chart; }; /** #### .title([titleFunction]) Set or get the title function. The chart class will use this function to render the svg title (usually interpreted by browser as tooltips) for each child element in the chart, e.g. a slice in a pie chart or a bubble in a bubble chart. Almost every chart supports the title function; however in grid coordinate charts you need to turn off the brush in order to see titles, because otherwise the brush layer will block tooltip triggering. ```js // default title function just return the key chart.title(function(d) { return d.key + ': ' + d.value; }); // title function has access to the standard d3 data binding and can get quite complicated chart.title(function(p) { return p.key.getFullYear() + '\n' + 'Index Gain: ' + numberFormat(p.value.absGain) + '\n' + 'Index Gain in Percentage: ' + numberFormat(p.value.percentageGain) + '%\n' + 'Fluctuation / Index Ratio: ' + numberFormat(p.value.fluctuationPercentage) + '%'; }); ``` **/ _chart.title = function (_) { if (!arguments.length) { return _title; } _title = _; return _chart; }; /** #### .renderTitle(boolean) Turn on/off title rendering, or return the state of the render title flag if no arguments are given. **/ _chart.renderTitle = function (_) { if (!arguments.length) { return _renderTitle; } _renderTitle = _; return _chart; }; /** #### .renderlet(renderletFunction) A renderlet is similar to an event listener on rendering event. Multiple renderlets can be added to an individual chart. Each time a chart is rerendered or redrawn the renderlets are invoked right after the chart finishes its own drawing routine, giving you a way to modify the svg elements. Renderlet functions take the chart instance as the only input parameter and you can use the dc API or use raw d3 to achieve pretty much any effect. ```js // renderlet function chart.renderlet(function(chart){ // mix of dc API and d3 manipulation chart.select('g.y').style('display', 'none'); // its a closure so you can also access other chart variable available in the closure scope moveChart.filter(chart.filter()); }); ``` **/ _chart.renderlet = function (_) { _renderlets.push(_); return _chart; }; function runAllRenderlets() { for (var i = 0; i < _renderlets.length; ++i) { _renderlets[i](_chart); } } /** #### .chartGroup([group]) Get or set the chart group to which this chart belongs. Chart groups are rendered or redrawn together since it is expected they share the same underlying crossfilter data set. **/ _chart.chartGroup = function (_) { if (!arguments.length) { return _chartGroup; } _chartGroup = _; return _chart; }; /** #### .expireCache() Expire the internal chart cache. dc charts cache some data internally on a per chart basis to speed up rendering and avoid unnecessary calculation; however it might be useful to clear the cache if you have changed state which will affect rendering. For example if you invoke the `crossfilter.add` function or reset group or dimension after rendering it is a good idea to clear the cache to make sure charts are rendered properly. **/ _chart.expireCache = function () { // do nothing in base, should be overridden by sub-function return _chart; }; /** #### .legend([dc.legend]) Attach a dc.legend widget to this chart. The legend widget will automatically draw legend labels based on the color setting and names associated with each group. ```js chart.legend(dc.legend().x(400).y(10).itemHeight(13).gap(5)) ``` **/ _chart.legend = function (l) { if (!arguments.length) { return _legend; } _legend = l; _legend.parent(_chart); return _chart; }; /** #### .chartID() Returns the internal numeric ID of the chart. **/ _chart.chartID = function () { return _chart.__dcFlag__; }; /** #### .options(optionsObject) Set chart options using a configuration object. Each key in the object will cause the method of the same name to be called with the value to set that attribute for the chart. Example: ``` chart.options({dimension: myDimension, group: myGroup}); ``` **/ _chart.options = function (opts) { for (var o in opts) { if (typeof(_chart[o]) === 'function') { _chart[o].call(_chart, opts[o]); } else { dc.logger.debug('Not a valid option setter name: ' + o); } } return _chart; }; /** ## Listeners All dc chart instance supports the following listeners. #### .on('preRender', function(chart){...}) This listener function will be invoked before chart rendering. #### .on('postRender', function(chart){...}) This listener function will be invoked after chart finish rendering including all renderlets' logic. #### .on('preRedraw', function(chart){...}) This listener function will be invoked before chart redrawing. #### .on('postRedraw', function(chart){...}) This listener function will be invoked after chart finish redrawing including all renderlets' logic. #### .on('filtered', function(chart, filter){...}) This listener function will be invoked after a filter is applied, added or removed. #### .on('zoomed', function(chart, filter){...}) This listener function will be invoked after a zoom is triggered. **/ _chart.on = function (event, listener) { _listeners.on(event, listener); return _chart; }; return _chart; }; /** ## Margin Mixin Margin is a mixin that provides margin utility functions for both the Row Chart and Coordinate Grid Charts. **/ dc.marginMixin = function (_chart) { var _margin = {top: 10, right: 50, bottom: 30, left: 30}; /** #### .margins([margins]) Get or set the margins for a particular coordinate grid chart instance. The margins is stored as an associative Javascript array. Default margins: {top: 10, right: 50, bottom: 30, left: 30}. The margins can be accessed directly from the getter. ```js var leftMargin = chart.margins().left; // 30 by default chart.margins().left = 50; leftMargin = chart.margins().left; // now 50 ``` **/ _chart.margins = function (m) { if (!arguments.length) { return _margin; } _margin = m; return _chart; }; _chart.effectiveWidth = function () { return _chart.width() - _chart.margins().left - _chart.margins().right; }; _chart.effectiveHeight = function () { return _chart.height() - _chart.margins().top - _chart.margins().bottom; }; return _chart; }; /** ## Color Mixin The Color Mixin is an abstract chart functional class providing universal coloring support as a mix-in for any concrete chart implementation. **/ dc.colorMixin = function (_chart) { var _colors = d3.scale.category20c(); var _defaultAccessor = true; var _colorAccessor = function (d) { return _chart.keyAccessor()(d); }; /** #### .colors([colorScale]) Retrieve current color scale or set a new color scale. This methods accepts any function that operates like a d3 scale. If not set the default is `d3.scale.category20c()`. ```js // alternate categorical scale chart.colors(d3.scale.category20b()); // ordinal scale chart.colors(d3.scale.ordinal().range(['red','green','blue'])); // convenience method, the same as above chart.ordinalColors(['red','green','blue']); // set a linear scale chart.linearColors(["#4575b4", "#ffffbf", "#a50026"]); ``` **/ _chart.colors = function (_) { if (!arguments.length) { return _colors; } if (_ instanceof Array) { _colors = d3.scale.quantize().range(_); // deprecated legacy support, note: this fails for ordinal domains } else { _colors = d3.functor(_); } return _chart; }; /** #### .ordinalColors(r) Convenience method to set the color scale to d3.scale.ordinal with range `r`. **/ _chart.ordinalColors = function (r) { return _chart.colors(d3.scale.ordinal().range(r)); }; /** #### .linearColors(r) Convenience method to set the color scale to an Hcl interpolated linear scale with range `r`. **/ _chart.linearColors = function (r) { return _chart.colors(d3.scale.linear() .range(r) .interpolate(d3.interpolateHcl)); }; /** #### .colorAccessor([colorAccessorFunction]) Set or the get color accessor function. This function will be used to map a data point in a crossfilter group to a color value on the color scale. The default function uses the key accessor. ```js // default index based color accessor .colorAccessor(function (d, i){return i;}) // color accessor for a multi-value crossfilter reduction .colorAccessor(function (d){return d.value.absGain;}) ``` **/ _chart.colorAccessor = function (_) { if (!arguments.length) { return _colorAccessor; } _colorAccessor = _; _defaultAccessor = false; return _chart; }; // what is this? _chart.defaultColorAccessor = function () { return _defaultAccessor; }; /** #### .colorDomain([domain]) Set or get the current domain for the color mapping function. The domain must be supplied as an array. Note: previously this method accepted a callback function. Instead you may use a custom scale set by `.colors`. **/ _chart.colorDomain = function (_) { if (!arguments.length) { return _colors.domain(); } _colors.domain(_); return _chart; }; /** #### .calculateColorDomain() Set the domain by determining the min and max values as retrieved by `.colorAccessor` over the chart's dataset. **/ _chart.calculateColorDomain = function () { var newDomain = [d3.min(_chart.data(), _chart.colorAccessor()), d3.max(_chart.data(), _chart.colorAccessor())]; _colors.domain(newDomain); }; /** #### .getColor(d [, i]) Get the color for the datum d and counter i. This is used internally by charts to retrieve a color. **/ _chart.getColor = function (d, i) { return _colors(_colorAccessor.call(this, d, i)); }; /** #### .colorCalculator([value]) Gets or sets chart.getColor. **/ _chart.colorCalculator = function (_) { if (!arguments.length) { return _chart.getColor; } _chart.getColor = _; return _chart; }; return _chart; }; /** ## Coordinate Grid Mixin Includes: [Color Mixin](#color-mixin), [Margin Mixin](#margin-mixin), [Base Mixin](#base-mixin) Coordinate Grid is an abstract base chart designed to support a number of coordinate grid based concrete chart types, e.g. bar chart, line chart, and bubble chart. **/ dc.coordinateGridMixin = function (_chart) { var GRID_LINE_CLASS = 'grid-line'; var HORIZONTAL_CLASS = 'horizontal'; var VERTICAL_CLASS = 'vertical'; var Y_AXIS_LABEL_CLASS = 'y-axis-label'; var X_AXIS_LABEL_CLASS = 'x-axis-label'; var DEFAULT_AXIS_LABEL_PADDING = 12; _chart = dc.colorMixin(dc.marginMixin(dc.baseMixin(_chart))); _chart.colors(d3.scale.category10()); _chart._mandatoryAttributes().push('x'); function zoomHandler () { _refocused = true; if (_zoomOutRestrict) { _chart.x().domain(constrainRange(_chart.x().domain(), _xOriginalDomain)); if (_rangeChart) { _chart.x().domain(constrainRange(_chart.x().domain(), _rangeChart.x().domain())); } } var domain = _chart.x().domain(); var domFilter = dc.filters.RangedFilter(domain[0], domain[1]); _chart.replaceFilter(domFilter); _chart.rescale(); _chart.redraw(); if (_rangeChart && !rangesEqual(_chart.filter(), _rangeChart.filter())) { dc.events.trigger(function () { _rangeChart.replaceFilter(domFilter); _rangeChart.redraw(); }); } _chart._invokeZoomedListener(); dc.events.trigger(function () { _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); _refocused = !rangesEqual(domain, _xOriginalDomain); } var _parent; var _g; var _chartBodyG; var _x; var _xOriginalDomain; var _xAxis = d3.svg.axis().orient('bottom'); var _xUnits = dc.units.integers; var _xAxisPadding = 0; var _xElasticity = false; var _xAxisLabel; var _xAxisLabelPadding = 0; var _lastXDomain; var _y; var _yAxis = d3.svg.axis().orient('left'); var _yAxisPadding = 0; var _yElasticity = false; var _yAxisLabel; var _yAxisLabelPadding = 0; var _brush = d3.svg.brush(); var _brushOn = true; var _round; var _renderHorizontalGridLine = false; var _renderVerticalGridLine = false; var _refocused = false; var _unitCount; var _zoomScale = [1, Infinity]; var _zoomOutRestrict = true; var _zoom = d3.behavior.zoom().on('zoom', zoomHandler); var _nullZoom = d3.behavior.zoom().on('zoom', null); var _hasBeenMouseZoomable = false; var _rangeChart; var _focusChart; var _mouseZoomable = false; var _clipPadding = 0; var _outerRangeBandPadding = 0.5; var _rangeBandPadding = 0; var _useRightYAxis = false; _chart.rescale = function () { _unitCount = undefined; }; /** #### .rangeChart([chart]) Get or set the range selection chart associated with this instance. Setting the range selection chart using this function will automatically update its selection brush when the current chart zooms in. In return the given range chart will also automatically attach this chart as its focus chart hence zoom in when range brush updates. See the [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) example for this effect in action. **/ _chart.rangeChart = function (_) { if (!arguments.length) { return _rangeChart; } _rangeChart = _; _rangeChart.focusChart(_chart); return _chart; }; /** #### .zoomScale([extent]) Get or set the scale extent for mouse zooms. **/ _chart.zoomScale = function (_) { if (!arguments.length) { return _zoomScale; } _zoomScale = _; return _chart; }; /** #### .zoomOutRestrict([true/false]) Get or set the zoom restriction for the chart. If true limits the zoom to origional domain of the chart. **/ _chart.zoomOutRestrict = function (r) { if (!arguments.length) { return _zoomOutRestrict; } _zoomScale[0] = r ? 1 : 0; _zoomOutRestrict = r; return _chart; }; _chart._generateG = function (parent) { if (parent === undefined) { _parent = _chart.svg(); } else { _parent = parent; } _g = _parent.append('g'); _chartBodyG = _g.append('g').attr('class', 'chart-body') .attr('transform', 'translate(' + _chart.margins().left + ', ' + _chart.margins().top + ')') .attr('clip-path', 'url(#' + getClipPathId() + ')'); return _g; }; /** #### .g([gElement]) Get or set the root g element. This method is usually used to retrieve the g element in order to overlay custom svg drawing programatically. **Caution**: The root g element is usually generated by dc.js internals, and resetting it might produce unpredictable result. **/ _chart.g = function (_) { if (!arguments.length) { return _g; } _g = _; return _chart; }; /** #### .mouseZoomable([boolean]) Set or get mouse zoom capability flag (default: false). When turned on the chart will be zoomable using the mouse wheel. If the range selector chart is attached zooming will also update the range selection brush on the associated range selector chart. **/ _chart.mouseZoomable = function (z) { if (!arguments.length) { return _mouseZoomable; } _mouseZoomable = z; return _chart; }; /** #### .chartBodyG() Retrieve the svg group for the chart body. **/ _chart.chartBodyG = function (_) { if (!arguments.length) { return _chartBodyG; } _chartBodyG = _; return _chart; }; /** #### .x([xScale]) - **mandatory** Get or set the x scale. The x scale can be any d3 [quantitive scale](https://github.com/mbostock/d3/wiki/Quantitative-Scales) or [ordinal scale](https://github.com/mbostock/d3/wiki/Ordinal-Scales). ```js // set x to a linear scale chart.x(d3.scale.linear().domain([-2500, 2500])) // set x to a time scale to generate histogram chart.x(d3.time.scale().domain([new Date(1985, 0, 1), new Date(2012, 11, 31)])) ``` **/ _chart.x = function (_) { if (!arguments.length) { return _x; } _x = _; _xOriginalDomain = _x.domain(); return _chart; }; _chart.xOriginalDomain = function () { return _xOriginalDomain; }; /** #### .xUnits([xUnits function]) Set or get the xUnits function. The coordinate grid chart uses the xUnits function to calculate the number of data projections on x axis such as the number of bars for a bar chart or the number of dots for a line chart. This function is expected to return a Javascript array of all data points on x axis, or the number of points on the axis. [d3 time range functions d3.time.days, d3.time.months, and d3.time.years](https://github.com/mbostock/d3/wiki/Time-Intervals#aliases) are all valid xUnits function. dc.js also provides a few units function, see the [Utilities](#utilities) section for a list of built-in units functions. The default xUnits function is dc.units.integers. ```js // set x units to count days chart.xUnits(d3.time.days); // set x units to count months chart.xUnits(d3.time.months); ``` A custom xUnits function can be used as long as it follows the following interface: ```js // units in integer function(start, end, xDomain) { // simply calculates how many integers in the domain return Math.abs(end - start); }; // fixed units function(start, end, xDomain) { // be aware using fixed units will disable the focus/zoom ability on the chart return 1000; }; ``` **/ _chart.xUnits = function (_) { if (!arguments.length) { return _xUnits; } _xUnits = _; return _chart; }; /** #### .xAxis([xAxis]) Set or get the x axis used by a particular coordinate grid chart instance. This function is most useful when x axis customization is required. The x axis in dc.js is an instance of a [d3 axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-axis); therefore it supports any valid d3 axis manipulation. **Caution**: The x axis is usually generated internally by dc; resetting it may cause unexpected results. ```js // customize x axis tick format chart.xAxis().tickFormat(function(v) {return v + '%';}); // customize x axis tick values chart.xAxis().tickValues([0, 100, 200, 300]); ``` **/ _chart.xAxis = function (_) { if (!arguments.length) { return _xAxis; } _xAxis = _; return _chart; }; /** #### .elasticX([boolean]) Turn on/off elastic x axis behavior. If x axis elasticity is turned on, then the grid chart will attempt to recalculate the x axis range whenever a redraw event is triggered. **/ _chart.elasticX = function (_) { if (!arguments.length) { return _xElasticity; } _xElasticity = _; return _chart; }; /** #### .xAxisPadding([padding]) Set or get x axis padding for the elastic x axis. The padding will be added to both end of the x axis if elasticX is turned on; otherwise it is ignored. * padding can be an integer or percentage in string (e.g. '10%'). Padding can be applied to number or date x axes. When padding a date axis, an integer represents number of days being padded and a percentage string will be treated the same as an integer. **/ _chart.xAxisPadding = function (_) { if (!arguments.length) { return _xAxisPadding; } _xAxisPadding = _; return _chart; }; /** #### .xUnitCount() Returns the number of units displayed on the x axis using the unit measure configured by .xUnits. **/ _chart.xUnitCount = function () { if (_unitCount === undefined) { var units = _chart.xUnits()(_chart.x().domain()[0], _chart.x().domain()[1], _chart.x().domain()); if (units instanceof Array) { _unitCount = units.length; } else { _unitCount = units; } } return _unitCount; }; /** #### .useRightYAxis() Gets or sets whether the chart should be drawn with a right axis instead of a left axis. When used with a chart in a composite chart, allows both left and right Y axes to be shown on a chart. **/ _chart.useRightYAxis = function (_) { if (!arguments.length) { return _useRightYAxis; } _useRightYAxis = _; return _chart; }; /** #### isOrdinal() Returns true if the chart is using ordinal xUnits ([dc.units.ordinal](#dcunitsordinal)), or false otherwise. Most charts behave differently with ordinal data and use the result of this method to trigger the appropriate logic. **/ _chart.isOrdinal = function () { return _chart.xUnits() === dc.units.ordinal; }; _chart._useOuterPadding = function () { return true; }; _chart._ordinalXDomain = function () { var groups = _chart._computeOrderedGroups(_chart.data()); return groups.map(_chart.keyAccessor()); }; function prepareXAxis(g) { if (!_chart.isOrdinal()) { if (_chart.elasticX()) { _x.domain([_chart.xAxisMin(), _chart.xAxisMax()]); } } else { // _chart.isOrdinal() if (_chart.elasticX() || _x.domain().length === 0) { _x.domain(_chart._ordinalXDomain()); } } // has the domain changed? var xdom = _x.domain(); if (!_lastXDomain || xdom.some(function (elem, i) { return elem !== _lastXDomain[i]; })) { _chart.rescale(); } _lastXDomain = xdom; // please can't we always use rangeBands for bar charts? if (_chart.isOrdinal()) { _x.rangeBands([0, _chart.xAxisLength()], _rangeBandPadding, _chart._useOuterPadding() ? _outerRangeBandPadding : 0); } else { _x.range([0, _chart.xAxisLength()]); } _xAxis = _xAxis.scale(_chart.x()); renderVerticalGridLines(g); } _chart.renderXAxis = function (g) { var axisXG = g.selectAll('g.x'); if (axisXG.empty()) { axisXG = g.append('g') .attr('class', 'axis x') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart._xAxisY() + ')'); } var axisXLab = g.selectAll('text.' + X_AXIS_LABEL_CLASS); if (axisXLab.empty() && _chart.xAxisLabel()) { axisXLab = g.append('text') .attr('transform', 'translate(' + (_chart.margins().left + _chart.xAxisLength() / 2) + ',' + (_chart.height() - _xAxisLabelPadding) + ')') .attr('class', X_AXIS_LABEL_CLASS) .attr('text-anchor', 'middle') .text(_chart.xAxisLabel()); } if (_chart.xAxisLabel() && axisXLab.text() !== _chart.xAxisLabel()) { axisXLab.text(_chart.xAxisLabel()); } dc.transition(axisXG, _chart.transitionDuration()) .call(_xAxis); }; function renderVerticalGridLines(g) { var gridLineG = g.selectAll('g.' + VERTICAL_CLASS); if (_renderVerticalGridLine) { if (gridLineG.empty()) { gridLineG = g.insert('g', ':first-child') .attr('class', GRID_LINE_CLASS + ' ' + VERTICAL_CLASS) .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); } var ticks = _xAxis.tickValues() ? _xAxis.tickValues() : (typeof _x.ticks === 'function' ? _x.ticks(_xAxis.ticks()[0]) : _x.domain()); var lines = gridLineG.selectAll('line') .data(ticks); // enter var linesGEnter = lines.enter() .append('line') .attr('x1', function (d) { return _x(d); }) .attr('y1', _chart._xAxisY() - _chart.margins().top) .attr('x2', function (d) { return _x(d); }) .attr('y2', 0) .attr('opacity', 0); dc.transition(linesGEnter, _chart.transitionDuration()) .attr('opacity', 1); // update dc.transition(lines, _chart.transitionDuration()) .attr('x1', function (d) { return _x(d); }) .attr('y1', _chart._xAxisY() - _chart.margins().top) .attr('x2', function (d) { return _x(d); }) .attr('y2', 0); // exit lines.exit().remove(); } else { gridLineG.selectAll('line').remove(); } } _chart._xAxisY = function () { return (_chart.height() - _chart.margins().bottom); }; _chart.xAxisLength = function () { return _chart.effectiveWidth(); }; /** #### .xAxisLabel([labelText, [, padding]]) Set or get the x axis label. If setting the label, you may optionally include additional padding to the margin to make room for the label. By default the padded is set to 12 to accomodate the text height. **/ _chart.xAxisLabel = function (_, padding) { if (!arguments.length) { return _xAxisLabel; } _xAxisLabel = _; _chart.margins().bottom -= _xAxisLabelPadding; _xAxisLabelPadding = (padding === undefined) ? DEFAULT_AXIS_LABEL_PADDING : padding; _chart.margins().bottom += _xAxisLabelPadding; return _chart; }; _chart._prepareYAxis = function (g) { if (_y === undefined || _chart.elasticY()) { _y = d3.scale.linear(); var min = _chart.yAxisMin() || 0, max = _chart.yAxisMax() || 0; _y.domain([min, max]).rangeRound([_chart.yAxisHeight(), 0]); } _y.range([_chart.yAxisHeight(), 0]); _yAxis = _yAxis.scale(_y); if (_useRightYAxis) { _yAxis.orient('right'); } _chart._renderHorizontalGridLinesForAxis(g, _y, _yAxis); }; _chart.renderYAxisLabel = function (axisClass, text, rotation, labelXPosition) { labelXPosition = labelXPosition || _yAxisLabelPadding; var axisYLab = _chart.g().selectAll('text.' + Y_AXIS_LABEL_CLASS + '.' + axisClass + '-label'); if (axisYLab.empty() && text) { var labelYPosition = (_chart.margins().top + _chart.yAxisHeight() / 2); axisYLab = _chart.g().append('text') .attr('transform', 'translate(' + labelXPosition + ',' + labelYPosition + '),rotate(' + rotation + ')') .attr('class', Y_AXIS_LABEL_CLASS + ' ' + axisClass + '-label') .attr('text-anchor', 'middle') .text(text); } if (text && axisYLab.text() !== text) { axisYLab.text(text); } }; _chart.renderYAxisAt = function (axisClass, axis, position) { var axisYG = _chart.g().selectAll('g.' + axisClass); if (axisYG.empty()) { axisYG = _chart.g().append('g') .attr('class', 'axis ' + axisClass) .attr('transform', 'translate(' + position + ',' + _chart.margins().top + ')'); } dc.transition(axisYG, _chart.transitionDuration()).call(axis); }; _chart.renderYAxis = function () { var axisPosition = _useRightYAxis ? (_chart.width() - _chart.margins().right) : _chart._yAxisX(); _chart.renderYAxisAt('y', _yAxis, axisPosition); var labelPosition = _useRightYAxis ? (_chart.width() - _yAxisLabelPadding) : _yAxisLabelPadding; var rotation = _useRightYAxis ? 90 : -90; _chart.renderYAxisLabel('y', _chart.yAxisLabel(), rotation, labelPosition); }; _chart._renderHorizontalGridLinesForAxis = function (g, scale, axis) { var gridLineG = g.selectAll('g.' + HORIZONTAL_CLASS); if (_renderHorizontalGridLine) { var ticks = axis.tickValues() ? axis.tickValues() : scale.ticks(axis.ticks()[0]); if (gridLineG.empty()) { gridLineG = g.insert('g', ':first-child') .attr('class', GRID_LINE_CLASS + ' ' + HORIZONTAL_CLASS) .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); } var lines = gridLineG.selectAll('line') .data(ticks); // enter var linesGEnter = lines.enter() .append('line') .attr('x1', 1) .attr('y1', function (d) { return scale(d); }) .attr('x2', _chart.xAxisLength()) .attr('y2', function (d) { return scale(d); }) .attr('opacity', 0); dc.transition(linesGEnter, _chart.transitionDuration()) .attr('opacity', 1); // update dc.transition(lines, _chart.transitionDuration()) .attr('x1', 1) .attr('y1', function (d) { return scale(d); }) .attr('x2', _chart.xAxisLength()) .attr('y2', function (d) { return scale(d); }); // exit lines.exit().remove(); } else { gridLineG.selectAll('line').remove(); } }; _chart._yAxisX = function () { return _chart.useRightYAxis() ? _chart.width() - _chart.margins().right : _chart.margins().left; }; /** #### .yAxisLabel([labelText, [, padding]]) Set or get the y axis label. If setting the label, you may optionally include additional padding to the margin to make room for the label. By default the padded is set to 12 to accomodate the text height. **/ _chart.yAxisLabel = function (_, padding) { if (!arguments.length) { return _yAxisLabel; } _yAxisLabel = _; _chart.margins().left -= _yAxisLabelPadding; _yAxisLabelPadding = (padding === undefined) ? DEFAULT_AXIS_LABEL_PADDING : padding; _chart.margins().left += _yAxisLabelPadding; return _chart; }; /** #### .y([yScale]) Get or set the y scale. The y scale is typically automatically determined by the chart implementation. **/ _chart.y = function (_) { if (!arguments.length) { return _y; } _y = _; return _chart; }; /** #### .yAxis([yAxis]) Set or get the y axis used by the coordinate grid chart instance. This function is most useful when y axis customization is required. The y axis in dc.js is simply an instance of a [d3 axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-_axis); therefore it supports any valid d3 axis manipulation. **Caution**: The y axis is usually generated internally by dc; resetting it may cause unexpected results. ```js // customize y axis tick format chart.yAxis().tickFormat(function(v) {return v + '%';}); // customize y axis tick values chart.yAxis().tickValues([0, 100, 200, 300]); ``` **/ _chart.yAxis = function (y) { if (!arguments.length) { return _yAxis; } _yAxis = y; return _chart; }; /** #### .elasticY([boolean]) Turn on/off elastic y axis behavior. If y axis elasticity is turned on, then the grid chart will attempt to recalculate the y axis range whenever a redraw event is triggered. **/ _chart.elasticY = function (_) { if (!arguments.length) { return _yElasticity; } _yElasticity = _; return _chart; }; /** #### .renderHorizontalGridLines([boolean]) Turn on/off horizontal grid lines. **/ _chart.renderHorizontalGridLines = function (_) { if (!arguments.length) { return _renderHorizontalGridLine; } _renderHorizontalGridLine = _; return _chart; }; /** #### .renderVerticalGridLines([boolean]) Turn on/off vertical grid lines. **/ _chart.renderVerticalGridLines = function (_) { if (!arguments.length) { return _renderVerticalGridLine; } _renderVerticalGridLine = _; return _chart; }; /** #### .xAxisMin() Calculates the minimum x value to display in the chart. Includes xAxisPadding if set. **/ _chart.xAxisMin = function () { var min = d3.min(_chart.data(), function (e) { return _chart.keyAccessor()(e); }); return dc.utils.subtract(min, _xAxisPadding); }; /** #### .xAxisMax() Calculates the maximum x value to display in the chart. Includes xAxisPadding if set. **/ _chart.xAxisMax = function () { var max = d3.max(_chart.data(), function (e) { return _chart.keyAccessor()(e); }); return dc.utils.add(max, _xAxisPadding); }; /** #### .yAxisMin() Calculates the minimum y value to display in the chart. Includes yAxisPadding if set. **/ _chart.yAxisMin = function () { var min = d3.min(_chart.data(), function (e) { return _chart.valueAccessor()(e); }); return dc.utils.subtract(min, _yAxisPadding); }; /** #### .yAxisMax() Calculates the maximum y value to display in the chart. Includes yAxisPadding if set. **/ _chart.yAxisMax = function () { var max = d3.max(_chart.data(), function (e) { return _chart.valueAccessor()(e); }); return dc.utils.add(max, _yAxisPadding); }; /** #### .yAxisPadding([padding]) Set or get y axis padding for the elastic y axis. The padding will be added to the top of the y axis if elasticY is turned on; otherwise it is ignored. * padding can be an integer or percentage in string (e.g. '10%'). Padding can be applied to number or date axes. When padding a date axis, an integer represents number of days being padded and a percentage string will be treated the same as an integer. **/ _chart.yAxisPadding = function (_) { if (!arguments.length) { return _yAxisPadding; } _yAxisPadding = _; return _chart; }; _chart.yAxisHeight = function () { return _chart.effectiveHeight(); }; /** #### .round([rounding function]) Set or get the rounding function used to quantize the selection when brushing is enabled. ```js // set x unit round to by month, this will make sure range selection brush will // select whole months chart.round(d3.time.month.round); ``` **/ _chart.round = function (_) { if (!arguments.length) { return _round; } _round = _; return _chart; }; _chart._rangeBandPadding = function (_) { if (!arguments.length) { return _rangeBandPadding; } _rangeBandPadding = _; return _chart; }; _chart._outerRangeBandPadding = function (_) { if (!arguments.length) { return _outerRangeBandPadding; } _outerRangeBandPadding = _; return _chart; }; dc.override(_chart, 'filter', function (_) { if (!arguments.length) { return _chart._filter(); } _chart._filter(_); if (_) { _chart.brush().extent(_); } else { _chart.brush().clear(); } return _chart; }); _chart.brush = function (_) { if (!arguments.length) { return _brush; } _brush = _; return _chart; }; function brushHeight() { return _chart._xAxisY() - _chart.margins().top; } _chart.renderBrush = function (g) { if (_brushOn) { _brush.on('brush', _chart._brushing); _brush.on('brushstart', _chart._disableMouseZoom); _brush.on('brushend', configureMouseZoom); var gBrush = g.append('g') .attr('class', 'brush') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')') .call(_brush.x(_chart.x())); _chart.setBrushY(gBrush); _chart.setHandlePaths(gBrush); if (_chart.hasFilter()) { _chart.redrawBrush(g); } } }; _chart.setHandlePaths = function (gBrush) { gBrush.selectAll('.resize').append('path').attr('d', _chart.resizeHandlePath); }; _chart.setBrushY = function (gBrush) { gBrush.selectAll('rect').attr('height', brushHeight()); }; _chart.extendBrush = function () { var extent = _brush.extent(); if (_chart.round()) { extent[0] = extent.map(_chart.round())[0]; extent[1] = extent.map(_chart.round())[1]; _g.select('.brush') .call(_brush.extent(extent)); } return extent; }; _chart.brushIsEmpty = function (extent) { return _brush.empty() || !extent || extent[1] <= extent[0]; }; _chart._brushing = function () { var extent = _chart.extendBrush(); _chart.redrawBrush(_g); if (_chart.brushIsEmpty(extent)) { dc.events.trigger(function () { _chart.filter(null); _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); } else { var rangedFilter = dc.filters.RangedFilter(extent[0], extent[1]); dc.events.trigger(function () { _chart.replaceFilter(rangedFilter); _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); } }; _chart.redrawBrush = function (g) { if (_brushOn) { if (_chart.filter() && _chart.brush().empty()) { _chart.brush().extent(_chart.filter()); } var gBrush = g.select('g.brush'); gBrush.call(_chart.brush().x(_chart.x())); _chart.setBrushY(gBrush); } _chart.fadeDeselectedArea(); }; _chart.fadeDeselectedArea = function () { // do nothing, sub-chart should override this function }; // borrowed from Crossfilter example _chart.resizeHandlePath = function (d) { var e = +(d === 'e'), x = e ? 1 : -1, y = brushHeight() / 3; /*jshint -W014 */ return 'M' + (0.5 * x) + ',' + y + 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6) + 'V' + (2 * y - 6) + 'A6,6 0 0 ' + e + ' ' + (0.5 * x) + ',' + (2 * y) + 'Z' + 'M' + (2.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8) + 'M' + (4.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8); /*jshint +W014 */ }; function getClipPathId() { return _chart.anchorName().replace(/[ .#]/g, '-') + '-clip'; } /** #### .clipPadding([padding]) Get or set the padding in pixels for the clip path. Once set padding will be applied evenly to the top, left, right, and bottom when the clip path is generated. If set to zero, the clip area will be exactly the chart body area minus the margins. Default: 5 **/ _chart.clipPadding = function (p) { if (!arguments.length) { return _clipPadding; } _clipPadding = p; return _chart; }; function generateClipPath() { var defs = dc.utils.appendOrSelect(_parent, 'defs'); // cannot select <clippath> elements; bug in WebKit, must select by id // https://groups.google.com/forum/#!topic/d3-js/6EpAzQ2gU9I var id = getClipPathId(); var chartBodyClip = dc.utils.appendOrSelect(defs, '#' + id, 'clipPath').attr('id', id); var padding = _clipPadding * 2; dc.utils.appendOrSelect(chartBodyClip, 'rect') .attr('width', _chart.xAxisLength() + padding) .attr('height', _chart.yAxisHeight() + padding) .attr('transform', 'translate(-' + _clipPadding + ', -' + _clipPadding + ')'); } _chart._preprocessData = function () {}; _chart._doRender = function () { _chart.resetSvg(); _chart._preprocessData(); _chart._generateG(); generateClipPath(); drawChart(true); configureMouseZoom(); return _chart; }; _chart._doRedraw = function () { _chart._preprocessData(); drawChart(false); generateClipPath(); return _chart; }; function drawChart (render) { if (_chart.isOrdinal()) { _brushOn = false; } prepareXAxis(_chart.g()); _chart._prepareYAxis(_chart.g()); _chart.plotData(); if (_chart.elasticX() || _refocused || render) { _chart.renderXAxis(_chart.g()); } if (_chart.elasticY() || render) { _chart.renderYAxis(_chart.g()); } if (render) { _chart.renderBrush(_chart.g()); } else { _chart.redrawBrush(_chart.g()); } } function configureMouseZoom () { if (_mouseZoomable) { _chart._enableMouseZoom(); } else if (_hasBeenMouseZoomable) { _chart._disableMouseZoom(); } } _chart._enableMouseZoom = function () { _hasBeenMouseZoomable = true; _zoom.x(_chart.x()) .scaleExtent(_zoomScale) .size([_chart.width(), _chart.height()]) .duration(_chart.transitionDuration()); _chart.root().call(_zoom); }; _chart._disableMouseZoom = function () { _chart.root().call(_nullZoom); }; function constrainRange(range, constraint) { var constrainedRange = []; constrainedRange[0] = d3.max([range[0], constraint[0]]); constrainedRange[1] = d3.min([range[1], constraint[1]]); return constrainedRange; } /** #### .focus([range]) Zoom this chart to focus on the given range. The given range should be an array containing only 2 elements (`[start, end]`) defining a range in the x domain. If the range is not given or set to null, then the zoom will be reset. _For focus to work elasticX has to be turned off; otherwise focus will be ignored._ ```js chart.renderlet(function(chart){ // smooth the rendering through event throttling dc.events.trigger(function(){ // focus some other chart to the range selected by user on this chart someOtherChart.focus(chart.filter()); }); }) ``` **/ _chart.focus = function (range) { if (hasRangeSelected(range)) { _chart.x().domain(range); } else { _chart.x().domain(_xOriginalDomain); } _zoom.x(_chart.x()); zoomHandler(); }; _chart.refocused = function () { return _refocused; }; _chart.focusChart = function (c) { if (!arguments.length) { return _focusChart; } _focusChart = c; _chart.on('filtered', function (chart) { if (!chart.filter()) { dc.events.trigger(function () { _focusChart.x().domain(_focusChart.xOriginalDomain()); }); } else if (!rangesEqual(chart.filter(), _focusChart.filter())) { dc.events.trigger(function () { _focusChart.focus(chart.filter()); }); } }); return _chart; }; function rangesEqual(range1, range2) { if (!range1 && !range2) { return true; } else if (!range1 || !range2) { return false; } else if (range1.length === 0 && range2.length === 0) { return true; } else if (range1[0].valueOf() === range2[0].valueOf() && range1[1].valueOf() === range2[1].valueOf()) { return true; } return false; } /** #### .brushOn([boolean]) Turn on/off the brush-based range filter. When brushing is on then user can drag the mouse across a chart with a quantitative scale to perform range filtering based on the extent of the brush, or click on the bars of an ordinal bar chart or slices of a pie chart to filter and unfilter them. However turning on the brush filter will disable other interactive elements on the chart such as highlighting, tool tips, and reference lines. Zooming will still be possible if enabled, but only via scrolling (panning will be disabled.) Default: true **/ _chart.brushOn = function (_) { if (!arguments.length) { return _brushOn; } _brushOn = _; return _chart; }; function hasRangeSelected(range) { return range instanceof Array && range.length > 1; } return _chart; }; /** ## Stack Mixin Stack Mixin is an mixin that provides cross-chart support of stackability using d3.layout.stack. **/ dc.stackMixin = function (_chart) { function prepareValues (layer, layerIdx) { var valAccessor = layer.accessor || _chart.valueAccessor(); layer.name = String(layer.name || layerIdx); layer.values = layer.group.all().map(function (d, i) { return { x: _chart.keyAccessor()(d, i), y: layer.hidden ? null : valAccessor(d, i), data: d, layer: layer.name, hidden: layer.hidden }; }); layer.values = layer.values.filter(domainFilter()); return layer.values; } var _stackLayout = d3.layout.stack() .values(prepareValues); var _stack = []; var _titles = {}; var _hidableStacks = false; function domainFilter() { if (!_chart.x()) { return d3.functor(true); } var xDomain = _chart.x().domain(); if (_chart.isOrdinal()) { // TODO #416 //var domainSet = d3.set(xDomain); return function () { return true; //domainSet.has(p.x); }; } if (_chart.elasticX()) { return function () { return true; }; } return function (p) { //return true; return p.x >= xDomain[0] && p.x <= xDomain[xDomain.length - 1]; }; } /** #### .stack(group[, name, accessor]) Stack a new crossfilter group onto this chart with an optional custom value accessor. All stacks in the same chart will share the same key accessor and therefore the same set of keys. For example, in a stacked bar chart, the bars of each stack will be positioned using the same set of keys on the x axis, while stacked vertically. If name is specified then it will be used to generate the legend label. ```js // stack group using default accessor chart.stack(valueSumGroup) // stack group using custom accessor .stack(avgByDayGroup, function(d){return d.value.avgByDay;}); ``` **/ _chart.stack = function (group, name, accessor) { if (!arguments.length) { return _stack; } if (arguments.length <= 2) { accessor = name; } var layer = {group:group}; if (typeof name === 'string') { layer.name = name; } if (typeof accessor === 'function') { layer.accessor = accessor; } _stack.push(layer); return _chart; }; dc.override(_chart, 'group', function (g, n, f) { if (!arguments.length) { return _chart._group(); } _stack = []; _titles = {}; _chart.stack(g, n); if (f) { _chart.valueAccessor(f); } return _chart._group(g, n); }); /** #### .hidableStacks([boolean]) Allow named stacks to be hidden or shown by clicking on legend items. This does not affect the behavior of hideStack or showStack. **/ _chart.hidableStacks = function (_) { if (!arguments.length) { return _hidableStacks; } _hidableStacks = _; return _chart; }; function findLayerByName(n) { var i = _stack.map(dc.pluck('name')).indexOf(n); return _stack[i]; } /** #### .hideStack(name) Hide all stacks on the chart with the given name. The chart must be re-rendered for this change to appear. **/ _chart.hideStack = function (stackName) { var layer = findLayerByName(stackName); if (layer) { layer.hidden = true; } return _chart; }; /** #### .showStack(name) Show all stacks on the chart with the given name. The chart must be re-rendered for this change to appear. **/ _chart.showStack = function (stackName) { var layer = findLayerByName(stackName); if (layer) { layer.hidden = false; } return _chart; }; _chart.getValueAccessorByIndex = function (index) { return _stack[index].accessor || _chart.valueAccessor(); }; _chart.yAxisMin = function () { var min = d3.min(flattenStack(), function (p) { return (p.y + p.y0 < p.y0) ? (p.y + p.y0) : p.y0; }); return dc.utils.subtract(min, _chart.yAxisPadding()); }; _chart.yAxisMax = function () { var max = d3.max(flattenStack(), function (p) { return p.y + p.y0; }); return dc.utils.add(max, _chart.yAxisPadding()); }; function flattenStack() { return _chart.data().reduce(function (all, layer) { return all.concat(layer.values); }, []); } _chart.xAxisMin = function () { var min = d3.min(flattenStack(), dc.pluck('x')); return dc.utils.subtract(min, _chart.xAxisPadding()); }; _chart.xAxisMax = function () { var max = d3.max(flattenStack(), dc.pluck('x')); return dc.utils.add(max, _chart.xAxisPadding()); }; /** #### .title([stackName], [titleFunction]) Set or get the title function. Chart class will use this function to render svg title (usually interpreted by browser as tooltips) for each child element in the chart, i.e. a slice in a pie chart or a bubble in a bubble chart. Almost every chart supports title function however in grid coordinate chart you need to turn off brush in order to use title otherwise the brush layer will block tooltip trigger. If the first argument is a stack name, the title function will get or set the title for that stack. If stackName is not provided, the first stack is implied. ```js // set a title function on 'first stack' chart.title('first stack', function(d) { return d.key + ': ' + d.value; }); // get a title function from 'second stack' var secondTitleFunction = chart.title('second stack'); ); ``` **/ dc.override(_chart, 'title', function (stackName, titleAccessor) { if (!stackName) { return _chart._title(); } if (typeof stackName === 'function') { return _chart._title(stackName); } if (stackName === _chart._groupName && typeof titleAccessor === 'function') { return _chart._title(titleAccessor); } if (typeof titleAccessor !== 'function') { return _titles[stackName] || _chart._title(); } _titles[stackName] = titleAccessor; return _chart; }); /** #### .stackLayout([layout]) Gets or sets the stack layout algorithm, which computes a baseline for each stack and propagates it to the next. The default is [d3.layout.stack](https://github.com/mbostock/d3/wiki/Stack-Layout#stack). **/ _chart.stackLayout = function (stack) { if (!arguments.length) { return _stackLayout; } _stackLayout = stack; return _chart; }; function visability(l) { return !l.hidden; } _chart.data(function () { var layers = _stack.filter(visability); return layers.length ? _chart.stackLayout()(layers) : []; }); _chart._ordinalXDomain = function () { return flattenStack().map(dc.pluck('x')); }; _chart.colorAccessor(function (d) { var layer = this.layer || this.name || d.name || d.layer; return layer; }); _chart.legendables = function () { return _stack.map(function (layer, i) { return { chart:_chart, name:layer.name, hidden: layer.hidden || false, color:_chart.getColor.call(layer, layer.values, i) }; }); }; _chart.isLegendableHidden = function (d) { var layer = findLayerByName(d.name); return layer ? layer.hidden : false; }; _chart.legendToggle = function (d) { if (_hidableStacks) { if (_chart.isLegendableHidden(d)) { _chart.showStack(d.name); } else { _chart.hideStack(d.name); } //_chart.redraw(); _chart.renderGroup(); } }; return _chart; }; /** ## Cap Mixin Cap is a mixin that groups small data elements below a _cap_ into an *others* grouping for both the Row and Pie Charts. The top ordered elements in the group up to the cap amount will be kept in the chart, and the rest will be replaced with an *others* element, with value equal to the sum of the replaced values. The keys of the elements below the cap limit are recorded in order to filter by those keys when the *others* element is clicked. **/ dc.capMixin = function (_chart) { var _cap = Infinity; var _othersLabel = 'Others'; var _othersGrouper = function (topRows) { var topRowsSum = d3.sum(topRows, _chart.valueAccessor()), allRows = _chart.group().all(), allRowsSum = d3.sum(allRows, _chart.valueAccessor()), topKeys = topRows.map(_chart.keyAccessor()), allKeys = allRows.map(_chart.keyAccessor()), topSet = d3.set(topKeys), others = allKeys.filter(function (d) {return !topSet.has(d);}); if (allRowsSum > topRowsSum) { return topRows.concat([{'others': others, 'key': _othersLabel, 'value': allRowsSum - topRowsSum}]); } return topRows; }; _chart.cappedKeyAccessor = function (d, i) { if (d.others) { return d.key; } return _chart.keyAccessor()(d, i); }; _chart.cappedValueAccessor = function (d, i) { if (d.others) { return d.value; } return _chart.valueAccessor()(d, i); }; _chart.data(function (group) { if (_cap === Infinity) { return _chart._computeOrderedGroups(group.all()); } else { var topRows = group.top(_cap); // ordered by crossfilter group order (default value) topRows = _chart._computeOrderedGroups(topRows); // re-order using ordering (default key) if (_othersGrouper) { return _othersGrouper(topRows); } return topRows; } }); /** #### .cap([count]) Get or set the count of elements to that will be included in the cap. **/ _chart.cap = function (_) { if (!arguments.length) { return _cap; } _cap = _; return _chart; }; /** #### .othersLabel([label]) Get or set the label for *Others* slice when slices cap is specified. Default label is **Others**. **/ _chart.othersLabel = function (_) { if (!arguments.length) { return _othersLabel; } _othersLabel = _; return _chart; }; /** #### .othersGrouper([grouperFunction]) Get or set the grouper function that will perform the insertion of data for the *Others* slice if the slices cap is specified. If set to a falsy value, no others will be added. By default the grouper function computes the sum of all values below the cap. ```js chart.othersGrouper(function (data) { // compute the value for others, presumably the sum of all values below the cap var othersSum = yourComputeOthersValueLogic(data) // the keys are needed to properly filter when the others element is clicked var othersKeys = yourComputeOthersKeysArrayLogic(data); // add the others row to the dataset data.push({'key': 'Others', 'value': othersSum, 'others': othersKeys }); return data; }); ``` **/ _chart.othersGrouper = function (_) { if (!arguments.length) { return _othersGrouper; } _othersGrouper = _; return _chart; }; dc.override(_chart, 'onClick', function (d) { if (d.others) { _chart.filter([d.others]); } _chart._onClick(d); }); return _chart; }; /** ## Bubble Mixin Includes: [Color Mixin](#color-mixin) This Mixin provides reusable functionalities for any chart that needs to visualize data using bubbles. **/ dc.bubbleMixin = function (_chart) { var _maxBubbleRelativeSize = 0.3; var _minRadiusWithLabel = 10; _chart.BUBBLE_NODE_CLASS = 'node'; _chart.BUBBLE_CLASS = 'bubble'; _chart.MIN_RADIUS = 10; _chart = dc.colorMixin(_chart); _chart.renderLabel(true); _chart.data(function (group) { return group.top(Infinity); }); var _r = d3.scale.linear().domain([0, 100]); var _rValueAccessor = function (d) { return d.r; }; /** #### .r([bubbleRadiusScale]) Get or set the bubble radius scale. By default the bubble chart uses `d3.scale.linear().domain([0, 100])` as its r scale . **/ _chart.r = function (_) { if (!arguments.length) { return _r; } _r = _; return _chart; }; /** #### .radiusValueAccessor([radiusValueAccessor]) Get or set the radius value accessor function. If set, the radius value accessor function will be used to retrieve a data value for each bubble. The data retrieved then will be mapped using the r scale to the actual bubble radius. This allows you to encode a data dimension using bubble size. **/ _chart.radiusValueAccessor = function (_) { if (!arguments.length) { return _rValueAccessor; } _rValueAccessor = _; return _chart; }; _chart.rMin = function () { var min = d3.min(_chart.data(), function (e) { return _chart.radiusValueAccessor()(e); }); return min; }; _chart.rMax = function () { var max = d3.max(_chart.data(), function (e) { return _chart.radiusValueAccessor()(e); }); return max; }; _chart.bubbleR = function (d) { var value = _chart.radiusValueAccessor()(d); var r = _chart.r()(value); if (isNaN(r) || value <= 0) { r = 0; } return r; }; var labelFunction = function (d) { return _chart.label()(d); }; var labelOpacity = function (d) { return (_chart.bubbleR(d) > _minRadiusWithLabel) ? 1 : 0; }; _chart._doRenderLabel = function (bubbleGEnter) { if (_chart.renderLabel()) { var label = bubbleGEnter.select('text'); if (label.empty()) { label = bubbleGEnter.append('text') .attr('text-anchor', 'middle') .attr('dy', '.3em') .on('click', _chart.onClick); } label .attr('opacity', 0) .text(labelFunction); dc.transition(label, _chart.transitionDuration()) .attr('opacity', labelOpacity); } }; _chart.doUpdateLabels = function (bubbleGEnter) { if (_chart.renderLabel()) { var labels = bubbleGEnter.selectAll('text') .text(labelFunction); dc.transition(labels, _chart.transitionDuration()) .attr('opacity', labelOpacity); } }; var titleFunction = function (d) { return _chart.title()(d); }; _chart._doRenderTitles = function (g) { if (_chart.renderTitle()) { var title = g.select('title'); if (title.empty()) { g.append('title').text(titleFunction); } } }; _chart.doUpdateTitles = function (g) { if (_chart.renderTitle()) { g.selectAll('title').text(titleFunction); } }; /** #### .minRadiusWithLabel([radius]) Get or set the minimum radius for label rendering. If a bubble's radius is less than this value then no label will be rendered. Default: 10 **/ _chart.minRadiusWithLabel = function (_) { if (!arguments.length) { return _minRadiusWithLabel; } _minRadiusWithLabel = _; return _chart; }; /** #### .maxBubbleRelativeSize([relativeSize]) Get or set the maximum relative size of a bubble to the length of x axis. This value is useful when the difference in radius between bubbles is too great. Default: 0.3 **/ _chart.maxBubbleRelativeSize = function (_) { if (!arguments.length) { return _maxBubbleRelativeSize; } _maxBubbleRelativeSize = _; return _chart; }; _chart.fadeDeselectedArea = function () { if (_chart.hasFilter()) { _chart.selectAll('g.' + _chart.BUBBLE_NODE_CLASS).each(function (d) { if (_chart.isSelectedNode(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.selectAll('g.' + _chart.BUBBLE_NODE_CLASS).each(function () { _chart.resetHighlight(this); }); } }; _chart.isSelectedNode = function (d) { return _chart.hasFilter(d.key); }; _chart.onClick = function (d) { var filter = d.key; dc.events.trigger(function () { _chart.filter(filter); _chart.redrawGroup(); }); }; return _chart; }; /** ## Pie Chart Includes: [Cap Mixin](#cap-mixin), [Color Mixin](#color-mixin), [Base Mixin](#base-mixin) The pie chart implementation is usually used to visualize a small categorical distribution. The pie chart uses keyAccessor to determine the slices, and valueAccessor to calculate the size of each slice relative to the sum of all values. Slices are ordered by `.ordering` which defaults to sorting by key. Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) #### dc.pieChart(parent[, chartGroup]) Create a pie chart instance and attaches it to the given parent element. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created pie chart instance ```js // create a pie chart under #chart-container1 element using the default global chart group var chart1 = dc.pieChart('#chart-container1'); // create a pie chart under #chart-container2 element using chart group A var chart2 = dc.pieChart('#chart-container2', 'chartGroupA'); ``` **/ dc.pieChart = function (parent, chartGroup) { var DEFAULT_MIN_ANGLE_FOR_LABEL = 0.5; var _sliceCssClass = 'pie-slice'; var _emptyCssClass = 'empty-chart'; var _emptyTitle = 'empty'; var _radius, _innerRadius = 0; var _g; var _cx; var _cy; var _minAngleForLabel = DEFAULT_MIN_ANGLE_FOR_LABEL; var _externalLabelRadius; var _chart = dc.capMixin(dc.colorMixin(dc.baseMixin({}))); _chart.colorAccessor(_chart.cappedKeyAccessor); _chart.title(function (d) { return _chart.cappedKeyAccessor(d) + ': ' + _chart.cappedValueAccessor(d); }); /** #### .slicesCap([cap]) Get or set the maximum number of slices the pie chart will generate. The top slices are determined by value from high to low. Other slices exeeding the cap will be rolled up into one single *Others* slice. The resulting data will still be sorted by .ordering (default by key). **/ _chart.slicesCap = _chart.cap; _chart.label(_chart.cappedKeyAccessor); _chart.renderLabel(true); _chart.transitionDuration(350); _chart._doRender = function () { _chart.resetSvg(); _g = _chart.svg() .append('g') .attr('transform', 'translate(' + _chart.cx() + ',' + _chart.cy() + ')'); drawChart(); return _chart; }; function drawChart() { // set radius on basis of chart dimension if missing _radius = _radius ? _radius : d3.min([_chart.width(), _chart.height()]) / 2; var arc = buildArcs(); var pie = pieLayout(); var pieData; // if we have data... if (d3.sum(_chart.data(), _chart.valueAccessor())) { pieData = pie(_chart.data()); _g.classed(_emptyCssClass, false); } else { // otherwise we'd be getting NaNs, so override // note: abuse others for its ignoring the value accessor pieData = pie([{key:_emptyTitle, value:1, others: [_emptyTitle]}]); _g.classed(_emptyCssClass, true); } if (_g) { var slices = _g.selectAll('g.' + _sliceCssClass) .data(pieData); createElements(slices, arc, pieData); updateElements(pieData, arc); removeElements(slices); highlightFilter(); } } function createElements(slices, arc, pieData) { var slicesEnter = createSliceNodes(slices); createSlicePath(slicesEnter, arc); createTitles(slicesEnter); createLabels(pieData, arc); } function createSliceNodes(slices) { var slicesEnter = slices .enter() .append('g') .attr('class', function (d, i) { return _sliceCssClass + ' _' + i; }); return slicesEnter; } function createSlicePath(slicesEnter, arc) { var slicePath = slicesEnter.append('path') .attr('fill', fill) .on('click', onClick) .attr('d', function (d, i) { return safeArc(d, i, arc); }); dc.transition(slicePath, _chart.transitionDuration(), function (s) { s.attrTween('d', tweenPie); }); } function createTitles(slicesEnter) { if (_chart.renderTitle()) { slicesEnter.append('title').text(function (d) { return _chart.title()(d); }); } } function positionLabels(labelsEnter, arc) { dc.transition(labelsEnter, _chart.transitionDuration()) .attr('transform', function (d) { return labelPosition(d, arc); }) .attr('text-anchor', 'middle') .text(function (d) { var data = d.data; if (sliceHasNoData(data) || sliceTooSmall(d)) { return ''; } return _chart.label()(d.data); }); } function createLabels(pieData, arc) { if (_chart.renderLabel()) { var labels = _g.selectAll('text.' + _sliceCssClass) .data(pieData); labels.exit().remove(); var labelsEnter = labels .enter() .append('text') .attr('class', function (d, i) { var classes = _sliceCssClass + ' _' + i; if (_externalLabelRadius) { classes += ' external'; } return classes; }) .on('click', onClick); positionLabels(labelsEnter, arc); } } function updateElements(pieData, arc) { updateSlicePaths(pieData, arc); updateLabels(pieData, arc); updateTitles(pieData); } function updateSlicePaths(pieData, arc) { var slicePaths = _g.selectAll('g.' + _sliceCssClass) .data(pieData) .select('path') .attr('d', function (d, i) { return safeArc(d, i, arc); }); dc.transition(slicePaths, _chart.transitionDuration(), function (s) { s.attrTween('d', tweenPie); }).attr('fill', fill); } function updateLabels(pieData, arc) { if (_chart.renderLabel()) { var labels = _g.selectAll('text.' + _sliceCssClass) .data(pieData); positionLabels(labels, arc); } } function updateTitles(pieData) { if (_chart.renderTitle()) { _g.selectAll('g.' + _sliceCssClass) .data(pieData) .select('title') .text(function (d) { return _chart.title()(d.data); }); } } function removeElements(slices) { slices.exit().remove(); } function highlightFilter() { if (_chart.hasFilter()) { _chart.selectAll('g.' + _sliceCssClass).each(function (d) { if (isSelectedSlice(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.selectAll('g.' + _sliceCssClass).each(function () { _chart.resetHighlight(this); }); } } /** #### .innerRadius([innerRadius]) Get or set the inner radius of the pie chart. If the inner radius is greater than 0px then the pie chart will be rendered as a doughnut chart. Default inner radius is 0px. **/ _chart.innerRadius = function (r) { if (!arguments.length) { return _innerRadius; } _innerRadius = r; return _chart; }; /** #### .radius([radius]) Get or set the outer radius. If the radius is not set, it will be half of the minimum of the chart width and height. **/ _chart.radius = function (r) { if (!arguments.length) { return _radius; } _radius = r; return _chart; }; /** #### .cx([cx]) Get or set center x coordinate position. Default is center of svg. **/ _chart.cx = function (cx) { if (!arguments.length) { return (_cx || _chart.width() / 2); } _cx = cx; return _chart; }; /** #### .cy([cy]) Get or set center y coordinate position. Default is center of svg. **/ _chart.cy = function (cy) { if (!arguments.length) { return (_cy || _chart.height() / 2); } _cy = cy; return _chart; }; function buildArcs() { return d3.svg.arc().outerRadius(_radius).innerRadius(_innerRadius); } function isSelectedSlice(d) { return _chart.hasFilter(_chart.cappedKeyAccessor(d.data)); } _chart._doRedraw = function () { drawChart(); return _chart; }; /** #### .minAngleForLabel([minAngle]) Get or set the minimal slice angle for label rendering. Any slice with a smaller angle will not display a slice label. Default min angle is 0.5. **/ _chart.minAngleForLabel = function (_) { if (!arguments.length) { return _minAngleForLabel; } _minAngleForLabel = _; return _chart; }; function pieLayout() { return d3.layout.pie().sort(null).value(_chart.cappedValueAccessor); } function sliceTooSmall(d) { var angle = (d.endAngle - d.startAngle); return isNaN(angle) || angle < _minAngleForLabel; } function sliceHasNoData(d) { return _chart.cappedValueAccessor(d) === 0; } function tweenPie(b) { b.innerRadius = _innerRadius; var current = this._current; if (isOffCanvas(current)) { current = {startAngle: 0, endAngle: 0}; } var i = d3.interpolate(current, b); this._current = i(0); return function (t) { return safeArc(i(t), 0, buildArcs()); }; } function isOffCanvas(current) { return !current || isNaN(current.startAngle) || isNaN(current.endAngle); } function fill(d, i) { return _chart.getColor(d.data, i); } function onClick(d, i) { if (_g.attr('class') !== _emptyCssClass) { _chart.onClick(d.data, i); } } function safeArc(d, i, arc) { var path = arc(d, i); if (path.indexOf('NaN') >= 0) { path = 'M0,0'; } return path; } /** #### .emptyTitle([title]) Title to use for the only slice when there is no data */ _chart.emptyTitle = function (title) { if (arguments.length === 0) { return _emptyTitle; } _emptyTitle = title; return _chart; }; /** #### .externalLabels([radius]) Position slice labels offset from the outer edge of the chart The given argument sets the radial offset. */ _chart.externalLabels = function (radius) { if (arguments.length === 0) { return _externalLabelRadius; } else if (radius) { _externalLabelRadius = radius; } else { _externalLabelRadius = undefined; } return _chart; }; function labelPosition(d, arc) { var centroid; if (_externalLabelRadius) { centroid = d3.svg.arc() .outerRadius(_radius + _externalLabelRadius) .innerRadius(_radius + _externalLabelRadius) .centroid(d); } else { centroid = arc.centroid(d); } if (isNaN(centroid[0]) || isNaN(centroid[1])) { return 'translate(0,0)'; } else { return 'translate(' + centroid + ')'; } } _chart.legendables = function () { return _chart.data().map(function (d, i) { var legendable = {name: d.key, data: d.value, others: d.others, chart:_chart}; legendable.color = _chart.getColor(d, i); return legendable; }); }; _chart.legendHighlight = function (d) { highlightSliceFromLegendable(d, true); }; _chart.legendReset = function (d) { highlightSliceFromLegendable(d, false); }; _chart.legendToggle = function (d) { _chart.onClick({key: d.name, others: d.others}); }; function highlightSliceFromLegendable(legendable, highlighted) { _chart.selectAll('g.pie-slice').each(function (d) { if (legendable.name === d.data.key) { d3.select(this).classed('highlight', highlighted); } }); } return _chart.anchor(parent, chartGroup); }; /** ## Bar Chart Includes: [Stack Mixin](#stack Mixin), [Coordinate Grid Mixin](#coordinate-grid-mixin) Concrete bar chart/histogram implementation. Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) #### dc.barChart(parent[, chartGroup]) Create a bar chart instance and attach it to the given parent element. Parameters: * parent : string | node | selection | compositeChart - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created bar chart instance ```js // create a bar chart under #chart-container1 element using the default global chart group var chart1 = dc.barChart('#chart-container1'); // create a bar chart under #chart-container2 element using chart group A var chart2 = dc.barChart('#chart-container2', 'chartGroupA'); // create a sub-chart under a composite parent chart var chart3 = dc.barChart(compositeChart); ``` **/ dc.barChart = function (parent, chartGroup) { var MIN_BAR_WIDTH = 1; var DEFAULT_GAP_BETWEEN_BARS = 2; var _chart = dc.stackMixin(dc.coordinateGridMixin({})); var _gap = DEFAULT_GAP_BETWEEN_BARS; var _centerBar = false; var _alwaysUseRounding = false; var _barWidth; dc.override(_chart, 'rescale', function () { _chart._rescale(); _barWidth = undefined; }); dc.override(_chart, 'render', function () { if (_chart.round() && _centerBar && !_alwaysUseRounding) { dc.logger.warn('By default, brush rounding is disabled if bars are centered. ' + 'See dc.js bar chart API documentation for details.'); } _chart._render(); }); _chart.plotData = function () { var layers = _chart.chartBodyG().selectAll('g.stack') .data(_chart.data()); calculateBarWidth(); layers .enter() .append('g') .attr('class', function (d, i) { return 'stack ' + '_' + i; }); layers.each(function (d, i) { var layer = d3.select(this); renderBars(layer, i, d); }); }; function barHeight(d) { return dc.utils.safeNumber(Math.abs(_chart.y()(d.y + d.y0) - _chart.y()(d.y0))); } function renderBars(layer, layerIndex, d) { var bars = layer.selectAll('rect.bar') .data(d.values, dc.pluck('x')); var enter = bars.enter() .append('rect') .attr('class', 'bar') .attr('fill', dc.pluck('data', _chart.getColor)) .attr('y', _chart.yAxisHeight()) .attr('height', 0); if (_chart.renderTitle()) { enter.append('title').text(dc.pluck('data', _chart.title(d.name))); } if (_chart.isOrdinal()) { bars.on('click', onClick); } dc.transition(bars, _chart.transitionDuration()) .attr('x', function (d) { var x = _chart.x()(d.x); if (_centerBar) { x -= _barWidth / 2; } if (_chart.isOrdinal() && _gap !== undefined) { x += _gap / 2; } return dc.utils.safeNumber(x); }) .attr('y', function (d) { var y = _chart.y()(d.y + d.y0); if (d.y < 0) { y -= barHeight(d); } return dc.utils.safeNumber(y); }) .attr('width', _barWidth) .attr('height', function (d) { return barHeight(d); }) .attr('fill', dc.pluck('data', _chart.getColor)) .select('title').text(dc.pluck('data', _chart.title(d.name))); dc.transition(bars.exit(), _chart.transitionDuration()) .attr('height', 0) .remove(); } function calculateBarWidth() { if (_barWidth === undefined) { var numberOfBars = _chart.xUnitCount(); // please can't we always use rangeBands for bar charts? if (_chart.isOrdinal() && _gap === undefined) { _barWidth = Math.floor(_chart.x().rangeBand()); } else if (_gap) { _barWidth = Math.floor((_chart.xAxisLength() - (numberOfBars - 1) * _gap) / numberOfBars); } else { _barWidth = Math.floor(_chart.xAxisLength() / (1 + _chart.barPadding()) / numberOfBars); } if (_barWidth === Infinity || isNaN(_barWidth) || _barWidth < MIN_BAR_WIDTH) { _barWidth = MIN_BAR_WIDTH; } } } _chart.fadeDeselectedArea = function () { var bars = _chart.chartBodyG().selectAll('rect.bar'); var extent = _chart.brush().extent(); if (_chart.isOrdinal()) { if (_chart.hasFilter()) { bars.classed(dc.constants.SELECTED_CLASS, function (d) { return _chart.hasFilter(d.x); }); bars.classed(dc.constants.DESELECTED_CLASS, function (d) { return !_chart.hasFilter(d.x); }); } else { bars.classed(dc.constants.SELECTED_CLASS, false); bars.classed(dc.constants.DESELECTED_CLASS, false); } } else { if (!_chart.brushIsEmpty(extent)) { var start = extent[0]; var end = extent[1]; bars.classed(dc.constants.DESELECTED_CLASS, function (d) { return d.x < start || d.x >= end; }); } else { bars.classed(dc.constants.DESELECTED_CLASS, false); } } }; /** #### .centerBar(boolean) Whether the bar chart will render each bar centered around the data position on x axis. Default: false **/ _chart.centerBar = function (_) { if (!arguments.length) { return _centerBar; } _centerBar = _; return _chart; }; function onClick(d) { _chart.onClick(d.data); } /** #### .barPadding([padding]) Get or set the spacing between bars as a fraction of bar size. Valid values are between 0-1. Setting this value will also remove any previously set `gap`. See the [d3 docs](https://github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-ordinal_rangeBands) for a visual description of how the padding is applied. **/ _chart.barPadding = function (_) { if (!arguments.length) { return _chart._rangeBandPadding(); } _chart._rangeBandPadding(_); _gap = undefined; return _chart; }; _chart._useOuterPadding = function () { return _gap === undefined; }; /** #### .outerPadding([padding]) Get or set the outer padding on an ordinal bar chart. This setting has no effect on non-ordinal charts. Will pad the width by `padding * barWidth` on each side of the chart. Default: 0.5 **/ _chart.outerPadding = _chart._outerRangeBandPadding; /** #### .gap(gapBetweenBars) Manually set fixed gap (in px) between bars instead of relying on the default auto-generated gap. By default the bar chart implementation will calculate and set the gap automatically based on the number of data points and the length of the x axis. **/ _chart.gap = function (_) { if (!arguments.length) { return _gap; } _gap = _; return _chart; }; _chart.extendBrush = function () { var extent = _chart.brush().extent(); if (_chart.round() && (!_centerBar || _alwaysUseRounding)) { extent[0] = extent.map(_chart.round())[0]; extent[1] = extent.map(_chart.round())[1]; _chart.chartBodyG().select('.brush') .call(_chart.brush().extent(extent)); } return extent; }; /** #### .alwaysUseRounding([boolean]) Set or get whether rounding is enabled when bars are centered. Default: false. If false, using rounding with centered bars will result in a warning and rounding will be ignored. This flag has no effect if bars are not centered. When using standard d3.js rounding methods, the brush often doesn't align correctly with centered bars since the bars are offset. The rounding function must add an offset to compensate, such as in the following example. ```js chart.round(function(n) {return Math.floor(n)+0.5}); ``` **/ _chart.alwaysUseRounding = function (_) { if (!arguments.length) { return _alwaysUseRounding; } _alwaysUseRounding = _; return _chart; }; function colorFilter(color, inv) { return function () { var item = d3.select(this); var match = item.attr('fill') === color; return inv ? !match : match; }; } _chart.legendHighlight = function (d) { if (!_chart.isLegendableHidden(d)) { _chart.g().selectAll('rect.bar') .classed('highlight', colorFilter(d.color)) .classed('fadeout', colorFilter(d.color, true)); } }; _chart.legendReset = function () { _chart.g().selectAll('rect.bar') .classed('highlight', false) .classed('fadeout', false); }; dc.override(_chart, 'xAxisMax', function () { var max = this._xAxisMax(); if ('resolution' in _chart.xUnits()) { var res = _chart.xUnits().resolution; max += res; } return max; }); return _chart.anchor(parent, chartGroup); }; /** ## Line Chart Includes [Stack Mixin](#stack-mixin), [Coordinate Grid Mixin](#coordinate-grid-mixin) Concrete line/area chart implementation. Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) #### dc.lineChart(parent[, chartGroup]) Create a line chart instance and attach it to the given parent element. Parameters: * parent : string | node | selection | compositeChart - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. If the line chart is a sub-chart in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created line chart instance ```js // create a line chart under #chart-container1 element using the default global chart group var chart1 = dc.lineChart('#chart-container1'); // create a line chart under #chart-container2 element using chart group A var chart2 = dc.lineChart('#chart-container2', 'chartGroupA'); // create a sub-chart under a composite parent chart var chart3 = dc.lineChart(compositeChart); ``` **/ dc.lineChart = function (parent, chartGroup) { var DEFAULT_DOT_RADIUS = 5; var TOOLTIP_G_CLASS = 'dc-tooltip'; var DOT_CIRCLE_CLASS = 'dot'; var Y_AXIS_REF_LINE_CLASS = 'yRef'; var X_AXIS_REF_LINE_CLASS = 'xRef'; var DEFAULT_DOT_OPACITY = 1e-6; var _chart = dc.stackMixin(dc.coordinateGridMixin({})); var _renderArea = false; var _dotRadius = DEFAULT_DOT_RADIUS; var _dataPointRadius = null; var _dataPointFillOpacity = DEFAULT_DOT_OPACITY; var _dataPointStrokeOpacity = DEFAULT_DOT_OPACITY; var _interpolate = 'linear'; var _tension = 0.7; var _defined; var _dashStyle; _chart.transitionDuration(500); _chart._rangeBandPadding(1); _chart.plotData = function () { var chartBody = _chart.chartBodyG(); var layersList = chartBody.selectAll('g.stack-list'); if (layersList.empty()) { layersList = chartBody.append('g').attr('class', 'stack-list'); } var layers = layersList.selectAll('g.stack').data(_chart.data()); var layersEnter = layers .enter() .append('g') .attr('class', function (d, i) { return 'stack ' + '_' + i; }); drawLine(layersEnter, layers); drawArea(layersEnter, layers); drawDots(chartBody, layers); }; /** #### .interpolate([value]) Gets or sets the interpolator to use for lines drawn, by string name, allowing e.g. step functions, splines, and cubic interpolation. This is passed to [d3.svg.line.interpolate](https://github.com/mbostock/d3/wiki/SVG-Shapes#line_interpolate) and [d3.svg.area.interpolate](https://github.com/mbostock/d3/wiki/SVG-Shapes#area_interpolate), where you can find a complete list of valid arguments **/ _chart.interpolate = function (_) { if (!arguments.length) { return _interpolate; } _interpolate = _; return _chart; }; /** #### .tension([value]) Gets or sets the tension to use for lines drawn, in the range 0 to 1. This parameter further customizes the interpolation behavior. It is passed to [d3.svg.line.tension](https://github.com/mbostock/d3/wiki/SVG-Shapes#line_tension) and [d3.svg.area.tension](https://github.com/mbostock/d3/wiki/SVG-Shapes#area_tension). Default: 0.7 **/ _chart.tension = function (_) { if (!arguments.length) { return _tension; } _tension = _; return _chart; }; /** #### .defined([value]) Gets or sets a function that will determine discontinuities in the line which should be skipped: the path will be broken into separate subpaths if some points are undefined. This function is passed to [d3.svg.line.defined](https://github.com/mbostock/d3/wiki/SVG-Shapes#line_defined) Note: crossfilter will sometimes coerce nulls to 0, so you may need to carefully write custom reduce functions to get this to work, depending on your data. See https://github.com/dc-js/dc.js/issues/615#issuecomment-49089248 **/ _chart.defined = function (_) { if (!arguments.length) { return _defined; } _defined = _; return _chart; }; /** #### .dashStyle([array]) Set the line's d3 dashstyle. This value becomes the 'stroke-dasharray' of line. Defaults to empty array (solid line). ```js // create a Dash Dot Dot Dot chart.dashStyle([3,1,1,1]); ``` **/ _chart.dashStyle = function (_) { if (!arguments.length) { return _dashStyle; } _dashStyle = _; return _chart; }; /** #### .renderArea([boolean]) Get or set render area flag. If the flag is set to true then the chart will render the area beneath each line and the line chart effectively becomes an area chart. **/ _chart.renderArea = function (_) { if (!arguments.length) { return _renderArea; } _renderArea = _; return _chart; }; function colors(d, i) { return _chart.getColor.call(d, d.values, i); } function drawLine(layersEnter, layers) { var line = d3.svg.line() .x(function (d) { return _chart.x()(d.x); }) .y(function (d) { return _chart.y()(d.y + d.y0); }) .interpolate(_interpolate) .tension(_tension); if (_defined) { line.defined(_defined); } var path = layersEnter.append('path') .attr('class', 'line') .attr('stroke', colors); if (_dashStyle) { path.attr('stroke-dasharray', _dashStyle); } dc.transition(layers.select('path.line'), _chart.transitionDuration()) //.ease('linear') .attr('stroke', colors) .attr('d', function (d) { return safeD(line(d.values)); }); } function drawArea(layersEnter, layers) { if (_renderArea) { var area = d3.svg.area() .x(function (d) { return _chart.x()(d.x); }) .y(function (d) { return _chart.y()(d.y + d.y0); }) .y0(function (d) { return _chart.y()(d.y0); }) .interpolate(_interpolate) .tension(_tension); if (_defined) { area.defined(_defined); } layersEnter.append('path') .attr('class', 'area') .attr('fill', colors) .attr('d', function (d) { return safeD(area(d.values)); }); dc.transition(layers.select('path.area'), _chart.transitionDuration()) //.ease('linear') .attr('fill', colors) .attr('d', function (d) { return safeD(area(d.values)); }); } } function safeD (d) { return (!d || d.indexOf('NaN') >= 0) ? 'M0,0' : d; } function drawDots(chartBody, layers) { if (!_chart.brushOn()) { var tooltipListClass = TOOLTIP_G_CLASS + '-list'; var tooltips = chartBody.select('g.' + tooltipListClass); if (tooltips.empty()) { tooltips = chartBody.append('g').attr('class', tooltipListClass); } layers.each(function (d, layerIndex) { var points = d.values; if (_defined) { points = points.filter(_defined); } var g = tooltips.select('g.' + TOOLTIP_G_CLASS + '._' + layerIndex); if (g.empty()) { g = tooltips.append('g').attr('class', TOOLTIP_G_CLASS + ' _' + layerIndex); } createRefLines(g); var dots = g.selectAll('circle.' + DOT_CIRCLE_CLASS) .data(points, dc.pluck('x')); dots.enter() .append('circle') .attr('class', DOT_CIRCLE_CLASS) .attr('r', getDotRadius()) .style('fill-opacity', _dataPointFillOpacity) .style('stroke-opacity', _dataPointStrokeOpacity) .on('mousemove', function () { var dot = d3.select(this); showDot(dot); showRefLines(dot, g); }) .on('mouseout', function () { var dot = d3.select(this); hideDot(dot); hideRefLines(g); }); dots .attr('cx', function (d) { return dc.utils.safeNumber(_chart.x()(d.x)); }) .attr('cy', function (d) { return dc.utils.safeNumber(_chart.y()(d.y + d.y0)); }) .attr('fill', _chart.getColor) .call(renderTitle, d); dots.exit().remove(); }); } } function createRefLines(g) { var yRefLine = g.select('path.' + Y_AXIS_REF_LINE_CLASS).empty() ? g.append('path').attr('class', Y_AXIS_REF_LINE_CLASS) : g.select('path.' + Y_AXIS_REF_LINE_CLASS); yRefLine.style('display', 'none').attr('stroke-dasharray', '5,5'); var xRefLine = g.select('path.' + X_AXIS_REF_LINE_CLASS).empty() ? g.append('path').attr('class', X_AXIS_REF_LINE_CLASS) : g.select('path.' + X_AXIS_REF_LINE_CLASS); xRefLine.style('display', 'none').attr('stroke-dasharray', '5,5'); } function showDot(dot) { dot.style('fill-opacity', 0.8); dot.style('stroke-opacity', 0.8); dot.attr('r', _dotRadius); return dot; } function showRefLines(dot, g) { var x = dot.attr('cx'); var y = dot.attr('cy'); var yAxisX = (_chart._yAxisX() - _chart.margins().left); var yAxisRefPathD = 'M' + yAxisX + ' ' + y + 'L' + (x) + ' ' + (y); var xAxisRefPathD = 'M' + x + ' ' + _chart.yAxisHeight() + 'L' + x + ' ' + y; g.select('path.' + Y_AXIS_REF_LINE_CLASS).style('display', '').attr('d', yAxisRefPathD); g.select('path.' + X_AXIS_REF_LINE_CLASS).style('display', '').attr('d', xAxisRefPathD); } function getDotRadius() { return _dataPointRadius || _dotRadius; } function hideDot(dot) { dot.style('fill-opacity', _dataPointFillOpacity) .style('stroke-opacity', _dataPointStrokeOpacity) .attr('r', getDotRadius()); } function hideRefLines(g) { g.select('path.' + Y_AXIS_REF_LINE_CLASS).style('display', 'none'); g.select('path.' + X_AXIS_REF_LINE_CLASS).style('display', 'none'); } function renderTitle(dot, d) { if (_chart.renderTitle()) { dot.selectAll('title').remove(); dot.append('title').text(dc.pluck('data', _chart.title(d.name))); } } /** #### .dotRadius([dotRadius]) Get or set the radius (in px) for dots displayed on the data points. Default dot radius is 5. **/ _chart.dotRadius = function (_) { if (!arguments.length) { return _dotRadius; } _dotRadius = _; return _chart; }; /** #### .renderDataPoints([options]) Always show individual dots for each datapoint. Options, if given, is an object that can contain the following: * fillOpacity (default 0.8) * strokeOpacity (default 0.8) * radius (default 2) If `options` is falsy, it disables data point rendering. If no `options` are provided, the current `options` values are instead returned. Example: ``` chart.renderDataPoints({radius: 2, fillOpacity: 0.8, strokeOpacity: 0.8}) ``` **/ _chart.renderDataPoints = function (options) { if (!arguments.length) { return { fillOpacity: _dataPointFillOpacity, strokeOpacity: _dataPointStrokeOpacity, radius: _dataPointRadius }; } else if (!options) { _dataPointFillOpacity = DEFAULT_DOT_OPACITY; _dataPointStrokeOpacity = DEFAULT_DOT_OPACITY; _dataPointRadius = null; } else { _dataPointFillOpacity = options.fillOpacity || 0.8; _dataPointStrokeOpacity = options.strokeOpacity || 0.8; _dataPointRadius = options.radius || 2; } return _chart; }; function colorFilter(color, dashstyle, inv) { return function () { var item = d3.select(this); var match = (item.attr('stroke') === color && item.attr('stroke-dasharray') === ((dashstyle instanceof Array) ? dashstyle.join(',') : null)) || item.attr('fill') === color; return inv ? !match : match; }; } _chart.legendHighlight = function (d) { if (!_chart.isLegendableHidden(d)) { _chart.g().selectAll('path.line, path.area') .classed('highlight', colorFilter(d.color, d.dashstyle)) .classed('fadeout', colorFilter(d.color, d.dashstyle, true)); } }; _chart.legendReset = function () { _chart.g().selectAll('path.line, path.area') .classed('highlight', false) .classed('fadeout', false); }; dc.override(_chart, 'legendables', function () { var legendables = _chart._legendables(); if (!_dashStyle) { return legendables; } return legendables.map(function (l) { l.dashstyle = _dashStyle; return l; }); }); return _chart.anchor(parent, chartGroup); }; /** ## Data Count Widget Includes: [Base Mixin](#base-mixin) The data count widget is a simple widget designed to display the number of records selected by the current filters out of the total number of records in the data set. Once created the data count widget will automatically update the text content of the following elements under the parent element. * '.total-count' - total number of records * '.filter-count' - number of records matched by the current filters Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) #### dc.dataCount(parent[, chartGroup]) Create a data count widget and attach it to the given parent element. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this widget should be placed in. The data count widget will only react to filter changes in the chart group. Returns: A newly created data count widget instance #### .dimension(allData) - **mandatory** For the data count widget the only valid dimension is the entire data set. #### .group(groupAll) - **mandatory** For the data count widget the only valid group is the group returned by `dimension.groupAll()`. ```js var ndx = crossfilter(data); var all = ndx.groupAll(); dc.dataCount('.dc-data-count') .dimension(ndx) .group(all); ``` **/ dc.dataCount = function (parent, chartGroup) { var _formatNumber = d3.format(',d'); var _chart = dc.baseMixin({}); var _html = {some:'', all:''}; /** #### html([object]) Gets or sets an optional object specifying HTML templates to use depending how many items are selected. The text `%total-count` will replaced with the total number of records, and the text `%filter-count` will be replaced with the number of selected records. - all: HTML template to use if all items are selected - some: HTML template to use if not all items are selected ```js counter.html({ some: '%filter-count out of %total-count records selected', all: 'All records selected. Click on charts to apply filters' }) ``` **/ _chart.html = function (s) { if (!arguments.length) { return _html; } if (s.all) { _html.all = s.all; } if (s.some) { _html.some = s.some; } return _chart; }; /** #### formatNumber([formatter]) Gets or sets an optional function to format the filter count and total count. ```js counter.formatNumber(d3.format('.2g')) ``` **/ _chart.formatNumber = function (s) { if (!arguments.length) { return _formatNumber; } _formatNumber = s; return _chart; }; _chart._doRender = function () { var tot = _chart.dimension().size(), val = _chart.group().value(); var all = _formatNumber(tot); var selected = _formatNumber(val); if ((tot === val) && (_html.all !== '')) { _chart.root().html(_html.all.replace('%total-count', all).replace('%filter-count', selected)); } else if (_html.some !== '') { _chart.root().html(_html.some.replace('%total-count', all).replace('%filter-count', selected)); } else { _chart.selectAll('.total-count').text(all); _chart.selectAll('.filter-count').text(selected); } return _chart; }; _chart._doRedraw = function () { return _chart._doRender(); }; return _chart.anchor(parent, chartGroup); }; /** ## Data Table Widget Includes: [Base Mixin](#base-mixin) The data table is a simple widget designed to list crossfilter focused data set (rows being filtered) in a good old tabular fashion. Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) #### dc.dataTable(parent[, chartGroup]) Create a data table widget instance and attach it to the given parent element. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created data table widget instance **/ dc.dataTable = function (parent, chartGroup) { var LABEL_CSS_CLASS = 'dc-table-label'; var ROW_CSS_CLASS = 'dc-table-row'; var COLUMN_CSS_CLASS = 'dc-table-column'; var GROUP_CSS_CLASS = 'dc-table-group'; var HEAD_CSS_CLASS = 'dc-table-head'; var _chart = dc.baseMixin({}); var _size = 25; var _columns = []; var _sortBy = function (d) { return d; }; var _order = d3.ascending; _chart._doRender = function () { _chart.selectAll('tbody').remove(); renderRows(renderGroups()); return _chart; }; _chart._doColumnValueFormat = function (v, d) { return ((typeof v === 'function') ? v(d) : // v as function ((typeof v === 'string') ? d[v] : // v is field name string v.format(d) // v is Object, use fn (element 2) ) ); }; _chart._doColumnHeaderFormat = function (d) { // if 'function', convert to string representation // show a string capitalized // if an object then display it's label string as-is. return (typeof d === 'function') ? _chart._doColumnHeaderFnToString(d) : ((typeof d === 'string') ? _chart._doColumnHeaderCapitalize(d) : String(d.label)); }; _chart._doColumnHeaderCapitalize = function (s) { // capitalize return s.charAt(0).toUpperCase() + s.slice(1); }; _chart._doColumnHeaderFnToString = function (f) { // columnString(f) { var s = String(f); var i1 = s.indexOf('return '); if (i1 >= 0) { var i2 = s.lastIndexOf(';'); if (i2 >= 0) { s = s.substring(i1 + 7, i2); var i3 = s.indexOf('numberFormat'); if (i3 >= 0) { s = s.replace('numberFormat', ''); } } } return s; }; function renderGroups() { // The 'original' example uses all 'functions'. // If all 'functions' are used, then don't remove/add a header, and leave // the html alone. This preserves the functionality of earlier releases. // A 2nd option is a string representing a field in the data. // A third option is to supply an Object such as an array of 'information', and // supply your own _doColumnHeaderFormat and _doColumnValueFormat functions to // create what you need. var bAllFunctions = true; _columns.forEach(function (f) { bAllFunctions = bAllFunctions & (typeof f === 'function'); }); if (!bAllFunctions) { _chart.selectAll('th').remove(); var headcols = _chart.root().selectAll('th') .data(_columns); var headGroup = headcols .enter() .append('th'); headGroup .attr('class', HEAD_CSS_CLASS) .html(function (d) { return (_chart._doColumnHeaderFormat(d)); }); } var groups = _chart.root().selectAll('tbody') .data(nestEntries(), function (d) { return _chart.keyAccessor()(d); }); var rowGroup = groups .enter() .append('tbody'); rowGroup .append('tr') .attr('class', GROUP_CSS_CLASS) .append('td') .attr('class', LABEL_CSS_CLASS) .attr('colspan', _columns.length) .html(function (d) { return _chart.keyAccessor()(d); }); groups.exit().remove(); return rowGroup; } function nestEntries() { var entries; if (_order === d3.ascending) { entries = _chart.dimension().bottom(_size); } else { entries = _chart.dimension().top(_size); } return d3.nest() .key(_chart.group()) .sortKeys(_order) .entries(entries.sort(function (a, b) { return _order(_sortBy(a), _sortBy(b)); })); } function renderRows(groups) { var rows = groups.order() .selectAll('tr.' + ROW_CSS_CLASS) .data(function (d) { return d.values; }); var rowEnter = rows.enter() .append('tr') .attr('class', ROW_CSS_CLASS); _columns.forEach(function (v, i) { rowEnter.append('td') .attr('class', COLUMN_CSS_CLASS + ' _' + i) .html(function (d) { return _chart._doColumnValueFormat(v, d); }); }); rows.exit().remove(); return rows; } _chart._doRedraw = function () { return _chart._doRender(); }; /** #### .size([size]) Get or set the table size which determines the number of rows displayed by the widget. **/ _chart.size = function (s) { if (!arguments.length) { return _size; } _size = s; return _chart; }; /** #### .columns([columnFunctionArray]) Get or set column functions. The data table widget now supports several methods of specifying the columns to display. The original method, first shown below, uses an array of functions to generate dynamic columns. Column functions are simple javascript functions with only one input argument `d` which represents a row in the data set. The return value of these functions will be used directly to generate table content for each cell. However, this method requires the .html table entry to have a fixed set of column headers. ```js chart.columns([ function(d) { return d.date; }, function(d) { return d.open; }, function(d) { return d.close; }, function(d) { return numberFormat(d.close - d.open); }, function(d) { return d.volume; } ]); ``` The next example shows you can simply list the data (d) content directly without specifying it as a function, except where necessary (ie, computed columns). Note the data element accessor name is capitalized when displayed in the table. You can also mix in functions as desired or necessary, but you must use the Object = [Label, Fn] method as shown below. You may wish to override the following two functions, which are internally used to translate the column information or function into a displayed header. The first one is used on the simple "string" column specifier, the second is used to transform the String(fn) into something displayable. For the Stock example, the function for Change becomes a header of 'd.close - d.open'. _chart._doColumnHeaderCapitalize _chart._doColumnHeaderFnToString You may use your own Object definition, however you must then override _chart._doColumnHeaderFormat , _chart._doColumnValueFormat Be aware that fields without numberFormat specification will be displayed just as they are stored in the data, unformatted. ```js chart.columns([ "date", // d["date"], ie, a field accessor; capitalized automatically "open", // ... "close", // ... ["Change", // Specify an Object = [Label, Fn] function (d) { return numberFormat(d.close - d.open); }], "volume" // d["volume"], ie, a field accessor; capitalized automatically ]); ``` A third example, where all fields are specified using the Object = [Label, Fn] method. ```js chart.columns([ ["Date", // Specify an Object = [Label, Fn] function (d) { return d.date; }], ["Open", function (d) { return numberFormat(d.open); }], ["Close", function (d) { return numberFormat(d.close); }], ["Change", function (d) { return numberFormat(d.close - d.open); }], ["Volume", function (d) { return d.volume; }] ]); ``` **/ _chart.columns = function (_) { if (!arguments.length) { return _columns; } _columns = _; return _chart; }; /** #### .sortBy([sortByFunction]) Get or set sort-by function. This function works as a value accessor at row level and returns a particular field to be sorted by. Default value: identity function ```js chart.sortBy(function(d) { return d.date; }); ``` **/ _chart.sortBy = function (_) { if (!arguments.length) { return _sortBy; } _sortBy = _; return _chart; }; /** #### .order([order]) Get or set sort order. Default value: ``` d3.ascending ``` ```js chart.order(d3.descending); ``` **/ _chart.order = function (_) { if (!arguments.length) { return _order; } _order = _; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** ## Data Grid Widget Includes: [Base Mixin](#base-mixin) Data grid is a simple widget designed to list the filtered records, providing a simple way to define how the items are displayed. Examples: * [List of members of the european parliament](http://europarl.me/dc.js/web/ep/index.html) #### dc.dataGrid(parent[, chartGroup]) Create a data grid widget instance and attach it to the given parent element. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created data grid widget instance **/ dc.dataGrid = function (parent, chartGroup) { var LABEL_CSS_CLASS = 'dc-grid-label'; var ITEM_CSS_CLASS = 'dc-grid-item'; var GROUP_CSS_CLASS = 'dc-grid-group'; var GRID_CSS_CLASS = 'dc-grid-top'; var _chart = dc.baseMixin({}); var _size = 999; // shouldn't be needed, but you might var _html = function (d) { return 'you need to provide an html() handling param: ' + JSON.stringify(d); }; var _sortBy = function (d) { return d; }; var _order = d3.ascending; var _htmlGroup = function (d) { return '<div class=\'' + GROUP_CSS_CLASS + '\'><h1 class=\'' + LABEL_CSS_CLASS + '\'>' + _chart.keyAccessor()(d) + '</h1></div>'; }; _chart._doRender = function () { _chart.selectAll('div.' + GRID_CSS_CLASS).remove(); renderItems(renderGroups()); return _chart; }; function renderGroups() { var groups = _chart.root().selectAll('div.' + GRID_CSS_CLASS) .data(nestEntries(), function (d) { return _chart.keyAccessor()(d); }); var itemGroup = groups .enter() .append('div') .attr('class', GRID_CSS_CLASS); if (_htmlGroup) { itemGroup .html(function (d) { return _htmlGroup(d); }); } groups.exit().remove(); return itemGroup; } function nestEntries() { var entries = _chart.dimension().top(_size); return d3.nest() .key(_chart.group()) .sortKeys(_order) .entries(entries.sort(function (a, b) { return _order(_sortBy(a), _sortBy(b)); })); } function renderItems(groups) { var items = groups.order() .selectAll('div.' + ITEM_CSS_CLASS) .data(function (d) { return d.values; }); items.enter() .append('div') .attr('class', ITEM_CSS_CLASS) .html(function (d) { return _html(d); }); items.exit().remove(); return items; } _chart._doRedraw = function () { return _chart._doRender(); }; /** #### .size([size]) Get or set the grid size which determines the number of items displayed by the widget. **/ _chart.size = function (s) { if (!arguments.length) { return _size; } _size = s; return _chart; }; /** #### .html( function (data) { return '<html>'; }) Get or set the function that formats an item. The data grid widget uses a function to generate dynamic html. Use your favourite templating engine or generate the string directly. ```js chart.html(function (d) { return '<div class='item '+data.exampleCategory+''>'+data.exampleString+'</div>';}); ``` **/ _chart.html = function (_) { if (!arguments.length) { return _html; } _html = _; return _chart; }; /** #### .htmlGroup( function (data) { return '<html>'; }) Get or set the function that formats a group label. ```js chart.htmlGroup (function (d) { return '<h2>'.d.key . 'with ' . d.values.length .' items</h2>'}); ``` **/ _chart.htmlGroup = function (_) { if (!arguments.length) { return _htmlGroup; } _htmlGroup = _; return _chart; }; /** #### .sortBy([sortByFunction]) Get or set sort-by function. This function works as a value accessor at the item level and returns a particular field to be sorted. by. Default: identity function ```js chart.sortBy(function(d) { return d.date; }); ``` **/ _chart.sortBy = function (_) { if (!arguments.length) { return _sortBy; } _sortBy = _; return _chart; }; /** #### .order([order]) Get or set sort order function. Default value: ``` d3.ascending ``` ```js chart.order(d3.descending); ``` **/ _chart.order = function (_) { if (!arguments.length) { return _order; } _order = _; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** ## Bubble Chart Includes: [Bubble Mixin](#bubble-mixin), [Coordinate Grid Mixin](#coordinate-grid-mixin) A concrete implementation of a general purpose bubble chart that allows data visualization using the following dimensions: * x axis position * y axis position * bubble radius * color Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * [US Venture Capital Landscape 2011](http://dc-js.github.com/dc.js/vc/index.html) #### dc.bubbleChart(parent[, chartGroup]) Create a bubble chart instance and attach it to the given parent element. Parameters: * parent : string | node | selection | compositeChart - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created bubble chart instance ```js // create a bubble chart under #chart-container1 element using the default global chart group var bubbleChart1 = dc.bubbleChart('#chart-container1'); // create a bubble chart under #chart-container2 element using chart group A var bubbleChart2 = dc.bubbleChart('#chart-container2', 'chartGroupA'); ``` **/ dc.bubbleChart = function (parent, chartGroup) { var _chart = dc.bubbleMixin(dc.coordinateGridMixin({})); var _elasticRadius = false; _chart.transitionDuration(750); var bubbleLocator = function (d) { return 'translate(' + (bubbleX(d)) + ',' + (bubbleY(d)) + ')'; }; /** #### .elasticRadius([boolean]) Turn on or off the elastic bubble radius feature, or return the value of the flag. If this feature is turned on, then bubble radii will be automatically rescaled to fit the chart better. **/ _chart.elasticRadius = function (_) { if (!arguments.length) { return _elasticRadius; } _elasticRadius = _; return _chart; }; _chart.plotData = function () { if (_elasticRadius) { _chart.r().domain([_chart.rMin(), _chart.rMax()]); } _chart.r().range([_chart.MIN_RADIUS, _chart.xAxisLength() * _chart.maxBubbleRelativeSize()]); var bubbleG = _chart.chartBodyG().selectAll('g.' + _chart.BUBBLE_NODE_CLASS) .data(_chart.data(), function (d) { return d.key; }); renderNodes(bubbleG); updateNodes(bubbleG); removeNodes(bubbleG); _chart.fadeDeselectedArea(); }; function renderNodes(bubbleG) { var bubbleGEnter = bubbleG.enter().append('g'); bubbleGEnter .attr('class', _chart.BUBBLE_NODE_CLASS) .attr('transform', bubbleLocator) .append('circle').attr('class', function (d, i) { return _chart.BUBBLE_CLASS + ' _' + i; }) .on('click', _chart.onClick) .attr('fill', _chart.getColor) .attr('r', 0); dc.transition(bubbleG, _chart.transitionDuration()) .selectAll('circle.' + _chart.BUBBLE_CLASS) .attr('r', function (d) { return _chart.bubbleR(d); }) .attr('opacity', function (d) { return (_chart.bubbleR(d) > 0) ? 1 : 0; }); _chart._doRenderLabel(bubbleGEnter); _chart._doRenderTitles(bubbleGEnter); } function updateNodes(bubbleG) { dc.transition(bubbleG, _chart.transitionDuration()) .attr('transform', bubbleLocator) .selectAll('circle.' + _chart.BUBBLE_CLASS) .attr('fill', _chart.getColor) .attr('r', function (d) { return _chart.bubbleR(d); }) .attr('opacity', function (d) { return (_chart.bubbleR(d) > 0) ? 1 : 0; }); _chart.doUpdateLabels(bubbleG); _chart.doUpdateTitles(bubbleG); } function removeNodes(bubbleG) { bubbleG.exit().remove(); } function bubbleX(d) { var x = _chart.x()(_chart.keyAccessor()(d)); if (isNaN(x)) { x = 0; } return x; } function bubbleY(d) { var y = _chart.y()(_chart.valueAccessor()(d)); if (isNaN(y)) { y = 0; } return y; } _chart.renderBrush = function () { // override default x axis brush from parent chart }; _chart.redrawBrush = function () { // override default x axis brush from parent chart _chart.fadeDeselectedArea(); }; return _chart.anchor(parent, chartGroup); }; /** ## Composite Chart Includes: [Coordinate Grid Mixin](#coordinate-grid-mixin) Composite charts are a special kind of chart that render multiple charts on the same Coordinate Grid. You can overlay (compose) different bar/line/area charts in a single composite chart to achieve some quite flexible charting effects. #### dc.compositeChart(parent[, chartGroup]) Create a composite chart instance and attach it to the given parent element. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created composite chart instance ```js // create a composite chart under #chart-container1 element using the default global chart group var compositeChart1 = dc.compositeChart('#chart-container1'); // create a composite chart under #chart-container2 element using chart group A var compositeChart2 = dc.compositeChart('#chart-container2', 'chartGroupA'); ``` **/ dc.compositeChart = function (parent, chartGroup) { var SUB_CHART_CLASS = 'sub'; var DEFAULT_RIGHT_Y_AXIS_LABEL_PADDING = 12; var _chart = dc.coordinateGridMixin({}); var _children = []; var _childOptions = {}; var _shareColors = false, _shareTitle = true; var _rightYAxis = d3.svg.axis(), _rightYAxisLabel = 0, _rightYAxisLabelPadding = DEFAULT_RIGHT_Y_AXIS_LABEL_PADDING, _rightY, _rightAxisGridLines = false; _chart._mandatoryAttributes([]); _chart.transitionDuration(500); dc.override(_chart, '_generateG', function () { var g = this.__generateG(); for (var i = 0; i < _children.length; ++i) { var child = _children[i]; generateChildG(child, i); if (!child.dimension()) { child.dimension(_chart.dimension()); } if (!child.group()) { child.group(_chart.group()); } child.chartGroup(_chart.chartGroup()); child.svg(_chart.svg()); child.xUnits(_chart.xUnits()); child.transitionDuration(_chart.transitionDuration()); child.brushOn(_chart.brushOn()); child.renderTitle(_chart.renderTitle()); } return g; }); _chart._brushing = function () { var extent = _chart.extendBrush(); var brushIsEmpty = _chart.brushIsEmpty(extent); for (var i = 0; i < _children.length; ++i) { _children[i].filter(null); if (!brushIsEmpty) { _children[i].filter(extent); } } }; _chart._prepareYAxis = function () { if (leftYAxisChildren().length !== 0) { prepareLeftYAxis(); } if (rightYAxisChildren().length !== 0) { prepareRightYAxis(); } if (leftYAxisChildren().length > 0 && !_rightAxisGridLines) { _chart._renderHorizontalGridLinesForAxis(_chart.g(), _chart.y(), _chart.yAxis()); } else if (rightYAxisChildren().length > 0) { _chart._renderHorizontalGridLinesForAxis(_chart.g(), _rightY, _rightYAxis); } }; _chart.renderYAxis = function () { if (leftYAxisChildren().length !== 0) { _chart.renderYAxisAt('y', _chart.yAxis(), _chart.margins().left); _chart.renderYAxisLabel('y', _chart.yAxisLabel(), -90); } if (rightYAxisChildren().length !== 0) { _chart.renderYAxisAt('yr', _chart.rightYAxis(), _chart.width() - _chart.margins().right); _chart.renderYAxisLabel('yr', _chart.rightYAxisLabel(), 90, _chart.width() - _rightYAxisLabelPadding); } }; function prepareRightYAxis() { if (_chart.rightY() === undefined || _chart.elasticY()) { _chart.rightY(d3.scale.linear()); _chart.rightY().domain([rightYAxisMin(), rightYAxisMax()]).rangeRound([_chart.yAxisHeight(), 0]); } _chart.rightY().range([_chart.yAxisHeight(), 0]); _chart.rightYAxis(_chart.rightYAxis().scale(_chart.rightY())); _chart.rightYAxis().orient('right'); } function prepareLeftYAxis() { if (_chart.y() === undefined || _chart.elasticY()) { _chart.y(d3.scale.linear()); _chart.y().domain([yAxisMin(), yAxisMax()]).rangeRound([_chart.yAxisHeight(), 0]); } _chart.y().range([_chart.yAxisHeight(), 0]); _chart.yAxis(_chart.yAxis().scale(_chart.y())); _chart.yAxis().orient('left'); } function generateChildG(child, i) { child._generateG(_chart.g()); child.g().attr('class', SUB_CHART_CLASS + ' _' + i); } _chart.plotData = function () { for (var i = 0; i < _children.length; ++i) { var child = _children[i]; if (!child.g()) { generateChildG(child, i); } if (_shareColors) { child.colors(_chart.colors()); } child.x(_chart.x()); child.xAxis(_chart.xAxis()); if (child.useRightYAxis()) { child.y(_chart.rightY()); child.yAxis(_chart.rightYAxis()); } else { child.y(_chart.y()); child.yAxis(_chart.yAxis()); } child.plotData(); child._activateRenderlets(); } }; /** #### .useRightAxisGridLines(bool) Get or set whether to draw gridlines from the right y axis. Drawing from the left y axis is the default behavior. This option is only respected when subcharts with both left and right y-axes are present. **/ _chart.useRightAxisGridLines = function (_) { if (!arguments) { return _rightAxisGridLines; } _rightAxisGridLines = _; return _chart; }; /** #### .childOptions({object}) Get or set chart-specific options for all child charts. This is equivalent to calling `.options` on each child chart. **/ _chart.childOptions = function (_) { if (!arguments.length) { return _childOptions; } _childOptions = _; _children.forEach(function (child) { child.options(_childOptions); }); return _chart; }; _chart.fadeDeselectedArea = function () { for (var i = 0; i < _children.length; ++i) { var child = _children[i]; child.brush(_chart.brush()); child.fadeDeselectedArea(); } }; /** #### .rightYAxisLabel([labelText]) Set or get the right y axis label. **/ _chart.rightYAxisLabel = function (_, padding) { if (!arguments.length) { return _rightYAxisLabel; } _rightYAxisLabel = _; _chart.margins().right -= _rightYAxisLabelPadding; _rightYAxisLabelPadding = (padding === undefined) ? DEFAULT_RIGHT_Y_AXIS_LABEL_PADDING : padding; _chart.margins().right += _rightYAxisLabelPadding; return _chart; }; /** #### .compose(subChartArray) Combine the given charts into one single composite coordinate grid chart. ```js // compose the given charts in the array into one single composite chart moveChart.compose([ // when creating sub-chart you need to pass in the parent chart dc.lineChart(moveChart) .group(indexAvgByMonthGroup) // if group is missing then parent's group will be used .valueAccessor(function (d){return d.value.avg;}) // most of the normal functions will continue to work in a composed chart .renderArea(true) .stack(monthlyMoveGroup, function (d){return d.value;}) .title(function (d){ var value = d.value.avg?d.value.avg:d.value; if(isNaN(value)) value = 0; return dateFormat(d.key) + '\n' + numberFormat(value); }), dc.barChart(moveChart) .group(volumeByMonthGroup) .centerBar(true) ]); ``` **/ _chart.compose = function (charts) { _children = charts; _children.forEach(function (child) { child.height(_chart.height()); child.width(_chart.width()); child.margins(_chart.margins()); if (_shareTitle) { child.title(_chart.title()); } child.options(_childOptions); }); return _chart; }; /** #### .children() Returns the child charts which are composed into the composite chart. **/ _chart.children = function () { return _children; }; /** #### .shareColors([boolean]) Get or set color sharing for the chart. If set, the `.colors()` value from this chart will be shared with composed children. Additionally if the child chart implements Stackable and has not set a custom .colorAccessor, then it will generate a color specific to its order in the composition. **/ _chart.shareColors = function (_) { if (!arguments.length) { return _shareColors; } _shareColors = _; return _chart; }; /** #### .shareTitle([[boolean]) Get or set title sharing for the chart. If set, the `.title()` value from this chart will be shared with composed children. Default value is true. **/ _chart.shareTitle = function (_) { if (!arguments.length) { return _shareTitle; } _shareTitle = _; return _chart; }; /** #### .rightY([yScale]) Get or set the y scale for the right axis. The right y scale is typically automatically generated by the chart implementation. **/ _chart.rightY = function (_) { if (!arguments.length) { return _rightY; } _rightY = _; return _chart; }; function leftYAxisChildren() { return _children.filter(function (child) { return !child.useRightYAxis(); }); } function rightYAxisChildren() { return _children.filter(function (child) { return child.useRightYAxis(); }); } function getYAxisMin(charts) { return charts.map(function (c) { return c.yAxisMin(); }); } delete _chart.yAxisMin; function yAxisMin() { return d3.min(getYAxisMin(leftYAxisChildren())); } function rightYAxisMin() { return d3.min(getYAxisMin(rightYAxisChildren())); } function getYAxisMax(charts) { return charts.map(function (c) { return c.yAxisMax(); }); } delete _chart.yAxisMax; function yAxisMax() { return dc.utils.add(d3.max(getYAxisMax(leftYAxisChildren())), _chart.yAxisPadding()); } function rightYAxisMax() { return dc.utils.add(d3.max(getYAxisMax(rightYAxisChildren())), _chart.yAxisPadding()); } function getAllXAxisMinFromChildCharts() { return _children.map(function (c) { return c.xAxisMin(); }); } dc.override(_chart, 'xAxisMin', function () { return dc.utils.subtract(d3.min(getAllXAxisMinFromChildCharts()), _chart.xAxisPadding()); }); function getAllXAxisMaxFromChildCharts() { return _children.map(function (c) { return c.xAxisMax(); }); } dc.override(_chart, 'xAxisMax', function () { return dc.utils.add(d3.max(getAllXAxisMaxFromChildCharts()), _chart.xAxisPadding()); }); _chart.legendables = function () { return _children.reduce(function (items, child) { if (_shareColors) { child.colors(_chart.colors()); } items.push.apply(items, child.legendables()); return items; }, []); }; _chart.legendHighlight = function (d) { for (var j = 0; j < _children.length; ++j) { var child = _children[j]; child.legendHighlight(d); } }; _chart.legendReset = function (d) { for (var j = 0; j < _children.length; ++j) { var child = _children[j]; child.legendReset(d); } }; _chart.legendToggle = function () { console.log('composite should not be getting legendToggle itself'); }; /** #### .rightYAxis([yAxis]) Set or get the right y axis used by the composite chart. This function is most useful when y axis customization is required. The y axis in dc.js is an instance of a [d3 axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-_axis) therefore it supports any valid d3 axis manipulation. **Caution**: The y axis is usually generated internally by dc; resetting it may cause unexpected results. ```jså // customize y axis tick format chart.rightYAxis().tickFormat(function (v) {return v + '%';}); // customize y axis tick values chart.rightYAxis().tickValues([0, 100, 200, 300]); ``` **/ _chart.rightYAxis = function (rightYAxis) { if (!arguments.length) { return _rightYAxis; } _rightYAxis = rightYAxis; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** ## Series Chart Includes: [Composite Chart](#composite chart) A series chart is a chart that shows multiple series of data overlaid on one chart, where the series is specified in the data. It is a specialization of Composite Chart and inherits all composite features other than recomposing the chart. #### dc.seriesChart(parent[, chartGroup]) Create a series chart instance and attach it to the given parent element. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created series chart instance ```js // create a series chart under #chart-container1 element using the default global chart group var seriesChart1 = dc.seriesChart("#chart-container1"); // create a series chart under #chart-container2 element using chart group A var seriesChart2 = dc.seriesChart("#chart-container2", "chartGroupA"); ``` **/ dc.seriesChart = function (parent, chartGroup) { var _chart = dc.compositeChart(parent, chartGroup); function keySort(a, b) { return d3.ascending(_chart.keyAccessor()(a), _chart.keyAccessor()(b)); } var _charts = {}; var _chartFunction = dc.lineChart; var _seriesAccessor; var _seriesSort = d3.ascending; var _valueSort = keySort; _chart._mandatoryAttributes().push('seriesAccessor', 'chart'); _chart.shareColors(true); _chart._preprocessData = function () { var keep = []; var childrenChanged; var nester = d3.nest().key(_seriesAccessor); if (_seriesSort) { nester.sortKeys(_seriesSort); } if (_valueSort) { nester.sortValues(_valueSort); } var nesting = nester.entries(_chart.data()); var children = nesting.map(function (sub, i) { var subChart = _charts[sub.key] || _chartFunction.call(_chart, _chart, chartGroup, sub.key, i); if (!_charts[sub.key]) { childrenChanged = true; } _charts[sub.key] = subChart; keep.push(sub.key); return subChart .dimension(_chart.dimension()) .group({all:d3.functor(sub.values)}, sub.key) .keyAccessor(_chart.keyAccessor()) .valueAccessor(_chart.valueAccessor()) .brushOn(_chart.brushOn()); }); // this works around the fact compositeChart doesn't really // have a removal interface Object.keys(_charts) .filter(function (c) {return keep.indexOf(c) === -1;}) .forEach(function (c) { clearChart(c); childrenChanged = true; }); _chart._compose(children); if (childrenChanged && _chart.legend()) { _chart.legend().render(); } }; function clearChart(c) { if (_charts[c].g()) { _charts[c].g().remove(); } delete _charts[c]; } function resetChildren() { Object.keys(_charts).map(clearChart); _charts = {}; } /** #### .chart([function]) Get or set the chart function, which generates the child charts. Default: dc.lineChart ``` // put interpolation on the line charts used for the series chart.chart(function(c) { return dc.lineChart(c).interpolate('basis'); }) // do a scatter series chart chart.chart(dc.scatterPlot) ``` **/ _chart.chart = function (_) { if (!arguments.length) { return _chartFunction; } _chartFunction = _; resetChildren(); return _chart; }; /** #### .seriesAccessor([accessor]) Get or set accessor function for the displayed series. Given a datum, this function should return the series that datum belongs to. **/ _chart.seriesAccessor = function (_) { if (!arguments.length) { return _seriesAccessor; } _seriesAccessor = _; resetChildren(); return _chart; }; /** #### .seriesSort([sortFunction]) Get or set a function to sort the list of series by, given series values. Example: ``` chart.seriesSort(d3.descending); ``` **/ _chart.seriesSort = function (_) { if (!arguments.length) { return _seriesSort; } _seriesSort = _; resetChildren(); return _chart; }; /** #### .valueSort([sortFunction]) Get or set a function to sort each series values by. By default this is the key accessor which, for example, will ensure a lineChart series connects its points in increasing key/x order, rather than haphazardly. **/ _chart.valueSort = function (_) { if (!arguments.length) { return _valueSort; } _valueSort = _; resetChildren(); return _chart; }; // make compose private _chart._compose = _chart.compose; delete _chart.compose; return _chart; }; /** ## Geo Choropleth Chart Includes: [Color Mixin](#color-mixin), [Base Mixin](#base-mixin) The geo choropleth chart is designed as an easy way to create a crossfilter driven choropleth map from GeoJson data. This chart implementation was inspired by [the great d3 choropleth example](http://bl.ocks.org/4060606). Examples: * [US Venture Capital Landscape 2011](http://dc-js.github.com/dc.js/vc/index.html) #### dc.geoChoroplethChart(parent[, chartGroup]) Create a choropleth chart instance and attach it to the given parent element. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created choropleth chart instance ```js // create a choropleth chart under '#us-chart' element using the default global chart group var chart1 = dc.geoChoroplethChart('#us-chart'); // create a choropleth chart under '#us-chart2' element using chart group A var chart2 = dc.compositeChart('#us-chart2', 'chartGroupA'); ``` **/ dc.geoChoroplethChart = function (parent, chartGroup) { var _chart = dc.colorMixin(dc.baseMixin({})); _chart.colorAccessor(function (d) { return d || 0; }); var _geoPath = d3.geo.path(); var _projectionFlag; var _geoJsons = []; _chart._doRender = function () { _chart.resetSvg(); for (var layerIndex = 0; layerIndex < _geoJsons.length; ++layerIndex) { var states = _chart.svg().append('g') .attr('class', 'layer' + layerIndex); var regionG = states.selectAll('g.' + geoJson(layerIndex).name) .data(geoJson(layerIndex).data) .enter() .append('g') .attr('class', geoJson(layerIndex).name); regionG .append('path') .attr('fill', 'white') .attr('d', _geoPath); regionG.append('title'); plotData(layerIndex); } _projectionFlag = false; }; function plotData(layerIndex) { var data = generateLayeredData(); if (isDataLayer(layerIndex)) { var regionG = renderRegionG(layerIndex); renderPaths(regionG, layerIndex, data); renderTitle(regionG, layerIndex, data); } } function generateLayeredData() { var data = {}; var groupAll = _chart.data(); for (var i = 0; i < groupAll.length; ++i) { data[_chart.keyAccessor()(groupAll[i])] = _chart.valueAccessor()(groupAll[i]); } return data; } function isDataLayer(layerIndex) { return geoJson(layerIndex).keyAccessor; } function renderRegionG(layerIndex) { var regionG = _chart.svg() .selectAll(layerSelector(layerIndex)) .classed('selected', function (d) { return isSelected(layerIndex, d); }) .classed('deselected', function (d) { return isDeselected(layerIndex, d); }) .attr('class', function (d) { var layerNameClass = geoJson(layerIndex).name; var regionClass = dc.utils.nameToId(geoJson(layerIndex).keyAccessor(d)); var baseClasses = layerNameClass + ' ' + regionClass; if (isSelected(layerIndex, d)) { baseClasses += ' selected'; } if (isDeselected(layerIndex, d)) { baseClasses += ' deselected'; } return baseClasses; }); return regionG; } function layerSelector(layerIndex) { return 'g.layer' + layerIndex + ' g.' + geoJson(layerIndex).name; } function isSelected(layerIndex, d) { return _chart.hasFilter() && _chart.hasFilter(getKey(layerIndex, d)); } function isDeselected(layerIndex, d) { return _chart.hasFilter() && !_chart.hasFilter(getKey(layerIndex, d)); } function getKey(layerIndex, d) { return geoJson(layerIndex).keyAccessor(d); } function geoJson(index) { return _geoJsons[index]; } function renderPaths(regionG, layerIndex, data) { var paths = regionG .select('path') .attr('fill', function () { var currentFill = d3.select(this).attr('fill'); if (currentFill) { return currentFill; } return 'none'; }) .on('click', function (d) { return _chart.onClick(d, layerIndex); }); dc.transition(paths, _chart.transitionDuration()).attr('fill', function (d, i) { return _chart.getColor(data[geoJson(layerIndex).keyAccessor(d)], i); }); } _chart.onClick = function (d, layerIndex) { var selectedRegion = geoJson(layerIndex).keyAccessor(d); dc.events.trigger(function () { _chart.filter(selectedRegion); _chart.redrawGroup(); }); }; function renderTitle(regionG, layerIndex, data) { if (_chart.renderTitle()) { regionG.selectAll('title').text(function (d) { var key = getKey(layerIndex, d); var value = data[key]; return _chart.title()({key: key, value: value}); }); } } _chart._doRedraw = function () { for (var layerIndex = 0; layerIndex < _geoJsons.length; ++layerIndex) { plotData(layerIndex); if (_projectionFlag) { _chart.svg().selectAll('g.' + geoJson(layerIndex).name + ' path').attr('d', _geoPath); } } _projectionFlag = false; }; /** #### .overlayGeoJson(json, name, keyAccessor) - **mandatory** Use this function to insert a new GeoJson map layer. This function can be invoked multiple times if you have multiple GeoJson data layers to render on top of each other. If you overlay multiple layers with the same name the new overlay will override the existing one. Parameters: * json - GeoJson feed * name - name of the layer * keyAccessor - accessor function used to extract 'key' from the GeoJson data. The key extracted by this function should match the keys returned by the crossfilter groups. ```js // insert a layer for rendering US states chart.overlayGeoJson(statesJson.features, 'state', function(d) { return d.properties.name; }); ``` **/ _chart.overlayGeoJson = function (json, name, keyAccessor) { for (var i = 0; i < _geoJsons.length; ++i) { if (_geoJsons[i].name === name) { _geoJsons[i].data = json; _geoJsons[i].keyAccessor = keyAccessor; return _chart; } } _geoJsons.push({name: name, data: json, keyAccessor: keyAccessor}); return _chart; }; /** #### .projection(projection) Set custom geo projection function. See the available [d3 geo projection functions](https://github.com/mbostock/d3/wiki/Geo-Projections). Default value: albersUsa. **/ _chart.projection = function (projection) { _geoPath.projection(projection); _projectionFlag = true; return _chart; }; /** #### .geoJsons() Returns all GeoJson layers currently registered with this chart. The returned array is a reference to this chart's internal data structure, so any modification to this array will also modify this chart's internal registration. Returns an array of objects containing fields {name, data, accessor} **/ _chart.geoJsons = function () { return _geoJsons; }; /** #### .geoPath() Returns the [d3.geo.path](https://github.com/mbostock/d3/wiki/Geo-Paths#path) object used to render the projection and features. Can be useful for figuring out the bounding box of the feature set and thus a way to calculate scale and translation for the projection. **/ _chart.geoPath = function () { return _geoPath; }; /** #### .removeGeoJson(name) Remove a GeoJson layer from this chart by name **/ _chart.removeGeoJson = function (name) { var geoJsons = []; for (var i = 0; i < _geoJsons.length; ++i) { var layer = _geoJsons[i]; if (layer.name !== name) { geoJsons.push(layer); } } _geoJsons = geoJsons; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** ## Bubble Overlay Chart Includes: [Bubble Mixin](#bubble-mixin), [Base Mixin](#base-mixin) The bubble overlay chart is quite different from the typical bubble chart. With the bubble overlay chart you can arbitrarily place bubbles on an existing svg or bitmap image, thus changing the typical x and y positioning while retaining the capability to visualize data using bubble radius and coloring. Examples: * [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) #### dc.bubbleOverlay(parent[, chartGroup]) Create a bubble overlay chart instance and attach it to the given parent element. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. off-screen. Typically this element should also be the parent of the underlying image. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created bubble overlay chart instance ```js // create a bubble overlay chart on top of the '#chart-container1 svg' element using the default global chart group var bubbleChart1 = dc.bubbleOverlayChart('#chart-container1').svg(d3.select('#chart-container1 svg')); // create a bubble overlay chart on top of the '#chart-container2 svg' element using chart group A var bubbleChart2 = dc.compositeChart('#chart-container2', 'chartGroupA').svg(d3.select('#chart-container2 svg')); ``` #### .svg(imageElement) - **mandatory** Set the underlying svg image element. Unlike other dc charts this chart will not generate a svg element; therefore the bubble overlay chart will not work if this function is not invoked. If the underlying image is a bitmap, then an empty svg will need to be created on top of the image. ```js // set up underlying svg element chart.svg(d3.select('#chart svg')); ``` **/ dc.bubbleOverlay = function (root, chartGroup) { var BUBBLE_OVERLAY_CLASS = 'bubble-overlay'; var BUBBLE_NODE_CLASS = 'node'; var BUBBLE_CLASS = 'bubble'; var _chart = dc.bubbleMixin(dc.baseMixin({})); var _g; var _points = []; _chart.transitionDuration(750); _chart.radiusValueAccessor(function (d) { return d.value; }); /** #### .point(name, x, y) - **mandatory** Set up a data point on the overlay. The name of a data point should match a specific 'key' among data groups generated using keyAccessor. If a match is found (point name <-> data group key) then a bubble will be generated at the position specified by the function. x and y value specified here are relative to the underlying svg. **/ _chart.point = function (name, x, y) { _points.push({name: name, x: x, y: y}); return _chart; }; _chart._doRender = function () { _g = initOverlayG(); _chart.r().range([_chart.MIN_RADIUS, _chart.width() * _chart.maxBubbleRelativeSize()]); initializeBubbles(); _chart.fadeDeselectedArea(); return _chart; }; function initOverlayG() { _g = _chart.select('g.' + BUBBLE_OVERLAY_CLASS); if (_g.empty()) { _g = _chart.svg().append('g').attr('class', BUBBLE_OVERLAY_CLASS); } return _g; } function initializeBubbles() { var data = mapData(); _points.forEach(function (point) { var nodeG = getNodeG(point, data); var circle = nodeG.select('circle.' + BUBBLE_CLASS); if (circle.empty()) { circle = nodeG.append('circle') .attr('class', BUBBLE_CLASS) .attr('r', 0) .attr('fill', _chart.getColor) .on('click', _chart.onClick); } dc.transition(circle, _chart.transitionDuration()) .attr('r', function (d) { return _chart.bubbleR(d); }); _chart._doRenderLabel(nodeG); _chart._doRenderTitles(nodeG); }); } function mapData() { var data = {}; _chart.data().forEach(function (datum) { data[_chart.keyAccessor()(datum)] = datum; }); return data; } function getNodeG(point, data) { var bubbleNodeClass = BUBBLE_NODE_CLASS + ' ' + dc.utils.nameToId(point.name); var nodeG = _g.select('g.' + dc.utils.nameToId(point.name)); if (nodeG.empty()) { nodeG = _g.append('g') .attr('class', bubbleNodeClass) .attr('transform', 'translate(' + point.x + ',' + point.y + ')'); } nodeG.datum(data[point.name]); return nodeG; } _chart._doRedraw = function () { updateBubbles(); _chart.fadeDeselectedArea(); return _chart; }; function updateBubbles() { var data = mapData(); _points.forEach(function (point) { var nodeG = getNodeG(point, data); var circle = nodeG.select('circle.' + BUBBLE_CLASS); dc.transition(circle, _chart.transitionDuration()) .attr('r', function (d) { return _chart.bubbleR(d); }) .attr('fill', _chart.getColor); _chart.doUpdateLabels(nodeG); _chart.doUpdateTitles(nodeG); }); } _chart.debug = function (flag) { if (flag) { var debugG = _chart.select('g.' + dc.constants.DEBUG_GROUP_CLASS); if (debugG.empty()) { debugG = _chart.svg() .append('g') .attr('class', dc.constants.DEBUG_GROUP_CLASS); } var debugText = debugG.append('text') .attr('x', 10) .attr('y', 20); debugG .append('rect') .attr('width', _chart.width()) .attr('height', _chart.height()) .on('mousemove', function () { var position = d3.mouse(debugG.node()); var msg = position[0] + ', ' + position[1]; debugText.text(msg); }); } else { _chart.selectAll('.debug').remove(); } return _chart; }; _chart.anchor(root, chartGroup); return _chart; }; /** ## Row Chart Includes: [Cap Mixin](#cap-mixin), [Margin Mixin](#margin-mixin), [Color Mixin](#color-mixin), [Base Mixin](#base-mixin) Concrete row chart implementation. #### dc.rowChart(parent[, chartGroup]) Create a row chart instance and attach it to the given parent element. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created row chart instance ```js // create a row chart under #chart-container1 element using the default global chart group var chart1 = dc.rowChart('#chart-container1'); // create a row chart under #chart-container2 element using chart group A var chart2 = dc.rowChart('#chart-container2', 'chartGroupA'); ``` **/ dc.rowChart = function (parent, chartGroup) { var _g; var _labelOffsetX = 10; var _labelOffsetY = 15; var _hasLabelOffsetY = false; var _dyOffset = '0.35em'; // this helps center labels https://github.com/mbostock/d3/wiki/SVG-Shapes#svg_text var _titleLabelOffsetX = 2; var _gap = 5; var _fixedBarHeight = false; var _rowCssClass = 'row'; var _titleRowCssClass = 'titlerow'; var _renderTitleLabel = false; var _chart = dc.capMixin(dc.marginMixin(dc.colorMixin(dc.baseMixin({})))); var _x; var _elasticX; var _xAxis = d3.svg.axis().orient('bottom'); var _rowData; _chart.rowsCap = _chart.cap; function calculateAxisScale() { if (!_x || _elasticX) { var extent = d3.extent(_rowData, _chart.cappedValueAccessor); if (extent[0] > 0) { extent[0] = 0; } _x = d3.scale.linear().domain(extent) .range([0, _chart.effectiveWidth()]); } _xAxis.scale(_x); } function drawAxis() { var axisG = _g.select('g.axis'); calculateAxisScale(); if (axisG.empty()) { axisG = _g.append('g').attr('class', 'axis') .attr('transform', 'translate(0, ' + _chart.effectiveHeight() + ')'); } dc.transition(axisG, _chart.transitionDuration()) .call(_xAxis); } _chart._doRender = function () { _chart.resetSvg(); _g = _chart.svg() .append('g') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); drawChart(); return _chart; }; _chart.title(function (d) { return _chart.cappedKeyAccessor(d) + ': ' + _chart.cappedValueAccessor(d); }); _chart.label(_chart.cappedKeyAccessor); /** #### .x([scale]) Gets or sets the x scale. The x scale can be any d3 [quantitive scale](https://github.com/mbostock/d3/wiki/Quantitative-Scales) **/ _chart.x = function (x) { if (!arguments.length) { return _x; } _x = x; return _chart; }; function drawGridLines() { _g.selectAll('g.tick') .select('line.grid-line') .remove(); _g.selectAll('g.tick') .append('line') .attr('class', 'grid-line') .attr('x1', 0) .attr('y1', 0) .attr('x2', 0) .attr('y2', function () { return -_chart.effectiveHeight(); }); } function drawChart() { _rowData = _chart.data(); drawAxis(); drawGridLines(); var rows = _g.selectAll('g.' + _rowCssClass) .data(_rowData); createElements(rows); removeElements(rows); updateElements(rows); } function createElements(rows) { var rowEnter = rows.enter() .append('g') .attr('class', function (d, i) { return _rowCssClass + ' _' + i; }); rowEnter.append('rect').attr('width', 0); createLabels(rowEnter); updateLabels(rows); } function removeElements(rows) { rows.exit().remove(); } function rootValue() { var root = _x(0); return (root === -Infinity || root !== root) ? _x(1) : root; } function updateElements(rows) { var n = _rowData.length; var height; if (!_fixedBarHeight) { height = (_chart.effectiveHeight() - (n + 1) * _gap) / n; } else { height = _fixedBarHeight; } // vertically align label in center unless they override the value via property setter if (!_hasLabelOffsetY) { _labelOffsetY = height / 2; } var rect = rows.attr('transform', function (d, i) { return 'translate(0,' + ((i + 1) * _gap + i * height) + ')'; }).select('rect') .attr('height', height) .attr('fill', _chart.getColor) .on('click', onClick) .classed('deselected', function (d) { return (_chart.hasFilter()) ? !isSelectedRow(d) : false; }) .classed('selected', function (d) { return (_chart.hasFilter()) ? isSelectedRow(d) : false; }); dc.transition(rect, _chart.transitionDuration()) .attr('width', function (d) { return Math.abs(rootValue() - _x(_chart.valueAccessor()(d))); }) .attr('transform', translateX); createTitles(rows); updateLabels(rows); } function createTitles(rows) { if (_chart.renderTitle()) { rows.selectAll('title').remove(); rows.append('title').text(_chart.title()); } } function createLabels(rowEnter) { if (_chart.renderLabel()) { rowEnter.append('text') .on('click', onClick); } if (_chart.renderTitleLabel()) { rowEnter.append('text') .attr('class', _titleRowCssClass) .on('click', onClick); } } function updateLabels(rows) { if (_chart.renderLabel()) { var lab = rows.select('text') .attr('x', _labelOffsetX) .attr('y', _labelOffsetY) .attr('dy', _dyOffset) .on('click', onClick) .attr('class', function (d, i) { return _rowCssClass + ' _' + i; }) .text(function (d) { return _chart.label()(d); }); dc.transition(lab, _chart.transitionDuration()) .attr('transform', translateX); } if (_chart.renderTitleLabel()) { var titlelab = rows.select('.' + _titleRowCssClass) .attr('x', _chart.effectiveWidth() - _titleLabelOffsetX) .attr('y', _labelOffsetY) .attr('text-anchor', 'end') .on('click', onClick) .attr('class', function (d, i) { return _titleRowCssClass + ' _' + i ; }) .text(function (d) { return _chart.title()(d); }); dc.transition(titlelab, _chart.transitionDuration()) .attr('transform', translateX); } } /** #### .renderTitleLabel(boolean) Turn on/off Title label rendering (values) using SVG style of text-anchor 'end' **/ _chart.renderTitleLabel = function (_) { if (!arguments.length) { return _renderTitleLabel; } _renderTitleLabel = _; return _chart; }; function onClick(d) { _chart.onClick(d); } function translateX(d) { var x = _x(_chart.cappedValueAccessor(d)), x0 = rootValue(), s = x > x0 ? x0 : x; return 'translate(' + s + ',0)'; } _chart._doRedraw = function () { drawChart(); return _chart; }; /** #### .xAxis() Get the x axis for the row chart instance. Note: not settable for row charts. See the [d3 axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-axis) documention for more information. ```js // customize x axis tick format chart.xAxis().tickFormat(function (v) {return v + '%';}); // customize x axis tick values chart.xAxis().tickValues([0, 100, 200, 300]); ``` **/ _chart.xAxis = function () { return _xAxis; }; /** #### .fixedBarHeight([height]) Get or set the fixed bar height. Default is [false] which will auto-scale bars. For example, if you want to fix the height for a specific number of bars (useful in TopN charts) you could fix height as follows (where count = total number of bars in your TopN and gap is your vertical gap space). ```js chart.fixedBarHeight( chartheight - (count + 1) * gap / count); ``` **/ _chart.fixedBarHeight = function (g) { if (!arguments.length) { return _fixedBarHeight; } _fixedBarHeight = g; return _chart; }; /** #### .gap([gap]) Get or set the vertical gap space between rows on a particular row chart instance. Default gap is 5px; **/ _chart.gap = function (g) { if (!arguments.length) { return _gap; } _gap = g; return _chart; }; /** #### .elasticX([boolean]) Get or set the elasticity on x axis. If this attribute is set to true, then the x axis will rescle to auto-fit the data range when filtered. **/ _chart.elasticX = function (_) { if (!arguments.length) { return _elasticX; } _elasticX = _; return _chart; }; /** #### .labelOffsetX([x]) Get or set the x offset (horizontal space to the top left corner of a row) for labels on a particular row chart. Default x offset is 10px; **/ _chart.labelOffsetX = function (o) { if (!arguments.length) { return _labelOffsetX; } _labelOffsetX = o; return _chart; }; /** #### .labelOffsetY([y]) Get or set the y offset (vertical space to the top left corner of a row) for labels on a particular row chart. Default y offset is 15px; **/ _chart.labelOffsetY = function (o) { if (!arguments.length) { return _labelOffsetY; } _labelOffsetY = o; _hasLabelOffsetY = true; return _chart; }; /** #### .titleLabelOffsetx([x]) Get of set the x offset (horizontal space between right edge of row and right edge or text. Default x offset is 2px; **/ _chart.titleLabelOffsetX = function (o) { if (!arguments.length) { return _titleLabelOffsetX; } _titleLabelOffsetX = o; return _chart; }; function isSelectedRow (d) { return _chart.hasFilter(_chart.cappedKeyAccessor(d)); } return _chart.anchor(parent, chartGroup); }; /** ## Legend Legend is a attachable widget that can be added to other dc charts to render horizontal legend labels. ```js chart.legend(dc.legend().x(400).y(10).itemHeight(13).gap(5)) ``` Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) **/ dc.legend = function () { var LABEL_GAP = 2; var _legend = {}, _parent, _x = 0, _y = 0, _itemHeight = 12, _gap = 5, _horizontal = false, _legendWidth = 560, _itemWidth = 70; var _g; _legend.parent = function (p) { if (!arguments.length) { return _parent; } _parent = p; return _legend; }; _legend.render = function () { _parent.svg().select('g.dc-legend').remove(); _g = _parent.svg().append('g') .attr('class', 'dc-legend') .attr('transform', 'translate(' + _x + ',' + _y + ')'); var legendables = _parent.legendables(); var itemEnter = _g.selectAll('g.dc-legend-item') .data(legendables) .enter() .append('g') .attr('class', 'dc-legend-item') .on('mouseover', function (d) { _parent.legendHighlight(d); }) .on('mouseout', function (d) { _parent.legendReset(d); }) .on('click', function (d) { d.chart.legendToggle(d); }); _g.selectAll('g.dc-legend-item') .classed('fadeout', function (d) { return d.chart.isLegendableHidden(d); }); if (legendables.some(dc.pluck('dashstyle'))) { itemEnter .append('line') .attr('x1', 0) .attr('y1', _itemHeight / 2) .attr('x2', _itemHeight) .attr('y2', _itemHeight / 2) .attr('stroke-width', 2) .attr('stroke-dasharray', dc.pluck('dashstyle')) .attr('stroke', dc.pluck('color')); } else { itemEnter .append('rect') .attr('width', _itemHeight) .attr('height', _itemHeight) .attr('fill', function (d) {return d ? d.color : 'blue';}); } itemEnter.append('text') .text(dc.pluck('name')) .attr('x', _itemHeight + LABEL_GAP) .attr('y', function () { return _itemHeight / 2 + (this.clientHeight ? this.clientHeight : 13) / 2 - 2; }); var _cumulativeLegendTextWidth = 0; var row = 0; itemEnter.attr('transform', function (d, i) { if (_horizontal) { var translateBy = 'translate(' + _cumulativeLegendTextWidth + ',' + row * legendItemHeight() + ')'; if ((_cumulativeLegendTextWidth + _itemWidth) >= _legendWidth) { ++row ; _cumulativeLegendTextWidth = 0 ; } else { _cumulativeLegendTextWidth += _itemWidth; } return translateBy; } else { return 'translate(0,' + i * legendItemHeight() + ')'; } }); }; function legendItemHeight() { return _gap + _itemHeight; } /** #### .x([value]) Set or get x coordinate for legend widget. Default: 0. **/ _legend.x = function (x) { if (!arguments.length) { return _x; } _x = x; return _legend; }; /** #### .y([value]) Set or get y coordinate for legend widget. Default: 0. **/ _legend.y = function (y) { if (!arguments.length) { return _y; } _y = y; return _legend; }; /** #### .gap([value]) Set or get gap between legend items. Default: 5. **/ _legend.gap = function (gap) { if (!arguments.length) { return _gap; } _gap = gap; return _legend; }; /** #### .itemHeight([value]) Set or get legend item height. Default: 12. **/ _legend.itemHeight = function (h) { if (!arguments.length) { return _itemHeight; } _itemHeight = h; return _legend; }; /** #### .horizontal([boolean]) Position legend horizontally instead of vertically **/ _legend.horizontal = function (_) { if (!arguments.length) { return _horizontal; } _horizontal = _; return _legend; }; /** #### .legendWidth([value]) Maximum width for horizontal legend. Default: 560. **/ _legend.legendWidth = function (_) { if (!arguments.length) { return _legendWidth; } _legendWidth = _; return _legend; }; /** #### .itemWidth([value]) legendItem width for horizontal legend. Default: 70. **/ _legend.itemWidth = function (_) { if (!arguments.length) { return _itemWidth; } _itemWidth = _; return _legend; }; return _legend; }; /** ## Scatter Plot Includes: [Coordinate Grid Mixin](#coordinate-grid-mixin) A scatter plot chart #### dc.scatterPlot(parent[, chartGroup]) Create a scatter plot instance and attach it to the given parent element. Parameters: * parent : string | node | selection | compositeChart - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. If the scatter plot is a sub-chart in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created scatter plot instance ```js // create a scatter plot under #chart-container1 element using the default global chart group var chart1 = dc.scatterPlot('#chart-container1'); // create a scatter plot under #chart-container2 element using chart group A var chart2 = dc.scatterPlot('#chart-container2', 'chartGroupA'); // create a sub-chart under a composite parent chart var chart3 = dc.scatterPlot(compositeChart); ``` **/ dc.scatterPlot = function (parent, chartGroup) { var _chart = dc.coordinateGridMixin({}); var _symbol = d3.svg.symbol(); var _existenceAccessor = function (d) { return d.value; }; var originalKeyAccessor = _chart.keyAccessor(); _chart.keyAccessor(function (d) { return originalKeyAccessor(d)[0]; }); _chart.valueAccessor(function (d) { return originalKeyAccessor(d)[1]; }); _chart.colorAccessor(function () { return _chart._groupName; }); var _locator = function (d) { return 'translate(' + _chart.x()(_chart.keyAccessor()(d)) + ',' + _chart.y()(_chart.valueAccessor()(d)) + ')'; }; var _symbolSize = 3; var _highlightedSize = 5; var _hiddenSize = 0; _symbol.size(function (d) { if (!_existenceAccessor(d)) { return _hiddenSize; } else if (this.filtered) { return Math.pow(_highlightedSize, 2); } else { return Math.pow(_symbolSize, 2); } }); dc.override(_chart, '_filter', function (filter) { if (!arguments.length) { return _chart.__filter(); } return _chart.__filter(dc.filters.RangedTwoDimensionalFilter(filter)); }); _chart.plotData = function () { var symbols = _chart.chartBodyG().selectAll('path.symbol') .data(_chart.data()); symbols .enter() .append('path') .attr('class', 'symbol') .attr('opacity', 0) .attr('fill', _chart.getColor) .attr('transform', _locator); dc.transition(symbols, _chart.transitionDuration()) .attr('opacity', function (d) { return _existenceAccessor(d) ? 1 : 0; }) .attr('fill', _chart.getColor) .attr('transform', _locator) .attr('d', _symbol); dc.transition(symbols.exit(), _chart.transitionDuration()) .attr('opacity', 0).remove(); }; /** #### .existenceAccessor([accessor]) Get or set the existence accessor. If a point exists, it is drawn with symbolSize radius and opacity 1; if it does not exist, it is drawn with hiddenSize radius and opacity 0. By default, the existence accessor checks if the reduced value is truthy. **/ _chart.existenceAccessor = function (acc) { if (!arguments.length) { return _existenceAccessor; } _existenceAccessor = acc; return this; }; /** #### .symbol([type]) Get or set the symbol type used for each point. By default the symbol is a circle. See the D3 [docs](https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-symbol_type) for acceptable types. Type can be a constant or an accessor. **/ _chart.symbol = function (type) { if (!arguments.length) { return _symbol.type(); } _symbol.type(type); return _chart; }; /** #### .symbolSize([radius]) Set or get radius for symbols. Default: 3. **/ _chart.symbolSize = function (s) { if (!arguments.length) { return _symbolSize; } _symbolSize = s; return _chart; }; /** #### .highlightedSize([radius]) Set or get radius for highlighted symbols. Default: 4. **/ _chart.highlightedSize = function (s) { if (!arguments.length) { return _highlightedSize; } _highlightedSize = s; return _chart; }; /** #### .hiddenSize([radius]) Set or get radius for symbols when the group is empty. Default: 0. **/ _chart.hiddenSize = function (s) { if (!arguments.length) { return _hiddenSize; } _hiddenSize = s; return _chart; }; _chart.legendables = function () { return [{chart: _chart, name: _chart._groupName, color: _chart.getColor()}]; }; _chart.legendHighlight = function (d) { resizeSymbolsWhere(function (symbol) { return symbol.attr('fill') === d.color; }, _highlightedSize); _chart.selectAll('.chart-body path.symbol').filter(function () { return d3.select(this).attr('fill') !== d.color; }).classed('fadeout', true); }; _chart.legendReset = function (d) { resizeSymbolsWhere(function (symbol) { return symbol.attr('fill') === d.color; }, _symbolSize); _chart.selectAll('.chart-body path.symbol').filter(function () { return d3.select(this).attr('fill') !== d.color; }).classed('fadeout', false); }; function resizeSymbolsWhere(condition, size) { var symbols = _chart.selectAll('.chart-body path.symbol').filter(function () { return condition(d3.select(this)); }); var oldSize = _symbol.size(); _symbol.size(Math.pow(size, 2)); dc.transition(symbols, _chart.transitionDuration()).attr('d', _symbol); _symbol.size(oldSize); } _chart.setHandlePaths = function () { // no handle paths for poly-brushes }; _chart.extendBrush = function () { var extent = _chart.brush().extent(); if (_chart.round()) { extent[0] = extent[0].map(_chart.round()); extent[1] = extent[1].map(_chart.round()); _chart.g().select('.brush') .call(_chart.brush().extent(extent)); } return extent; }; _chart.brushIsEmpty = function (extent) { return _chart.brush().empty() || !extent || extent[0][0] >= extent[1][0] || extent[0][1] >= extent[1][1]; }; function resizeFiltered(filter) { var symbols = _chart.selectAll('.chart-body path.symbol').each(function (d) { this.filtered = filter && filter.isFiltered(d.key); }); dc.transition(symbols, _chart.transitionDuration()).attr('d', _symbol); } _chart._brushing = function () { var extent = _chart.extendBrush(); _chart.redrawBrush(_chart.g()); if (_chart.brushIsEmpty(extent)) { dc.events.trigger(function () { _chart.filter(null); _chart.redrawGroup(); }); resizeFiltered(false); } else { var ranged2DFilter = dc.filters.RangedTwoDimensionalFilter(extent); dc.events.trigger(function () { _chart.filter(null); _chart.filter(ranged2DFilter); _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); resizeFiltered(ranged2DFilter); } }; _chart.setBrushY = function (gBrush) { gBrush.call(_chart.brush().y(_chart.y())); }; return _chart.anchor(parent, chartGroup); }; /** ## Number Display Widget Includes: [Base Mixin](#base-mixin) A display of a single numeric value. Examples: * [Test Example](http://dc-js.github.io/dc.js/examples/number.html) #### dc.numberDisplay(parent[, chartGroup]) Create a Number Display instance and attach it to the given parent element. Unlike other charts, you do not need to set a dimension. Instead a group object must be provided and a valueAccessor that returns a single value. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. The number display widget will only react to filter changes in the chart group. Returns: A newly created number display instance ```js // create a number display under #chart-container1 element using the default global chart group var display1 = dc.numberDisplay('#chart-container1'); ``` **/ dc.numberDisplay = function (parent, chartGroup) { var SPAN_CLASS = 'number-display'; var _formatNumber = d3.format('.2s'); var _chart = dc.baseMixin({}); var _html = {one:'', some:'', none:''}; // dimension not required _chart._mandatoryAttributes(['group']); /** #### .html([object]) Gets or sets an optional object specifying HTML templates to use depending on the number displayed. The text `%number` will be replaced with the current value. - one: HTML template to use if the number is 1 - zero: HTML template to use if the number is 0 - some: HTML template to use otherwise ```js numberWidget.html({ one:'%number record', some:'%number records', none:'no records'}) ``` **/ _chart.html = function (s) { if (!arguments.length) { return _html; } if (s.none) { _html.none = s.none;//if none available } else if (s.one) { _html.none = s.one;//if none not available use one } else if (s.some) { _html.none = s.some;//if none and one not available use some } if (s.one) { _html.one = s.one;//if one available } else if (s.some) { _html.one = s.some;//if one not available use some } if (s.some) { _html.some = s.some;//if some available } else if (s.one) { _html.some = s.one;//if some not available use one } return _chart; }; /** #### .value() Calculate and return the underlying value of the display **/ _chart.value = function () { return _chart.data(); }; _chart.data(function (group) { var valObj = group.value ? group.value() : group.top(1)[0]; return _chart.valueAccessor()(valObj); }); _chart.transitionDuration(250); // good default _chart._doRender = function () { var newValue = _chart.value(), span = _chart.selectAll('.' + SPAN_CLASS); if (span.empty()) { span = span.data([0]) .enter() .append('span') .attr('class', SPAN_CLASS); } span.transition() .duration(_chart.transitionDuration()) .ease('quad-out-in') .tween('text', function () { var interp = d3.interpolateNumber(this.lastValue || 0, newValue); this.lastValue = newValue; return function (t) { var html = null, num = _chart.formatNumber()(interp(t)); if (newValue === 0 && (_html.none !== '')) { html = _html.none; } else if (newValue === 1 && (_html.one !== '')) { html = _html.one; } else if (_html.some !== '') { html = _html.some; } this.innerHTML = html ? html.replace('%number', num) : num; }; }); }; _chart._doRedraw = function () { return _chart._doRender(); }; /** #### .formatNumber([formatter]) Get or set a function to format the value for the display. By default `d3.format('.2s');` is used. **/ _chart.formatNumber = function (_) { if (!arguments.length) { return _formatNumber; } _formatNumber = _; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** ## Heat Map Includes: [Color Mixin](#color-mixin), [Margin Mixin](#margin-mixin), [Base Mixin](#base-mixin) A heat map is matrix that represents the values of two dimensions of data using colors. #### dc.heatMap(parent[, chartGroup]) Create a heat map instance and attach it to the given parent element. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created heat map instance ```js // create a heat map under #chart-container1 element using the default global chart group var heatMap1 = dc.heatMap('#chart-container1'); // create a heat map under #chart-container2 element using chart group A var heatMap2 = dc.heatMap('#chart-container2', 'chartGroupA'); ``` **/ dc.heatMap = function (parent, chartGroup) { var DEFAULT_BORDER_RADIUS = 6.75; var _chartBody; var _cols; var _rows; var _xBorderRadius = DEFAULT_BORDER_RADIUS; var _yBorderRadius = DEFAULT_BORDER_RADIUS; var _chart = dc.colorMixin(dc.marginMixin(dc.baseMixin({}))); _chart._mandatoryAttributes(['group']); _chart.title(_chart.colorAccessor()); var _xAxisOnClick = function (d) { filterAxis(0, d); }; var _yAxisOnClick = function (d) { filterAxis(1, d); }; var _boxOnClick = function (d) { var filter = d.key; dc.events.trigger(function () { _chart.filter(filter); _chart.redrawGroup(); }); }; function filterAxis(axis, value) { var cellsOnAxis = _chart.selectAll('.box-group').filter(function (d) { return d.key[axis] === value; }); var unfilteredCellsOnAxis = cellsOnAxis.filter(function (d) { return !_chart.hasFilter(d.key); }); dc.events.trigger(function () { if (unfilteredCellsOnAxis.empty()) { cellsOnAxis.each(function (d) { _chart.filter(d.key); }); } else { unfilteredCellsOnAxis.each(function (d) { _chart.filter(d.key); }); } _chart.redrawGroup(); }); } dc.override(_chart, 'filter', function (filter) { if (!arguments.length) { return _chart._filter(); } return _chart._filter(dc.filters.TwoDimensionalFilter(filter)); }); function uniq(d, i, a) { return !i || a[i - 1] !== d; } /** #### .rows([values]) Gets or sets the values used to create the rows of the heatmap, as an array. By default, all the values will be fetched from the data using the value accessor, and they will be sorted in ascending order. **/ _chart.rows = function (_) { if (arguments.length) { _rows = _; return _chart; } if (_rows) { return _rows; } var rowValues = _chart.data().map(_chart.valueAccessor()); rowValues.sort(d3.ascending); return d3.scale.ordinal().domain(rowValues.filter(uniq)); }; /** #### .cols([keys]) Gets or sets the keys used to create the columns of the heatmap, as an array. By default, all the values will be fetched from the data using the key accessor, and they will be sorted in ascending order. **/ _chart.cols = function (_) { if (arguments.length) { _cols = _; return _chart; } if (_cols) { return _cols; } var colValues = _chart.data().map(_chart.keyAccessor()); colValues.sort(d3.ascending); return d3.scale.ordinal().domain(colValues.filter(uniq)); }; _chart._doRender = function () { _chart.resetSvg(); _chartBody = _chart.svg() .append('g') .attr('class', 'heatmap') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); return _chart._doRedraw(); }; _chart._doRedraw = function () { var rows = _chart.rows(), cols = _chart.cols(), rowCount = rows.domain().length, colCount = cols.domain().length, boxWidth = Math.floor(_chart.effectiveWidth() / colCount), boxHeight = Math.floor(_chart.effectiveHeight() / rowCount); cols.rangeRoundBands([0, _chart.effectiveWidth()]); rows.rangeRoundBands([_chart.effectiveHeight(), 0]); var boxes = _chartBody.selectAll('g.box-group').data(_chart.data(), function (d, i) { return _chart.keyAccessor()(d, i) + '\0' + _chart.valueAccessor()(d, i); }); var gEnter = boxes.enter().append('g') .attr('class', 'box-group'); gEnter.append('rect') .attr('class', 'heat-box') .attr('fill', 'white') .on('click', _chart.boxOnClick()); if (_chart.renderTitle()) { gEnter.append('title') .text(_chart.title()); } dc.transition(boxes.selectAll('rect'), _chart.transitionDuration()) .attr('x', function (d, i) { return cols(_chart.keyAccessor()(d, i)); }) .attr('y', function (d, i) { return rows(_chart.valueAccessor()(d, i)); }) .attr('rx', _xBorderRadius) .attr('ry', _yBorderRadius) .attr('fill', _chart.getColor) .attr('width', boxWidth) .attr('height', boxHeight); boxes.exit().remove(); var gCols = _chartBody.selectAll('g.cols'); if (gCols.empty()) { gCols = _chartBody.append('g').attr('class', 'cols axis'); } var gColsText = gCols.selectAll('text').data(cols.domain()); gColsText.enter().append('text') .attr('x', function (d) { return cols(d) + boxWidth / 2; }) .style('text-anchor', 'middle') .attr('y', _chart.effectiveHeight()) .attr('dy', 12) .on('click', _chart.xAxisOnClick()) .text(function (d) { return d; }); dc.transition(gColsText, _chart.transitionDuration()) .text(function (d) { return d; }) .attr('x', function (d) { return cols(d) + boxWidth / 2; }); gColsText.exit().remove(); var gRows = _chartBody.selectAll('g.rows'); if (gRows.empty()) { gRows = _chartBody.append('g').attr('class', 'rows axis'); } var gRowsText = gRows.selectAll('text').data(rows.domain()); gRowsText.enter().append('text') .attr('dy', 6) .style('text-anchor', 'end') .attr('x', 0) .attr('dx', -2) .on('click', _chart.yAxisOnClick()) .text(function (d) { return d; }); dc.transition(gRowsText, _chart.transitionDuration()) .text(function (d) { return d; }) .attr('y', function (d) { return rows(d) + boxHeight / 2; }); gRowsText.exit().remove(); if (_chart.hasFilter()) { _chart.selectAll('g.box-group').each(function (d) { if (_chart.isSelectedNode(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.selectAll('g.box-group').each(function () { _chart.resetHighlight(this); }); } return _chart; }; /** #### .boxOnClick([handler]) Gets or sets the handler that fires when an individual cell is clicked in the heatmap. By default, filtering of the cell will be toggled. **/ _chart.boxOnClick = function (f) { if (!arguments.length) { return _boxOnClick; } _boxOnClick = f; return _chart; }; /** #### .xAxisOnClick([handler]) Gets or sets the handler that fires when a column tick is clicked in the x axis. By default, if any cells in the column are unselected, the whole column will be selected, otherwise the whole column will be unselected. **/ _chart.xAxisOnClick = function (f) { if (!arguments.length) { return _xAxisOnClick; } _xAxisOnClick = f; return _chart; }; /** #### .yAxisOnClick([handler]) Gets or sets the handler that fires when a row tick is clicked in the y axis. By default, if any cells in the row are unselected, the whole row will be selected, otherwise the whole row will be unselected. **/ _chart.yAxisOnClick = function (f) { if (!arguments.length) { return _yAxisOnClick; } _yAxisOnClick = f; return _chart; }; /** #### .xBorderRadius([value]) Gets or sets the X border radius. Set to 0 to get full rectangles. Default: 6.75 */ _chart.xBorderRadius = function (d) { if (!arguments.length) { return _xBorderRadius; } _xBorderRadius = d; return _chart; }; /** #### .xBorderRadius([value]) Gets or sets the Y border radius. Set to 0 to get full rectangles. Default: 6.75 */ _chart.yBorderRadius = function (d) { if (!arguments.length) { return _yBorderRadius; } _yBorderRadius = d; return _chart; }; _chart.isSelectedNode = function (d) { return _chart.hasFilter(d.key); }; return _chart.anchor(parent, chartGroup); }; // https://github.com/d3/d3-plugins/blob/master/box/box.js (function () { // Inspired by http://informationandvisualization.de/blog/box-plot d3.box = function () { var width = 1, height = 1, duration = 0, domain = null, value = Number, whiskers = boxWhiskers, quartiles = boxQuartiles, tickFormat = null; // For each small multiple… function box(g) { g.each(function (d, i) { d = d.map(value).sort(d3.ascending); var g = d3.select(this), n = d.length, min = d[0], max = d[n - 1]; // Compute quartiles. Must return exactly 3 elements. var quartileData = d.quartiles = quartiles(d); // Compute whiskers. Must return exactly 2 elements, or null. var whiskerIndices = whiskers && whiskers.call(this, d, i), whiskerData = whiskerIndices && whiskerIndices.map(function (i) { return d[i]; }); // Compute outliers. If no whiskers are specified, all data are 'outliers'. // We compute the outliers as indices, so that we can join across transitions! var outlierIndices = whiskerIndices ? d3.range(0, whiskerIndices[0]).concat(d3.range(whiskerIndices[1] + 1, n)) : d3.range(n); // Compute the new x-scale. var x1 = d3.scale.linear() .domain(domain && domain.call(this, d, i) || [min, max]) .range([height, 0]); // Retrieve the old x-scale, if this is an update. var x0 = this.__chart__ || d3.scale.linear() .domain([0, Infinity]) .range(x1.range()); // Stash the new scale. this.__chart__ = x1; // Note: the box, median, and box tick elements are fixed in number, // so we only have to handle enter and update. In contrast, the outliers // and other elements are variable, so we need to exit them! Variable // elements also fade in and out. // Update center line: the vertical line spanning the whiskers. var center = g.selectAll('line.center') .data(whiskerData ? [whiskerData] : []); center.enter().insert('line', 'rect') .attr('class', 'center') .attr('x1', width / 2) .attr('y1', function (d) { return x0(d[0]); }) .attr('x2', width / 2) .attr('y2', function (d) { return x0(d[1]); }) .style('opacity', 1e-6) .transition() .duration(duration) .style('opacity', 1) .attr('y1', function (d) { return x1(d[0]); }) .attr('y2', function (d) { return x1(d[1]); }); center.transition() .duration(duration) .style('opacity', 1) .attr('y1', function (d) { return x1(d[0]); }) .attr('y2', function (d) { return x1(d[1]); }); center.exit().transition() .duration(duration) .style('opacity', 1e-6) .attr('y1', function (d) { return x1(d[0]); }) .attr('y2', function (d) { return x1(d[1]); }) .remove(); // Update innerquartile box. var box = g.selectAll('rect.box') .data([quartileData]); box.enter().append('rect') .attr('class', 'box') .attr('x', 0) .attr('y', function (d) { return x0(d[2]); }) .attr('width', width) .attr('height', function (d) { return x0(d[0]) - x0(d[2]); }) .transition() .duration(duration) .attr('y', function (d) { return x1(d[2]); }) .attr('height', function (d) { return x1(d[0]) - x1(d[2]); }); box.transition() .duration(duration) .attr('y', function (d) { return x1(d[2]); }) .attr('height', function (d) { return x1(d[0]) - x1(d[2]); }); // Update median line. var medianLine = g.selectAll('line.median') .data([quartileData[1]]); medianLine.enter().append('line') .attr('class', 'median') .attr('x1', 0) .attr('y1', x0) .attr('x2', width) .attr('y2', x0) .transition() .duration(duration) .attr('y1', x1) .attr('y2', x1); medianLine.transition() .duration(duration) .attr('y1', x1) .attr('y2', x1); // Update whiskers. var whisker = g.selectAll('line.whisker') .data(whiskerData || []); whisker.enter().insert('line', 'circle, text') .attr('class', 'whisker') .attr('x1', 0) .attr('y1', x0) .attr('x2', width) .attr('y2', x0) .style('opacity', 1e-6) .transition() .duration(duration) .attr('y1', x1) .attr('y2', x1) .style('opacity', 1); whisker.transition() .duration(duration) .attr('y1', x1) .attr('y2', x1) .style('opacity', 1); whisker.exit().transition() .duration(duration) .attr('y1', x1) .attr('y2', x1) .style('opacity', 1e-6) .remove(); // Update outliers. var outlier = g.selectAll('circle.outlier') .data(outlierIndices, Number); outlier.enter().insert('circle', 'text') .attr('class', 'outlier') .attr('r', 5) .attr('cx', width / 2) .attr('cy', function (i) { return x0(d[i]); }) .style('opacity', 1e-6) .transition() .duration(duration) .attr('cy', function (i) { return x1(d[i]); }) .style('opacity', 1); outlier.transition() .duration(duration) .attr('cy', function (i) { return x1(d[i]); }) .style('opacity', 1); outlier.exit().transition() .duration(duration) .attr('cy', function (i) { return x1(d[i]); }) .style('opacity', 1e-6) .remove(); // Compute the tick format. var format = tickFormat || x1.tickFormat(8); // Update box ticks. var boxTick = g.selectAll('text.box') .data(quartileData); boxTick.enter().append('text') .attr('class', 'box') .attr('dy', '.3em') .attr('dx', function (d, i) { return i & 1 ? 6 : -6; }) .attr('x', function (d, i) { return i & 1 ? width : 0; }) .attr('y', x0) .attr('text-anchor', function (d, i) { return i & 1 ? 'start' : 'end'; }) .text(format) .transition() .duration(duration) .attr('y', x1); boxTick.transition() .duration(duration) .text(format) .attr('y', x1); // Update whisker ticks. These are handled separately from the box // ticks because they may or may not exist, and we want don't want // to join box ticks pre-transition with whisker ticks post-. var whiskerTick = g.selectAll('text.whisker') .data(whiskerData || []); whiskerTick.enter().append('text') .attr('class', 'whisker') .attr('dy', '.3em') .attr('dx', 6) .attr('x', width) .attr('y', x0) .text(format) .style('opacity', 1e-6) .transition() .duration(duration) .attr('y', x1) .style('opacity', 1); whiskerTick.transition() .duration(duration) .text(format) .attr('y', x1) .style('opacity', 1); whiskerTick.exit().transition() .duration(duration) .attr('y', x1) .style('opacity', 1e-6) .remove(); }); d3.timer.flush(); } box.width = function (x) { if (!arguments.length) { return width; } width = x; return box; }; box.height = function (x) { if (!arguments.length) { return height; } height = x; return box; }; box.tickFormat = function (x) { if (!arguments.length) { return tickFormat; } tickFormat = x; return box; }; box.duration = function (x) { if (!arguments.length) { return duration; } duration = x; return box; }; box.domain = function (x) { if (!arguments.length) { return domain; } domain = x === null ? x : d3.functor(x); return box; }; box.value = function (x) { if (!arguments.length) { return value; } value = x; return box; }; box.whiskers = function (x) { if (!arguments.length) { return whiskers; } whiskers = x; return box; }; box.quartiles = function (x) { if (!arguments.length) { return quartiles; } quartiles = x; return box; }; return box; }; function boxWhiskers(d) { return [0, d.length - 1]; } function boxQuartiles(d) { return [ d3.quantile(d, 0.25), d3.quantile(d, 0.5), d3.quantile(d, 0.75) ]; } })(); /** ## Box Plot Includes: [Coordinate Grid Mixin](#coordinate-grid-mixin) A box plot is a chart that depicts numerical data via their quartile ranges. #### dc.boxPlot(parent[, chartGroup]) Create a box plot instance and attach it to the given parent element. Parameters: * parent : string | node | selection - any valid [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) representing a dom block element such as a div; or a dom element or d3 selection. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Interaction with a chart will only trigger events and redraws within the chart's group. Returns: A newly created box plot instance ```js // create a box plot under #chart-container1 element using the default global chart group var boxPlot1 = dc.boxPlot('#chart-container1'); // create a box plot under #chart-container2 element using chart group A var boxPlot2 = dc.boxPlot('#chart-container2', 'chartGroupA'); ``` **/ dc.boxPlot = function (parent, chartGroup) { var _chart = dc.coordinateGridMixin({}); // Returns a function to compute the interquartile range. function DEFAULT_WHISKERS_IQR (k) { return function (d) { var q1 = d.quartiles[0], q3 = d.quartiles[2], iqr = (q3 - q1) * k, i = -1, j = d.length; /*jshint -W116*/ /*jshint -W035*/ while (d[++i] < q1 - iqr) {} while (d[--j] > q3 + iqr) {} /*jshint +W116*/ return [i, j]; /*jshint +W035*/ }; } var _whiskerIqrFactor = 1.5; var _whiskersIqr = DEFAULT_WHISKERS_IQR; var _whiskers = _whiskersIqr(_whiskerIqrFactor); var _box = d3.box(); var _tickFormat = null; var _boxWidth = function (innerChartWidth, xUnits) { if (_chart.isOrdinal()) { return _chart.x().rangeBand(); } else { return innerChartWidth / (1 + _chart.boxPadding()) / xUnits; } }; // default padding to handle min/max whisker text _chart.yAxisPadding(12); // default to ordinal _chart.x(d3.scale.ordinal()); _chart.xUnits(dc.units.ordinal); // valueAccessor should return an array of values that can be coerced into numbers // or if data is overloaded for a static array of arrays, it should be `Number`. // Empty arrays are not included. _chart.data(function (group) { return group.all().map(function (d) { d.map = function (accessor) { return accessor.call(d, d); }; return d; }).filter(function (d) { var values = _chart.valueAccessor()(d); return values.length !== 0; }); }); /** #### .boxPadding([padding]) Get or set the spacing between boxes as a fraction of box size. Valid values are within 0-1. See the [d3 docs](https://github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-ordinal_rangeBands) for a visual description of how the padding is applied. Default: 0.8 **/ _chart.boxPadding = _chart._rangeBandPadding; _chart.boxPadding(0.8); /** #### .outerPadding([padding]) Get or set the outer padding on an ordinal box chart. This setting has no effect on non-ordinal charts or on charts with a custom `.boxWidth`. Will pad the width by `padding * barWidth` on each side of the chart. Default: 0.5 **/ _chart.outerPadding = _chart._outerRangeBandPadding; _chart.outerPadding(0.5); /** #### .boxWidth(width || function(innerChartWidth, xUnits) { ... }) Get or set the numerical width of the boxplot box. The width may also be a function taking as parameters the chart width excluding the right and left margins, as well as the number of x units. **/ _chart.boxWidth = function (_) { if (!arguments.length) { return _boxWidth; } _boxWidth = d3.functor(_); return _chart; }; var boxTransform = function (d, i) { var xOffset = _chart.x()(_chart.keyAccessor()(d, i)); return 'translate(' + xOffset + ', 0)'; }; _chart._preprocessData = function () { if (_chart.elasticX()) { _chart.x().domain([]); } }; _chart.plotData = function () { var _calculatedBoxWidth = _boxWidth(_chart.effectiveWidth(), _chart.xUnitCount()); _box.whiskers(_whiskers) .width(_calculatedBoxWidth) .height(_chart.effectiveHeight()) .value(_chart.valueAccessor()) .domain(_chart.y().domain()) .duration(_chart.transitionDuration()) .tickFormat(_tickFormat); var boxesG = _chart.chartBodyG().selectAll('g.box').data(_chart.data(), function (d) { return d.key; }); renderBoxes(boxesG); updateBoxes(boxesG); removeBoxes(boxesG); _chart.fadeDeselectedArea(); }; function renderBoxes(boxesG) { var boxesGEnter = boxesG.enter().append('g'); boxesGEnter .attr('class', 'box') .attr('transform', boxTransform) .call(_box) .on('click', function (d) { _chart.filter(d.key); _chart.redrawGroup(); }); } function updateBoxes(boxesG) { dc.transition(boxesG, _chart.transitionDuration()) .attr('transform', boxTransform) .call(_box) .each(function () { d3.select(this).select('rect.box').attr('fill', _chart.getColor); }); } function removeBoxes(boxesG) { boxesG.exit().remove().call(_box); } _chart.fadeDeselectedArea = function () { if (_chart.hasFilter()) { _chart.g().selectAll('g.box').each(function (d) { if (_chart.isSelectedNode(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.g().selectAll('g.box').each(function () { _chart.resetHighlight(this); }); } }; _chart.isSelectedNode = function (d) { return _chart.hasFilter(d.key); }; _chart.yAxisMin = function () { var min = d3.min(_chart.data(), function (e) { return d3.min(_chart.valueAccessor()(e)); }); return dc.utils.subtract(min, _chart.yAxisPadding()); }; _chart.yAxisMax = function () { var max = d3.max(_chart.data(), function (e) { return d3.max(_chart.valueAccessor()(e)); }); return dc.utils.add(max, _chart.yAxisPadding()); }; /** #### .tickFormat() Set the numerical format of the boxplot median, whiskers and quartile labels. Defaults to integer formatting. ```js // format ticks to 2 decimal places chart.tickFormat(d3.format('.2f')); ``` **/ _chart.tickFormat = function (x) { if (!arguments.length) { return _tickFormat; } _tickFormat = x; return _chart; }; return _chart.anchor(parent, chartGroup); }; // Renamed functions dc.abstractBubbleChart = dc.bubbleMixin; dc.baseChart = dc.baseMixin; dc.capped = dc.capMixin; dc.colorChart = dc.colorMixin; dc.coordinateGridChart = dc.coordinateGridMixin; dc.marginable = dc.marginMixin; dc.stackableChart = dc.stackMixin; return dc;} if(typeof define === "function" && define.amd) { define(["d3", "crossfilter"], _dc); } else if(typeof module === "object" && module.exports) { // When using window global, window.crossfilter is a function // When using require, the value will be an object with 'crossfilter' // field, so we need to access it here. module.exports = _dc(require('d3'), require('crossfilter').crossfilter); } else { this.dc = _dc(d3, crossfilter); } } )();
ajax/libs/polymer/0.5.3/polymer.js
cloudrifles/cdnjs
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // @version 0.5.3 window.PolymerGestures = {}; (function(scope) { var hasFullPath = false; // test for full event path support var pathTest = document.createElement('meta'); if (pathTest.createShadowRoot) { var sr = pathTest.createShadowRoot(); var s = document.createElement('span'); sr.appendChild(s); pathTest.addEventListener('testpath', function(ev) { if (ev.path) { // if the span is in the event path, then path[0] is the real source for all events hasFullPath = ev.path[0] === s; } ev.stopPropagation(); }); var ev = new CustomEvent('testpath', {bubbles: true}); // must add node to DOM to trigger event listener document.head.appendChild(pathTest); s.dispatchEvent(ev); pathTest.parentNode.removeChild(pathTest); sr = s = null; } pathTest = null; var target = { shadow: function(inEl) { if (inEl) { return inEl.shadowRoot || inEl.webkitShadowRoot; } }, canTarget: function(shadow) { return shadow && Boolean(shadow.elementFromPoint); }, targetingShadow: function(inEl) { var s = this.shadow(inEl); if (this.canTarget(s)) { return s; } }, olderShadow: function(shadow) { var os = shadow.olderShadowRoot; if (!os) { var se = shadow.querySelector('shadow'); if (se) { os = se.olderShadowRoot; } } return os; }, allShadows: function(element) { var shadows = [], s = this.shadow(element); while(s) { shadows.push(s); s = this.olderShadow(s); } return shadows; }, searchRoot: function(inRoot, x, y) { var t, st, sr, os; if (inRoot) { t = inRoot.elementFromPoint(x, y); if (t) { // found element, check if it has a ShadowRoot sr = this.targetingShadow(t); } else if (inRoot !== document) { // check for sibling roots sr = this.olderShadow(inRoot); } // search other roots, fall back to light dom element return this.searchRoot(sr, x, y) || t; } }, owner: function(element) { if (!element) { return document; } var s = element; // walk up until you hit the shadow root or document while (s.parentNode) { s = s.parentNode; } // the owner element is expected to be a Document or ShadowRoot if (s.nodeType != Node.DOCUMENT_NODE && s.nodeType != Node.DOCUMENT_FRAGMENT_NODE) { s = document; } return s; }, findTarget: function(inEvent) { if (hasFullPath && inEvent.path && inEvent.path.length) { return inEvent.path[0]; } var x = inEvent.clientX, y = inEvent.clientY; // if the listener is in the shadow root, it is much faster to start there var s = this.owner(inEvent.target); // if x, y is not in this root, fall back to document search if (!s.elementFromPoint(x, y)) { s = document; } return this.searchRoot(s, x, y); }, findTouchAction: function(inEvent) { var n; if (hasFullPath && inEvent.path && inEvent.path.length) { var path = inEvent.path; for (var i = 0; i < path.length; i++) { n = path[i]; if (n.nodeType === Node.ELEMENT_NODE && n.hasAttribute('touch-action')) { return n.getAttribute('touch-action'); } } } else { n = inEvent.target; while(n) { if (n.nodeType === Node.ELEMENT_NODE && n.hasAttribute('touch-action')) { return n.getAttribute('touch-action'); } n = n.parentNode || n.host; } } // auto is default return "auto"; }, LCA: function(a, b) { if (a === b) { return a; } if (a && !b) { return a; } if (b && !a) { return b; } if (!b && !a) { return document; } // fast case, a is a direct descendant of b or vice versa if (a.contains && a.contains(b)) { return a; } if (b.contains && b.contains(a)) { return b; } var adepth = this.depth(a); var bdepth = this.depth(b); var d = adepth - bdepth; if (d >= 0) { a = this.walk(a, d); } else { b = this.walk(b, -d); } while (a && b && a !== b) { a = a.parentNode || a.host; b = b.parentNode || b.host; } return a; }, walk: function(n, u) { for (var i = 0; n && (i < u); i++) { n = n.parentNode || n.host; } return n; }, depth: function(n) { var d = 0; while(n) { d++; n = n.parentNode || n.host; } return d; }, deepContains: function(a, b) { var common = this.LCA(a, b); // if a is the common ancestor, it must "deeply" contain b return common === a; }, insideNode: function(node, x, y) { var rect = node.getBoundingClientRect(); return (rect.left <= x) && (x <= rect.right) && (rect.top <= y) && (y <= rect.bottom); }, path: function(event) { var p; if (hasFullPath && event.path && event.path.length) { p = event.path; } else { p = []; var n = this.findTarget(event); while (n) { p.push(n); n = n.parentNode || n.host; } } return p; } }; scope.targetFinding = target; /** * Given an event, finds the "deepest" node that could have been the original target before ShadowDOM retargetting * * @param {Event} Event An event object with clientX and clientY properties * @return {Element} The probable event origninator */ scope.findTarget = target.findTarget.bind(target); /** * Determines if the "container" node deeply contains the "containee" node, including situations where the "containee" is contained by one or more ShadowDOM * roots. * * @param {Node} container * @param {Node} containee * @return {Boolean} */ scope.deepContains = target.deepContains.bind(target); /** * Determines if the x/y position is inside the given node. * * Example: * * function upHandler(event) { * var innode = PolymerGestures.insideNode(event.target, event.clientX, event.clientY); * if (innode) { * // wait for tap? * } else { * // tap will never happen * } * } * * @param {Node} node * @param {Number} x Screen X position * @param {Number} y screen Y position * @return {Boolean} */ scope.insideNode = target.insideNode; })(window.PolymerGestures); (function() { function shadowSelector(v) { return 'html /deep/ ' + selector(v); } function selector(v) { return '[touch-action="' + v + '"]'; } function rule(v) { return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + ';}'; } var attrib2css = [ 'none', 'auto', 'pan-x', 'pan-y', { rule: 'pan-x pan-y', selectors: [ 'pan-x pan-y', 'pan-y pan-x' ] }, 'manipulation' ]; var styles = ''; // only install stylesheet if the browser has touch action support var hasTouchAction = typeof document.head.style.touchAction === 'string'; // only add shadow selectors if shadowdom is supported var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot; if (hasTouchAction) { attrib2css.forEach(function(r) { if (String(r) === r) { styles += selector(r) + rule(r) + '\n'; if (hasShadowRoot) { styles += shadowSelector(r) + rule(r) + '\n'; } } else { styles += r.selectors.map(selector) + rule(r.rule) + '\n'; if (hasShadowRoot) { styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n'; } } }); var el = document.createElement('style'); el.textContent = styles; document.head.appendChild(el); } })(); /** * This is the constructor for new PointerEvents. * * New Pointer Events must be given a type, and an optional dictionary of * initialization properties. * * Due to certain platform requirements, events returned from the constructor * identify as MouseEvents. * * @constructor * @param {String} inType The type of the event to create. * @param {Object} [inDict] An optional dictionary of initial event properties. * @return {Event} A new PointerEvent of type `inType` and initialized with properties from `inDict`. */ (function(scope) { var MOUSE_PROPS = [ 'bubbles', 'cancelable', 'view', 'detail', 'screenX', 'screenY', 'clientX', 'clientY', 'ctrlKey', 'altKey', 'shiftKey', 'metaKey', 'button', 'relatedTarget', 'pageX', 'pageY' ]; var MOUSE_DEFAULTS = [ false, false, null, null, 0, 0, 0, 0, false, false, false, false, 0, null, 0, 0 ]; var NOP_FACTORY = function(){ return function(){}; }; var eventFactory = { // TODO(dfreedm): this is overridden by tap recognizer, needs review preventTap: NOP_FACTORY, makeBaseEvent: function(inType, inDict) { var e = document.createEvent('Event'); e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false); e.preventTap = eventFactory.preventTap(e); return e; }, makeGestureEvent: function(inType, inDict) { inDict = inDict || Object.create(null); var e = this.makeBaseEvent(inType, inDict); for (var i = 0, keys = Object.keys(inDict), k; i < keys.length; i++) { k = keys[i]; e[k] = inDict[k]; } return e; }, makePointerEvent: function(inType, inDict) { inDict = inDict || Object.create(null); var e = this.makeBaseEvent(inType, inDict); // define inherited MouseEvent properties for(var i = 0, p; i < MOUSE_PROPS.length; i++) { p = MOUSE_PROPS[i]; e[p] = inDict[p] || MOUSE_DEFAULTS[i]; } e.buttons = inDict.buttons || 0; // Spec requires that pointers without pressure specified use 0.5 for down // state and 0 for up state. var pressure = 0; if (inDict.pressure) { pressure = inDict.pressure; } else { pressure = e.buttons ? 0.5 : 0; } // add x/y properties aliased to clientX/Y e.x = e.clientX; e.y = e.clientY; // define the properties of the PointerEvent interface e.pointerId = inDict.pointerId || 0; e.width = inDict.width || 0; e.height = inDict.height || 0; e.pressure = pressure; e.tiltX = inDict.tiltX || 0; e.tiltY = inDict.tiltY || 0; e.pointerType = inDict.pointerType || ''; e.hwTimestamp = inDict.hwTimestamp || 0; e.isPrimary = inDict.isPrimary || false; e._source = inDict._source || ''; return e; } }; scope.eventFactory = eventFactory; })(window.PolymerGestures); /** * This module implements an map of pointer states */ (function(scope) { var USE_MAP = window.Map && window.Map.prototype.forEach; var POINTERS_FN = function(){ return this.size; }; function PointerMap() { if (USE_MAP) { var m = new Map(); m.pointers = POINTERS_FN; return m; } else { this.keys = []; this.values = []; } } PointerMap.prototype = { set: function(inId, inEvent) { var i = this.keys.indexOf(inId); if (i > -1) { this.values[i] = inEvent; } else { this.keys.push(inId); this.values.push(inEvent); } }, has: function(inId) { return this.keys.indexOf(inId) > -1; }, 'delete': function(inId) { var i = this.keys.indexOf(inId); if (i > -1) { this.keys.splice(i, 1); this.values.splice(i, 1); } }, get: function(inId) { var i = this.keys.indexOf(inId); return this.values[i]; }, clear: function() { this.keys.length = 0; this.values.length = 0; }, // return value, key, map forEach: function(callback, thisArg) { this.values.forEach(function(v, i) { callback.call(thisArg, v, this.keys[i], this); }, this); }, pointers: function() { return this.keys.length; } }; scope.PointerMap = PointerMap; })(window.PolymerGestures); (function(scope) { var CLONE_PROPS = [ // MouseEvent 'bubbles', 'cancelable', 'view', 'detail', 'screenX', 'screenY', 'clientX', 'clientY', 'ctrlKey', 'altKey', 'shiftKey', 'metaKey', 'button', 'relatedTarget', // DOM Level 3 'buttons', // PointerEvent 'pointerId', 'width', 'height', 'pressure', 'tiltX', 'tiltY', 'pointerType', 'hwTimestamp', 'isPrimary', // event instance 'type', 'target', 'currentTarget', 'which', 'pageX', 'pageY', 'timeStamp', // gesture addons 'preventTap', 'tapPrevented', '_source' ]; var CLONE_DEFAULTS = [ // MouseEvent false, false, null, null, 0, 0, 0, 0, false, false, false, false, 0, null, // DOM Level 3 0, // PointerEvent 0, 0, 0, 0, 0, 0, '', 0, false, // event instance '', null, null, 0, 0, 0, 0, function(){}, false ]; var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined'); var eventFactory = scope.eventFactory; // set of recognizers to run for the currently handled event var currentGestures; /** * This module is for normalizing events. Mouse and Touch events will be * collected here, and fire PointerEvents that have the same semantics, no * matter the source. * Events fired: * - pointerdown: a pointing is added * - pointerup: a pointer is removed * - pointermove: a pointer is moved * - pointerover: a pointer crosses into an element * - pointerout: a pointer leaves an element * - pointercancel: a pointer will no longer generate events */ var dispatcher = { IS_IOS: false, pointermap: new scope.PointerMap(), requiredGestures: new scope.PointerMap(), eventMap: Object.create(null), // Scope objects for native events. // This exists for ease of testing. eventSources: Object.create(null), eventSourceList: [], gestures: [], // map gesture event -> {listeners: int, index: gestures[int]} dependencyMap: { // make sure down and up are in the map to trigger "register" down: {listeners: 0, index: -1}, up: {listeners: 0, index: -1} }, gestureQueue: [], /** * Add a new event source that will generate pointer events. * * `inSource` must contain an array of event names named `events`, and * functions with the names specified in the `events` array. * @param {string} name A name for the event source * @param {Object} source A new source of platform events. */ registerSource: function(name, source) { var s = source; var newEvents = s.events; if (newEvents) { newEvents.forEach(function(e) { if (s[e]) { this.eventMap[e] = s[e].bind(s); } }, this); this.eventSources[name] = s; this.eventSourceList.push(s); } }, registerGesture: function(name, source) { var obj = Object.create(null); obj.listeners = 0; obj.index = this.gestures.length; for (var i = 0, g; i < source.exposes.length; i++) { g = source.exposes[i].toLowerCase(); this.dependencyMap[g] = obj; } this.gestures.push(source); }, register: function(element, initial) { var l = this.eventSourceList.length; for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { // call eventsource register es.register.call(es, element, initial); } }, unregister: function(element) { var l = this.eventSourceList.length; for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { // call eventsource register es.unregister.call(es, element); } }, // EVENTS down: function(inEvent) { this.requiredGestures.set(inEvent.pointerId, currentGestures); this.fireEvent('down', inEvent); }, move: function(inEvent) { // pipe move events into gesture queue directly inEvent.type = 'move'; this.fillGestureQueue(inEvent); }, up: function(inEvent) { this.fireEvent('up', inEvent); this.requiredGestures.delete(inEvent.pointerId); }, cancel: function(inEvent) { inEvent.tapPrevented = true; this.fireEvent('up', inEvent); this.requiredGestures.delete(inEvent.pointerId); }, addGestureDependency: function(node, currentGestures) { var gesturesWanted = node._pgEvents; if (gesturesWanted && currentGestures) { var gk = Object.keys(gesturesWanted); for (var i = 0, r, ri, g; i < gk.length; i++) { // gesture g = gk[i]; if (gesturesWanted[g] > 0) { // lookup gesture recognizer r = this.dependencyMap[g]; // recognizer index ri = r ? r.index : -1; currentGestures[ri] = true; } } } }, // LISTENER LOGIC eventHandler: function(inEvent) { // This is used to prevent multiple dispatch of events from // platform events. This can happen when two elements in different scopes // are set up to create pointer events, which is relevant to Shadow DOM. var type = inEvent.type; // only generate the list of desired events on "down" if (type === 'touchstart' || type === 'mousedown' || type === 'pointerdown' || type === 'MSPointerDown') { if (!inEvent._handledByPG) { currentGestures = {}; } // in IOS mode, there is only a listener on the document, so this is not re-entrant if (this.IS_IOS) { var ev = inEvent; if (type === 'touchstart') { var ct = inEvent.changedTouches[0]; // set up a fake event to give to the path builder ev = {target: inEvent.target, clientX: ct.clientX, clientY: ct.clientY, path: inEvent.path}; } // use event path if available, otherwise build a path from target finding var nodes = inEvent.path || scope.targetFinding.path(ev); for (var i = 0, n; i < nodes.length; i++) { n = nodes[i]; this.addGestureDependency(n, currentGestures); } } else { this.addGestureDependency(inEvent.currentTarget, currentGestures); } } if (inEvent._handledByPG) { return; } var fn = this.eventMap && this.eventMap[type]; if (fn) { fn(inEvent); } inEvent._handledByPG = true; }, // set up event listeners listen: function(target, events) { for (var i = 0, l = events.length, e; (i < l) && (e = events[i]); i++) { this.addEvent(target, e); } }, // remove event listeners unlisten: function(target, events) { for (var i = 0, l = events.length, e; (i < l) && (e = events[i]); i++) { this.removeEvent(target, e); } }, addEvent: function(target, eventName) { target.addEventListener(eventName, this.boundHandler); }, removeEvent: function(target, eventName) { target.removeEventListener(eventName, this.boundHandler); }, // EVENT CREATION AND TRACKING /** * Creates a new Event of type `inType`, based on the information in * `inEvent`. * * @param {string} inType A string representing the type of event to create * @param {Event} inEvent A platform event with a target * @return {Event} A PointerEvent of type `inType` */ makeEvent: function(inType, inEvent) { var e = eventFactory.makePointerEvent(inType, inEvent); e.preventDefault = inEvent.preventDefault; e.tapPrevented = inEvent.tapPrevented; e._target = e._target || inEvent.target; return e; }, // make and dispatch an event in one call fireEvent: function(inType, inEvent) { var e = this.makeEvent(inType, inEvent); return this.dispatchEvent(e); }, /** * Returns a snapshot of inEvent, with writable properties. * * @param {Event} inEvent An event that contains properties to copy. * @return {Object} An object containing shallow copies of `inEvent`'s * properties. */ cloneEvent: function(inEvent) { var eventCopy = Object.create(null), p; for (var i = 0; i < CLONE_PROPS.length; i++) { p = CLONE_PROPS[i]; eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i]; // Work around SVGInstanceElement shadow tree // Return the <use> element that is represented by the instance for Safari, Chrome, IE. // This is the behavior implemented by Firefox. if (p === 'target' || p === 'relatedTarget') { if (HAS_SVG_INSTANCE && eventCopy[p] instanceof SVGElementInstance) { eventCopy[p] = eventCopy[p].correspondingUseElement; } } } // keep the semantics of preventDefault eventCopy.preventDefault = function() { inEvent.preventDefault(); }; return eventCopy; }, /** * Dispatches the event to its target. * * @param {Event} inEvent The event to be dispatched. * @return {Boolean} True if an event handler returns true, false otherwise. */ dispatchEvent: function(inEvent) { var t = inEvent._target; if (t) { t.dispatchEvent(inEvent); // clone the event for the gesture system to process // clone after dispatch to pick up gesture prevention code var clone = this.cloneEvent(inEvent); clone.target = t; this.fillGestureQueue(clone); } }, gestureTrigger: function() { // process the gesture queue for (var i = 0, e, rg; i < this.gestureQueue.length; i++) { e = this.gestureQueue[i]; rg = e._requiredGestures; if (rg) { for (var j = 0, g, fn; j < this.gestures.length; j++) { // only run recognizer if an element in the source event's path is listening for those gestures if (rg[j]) { g = this.gestures[j]; fn = g[e.type]; if (fn) { fn.call(g, e); } } } } } this.gestureQueue.length = 0; }, fillGestureQueue: function(ev) { // only trigger the gesture queue once if (!this.gestureQueue.length) { requestAnimationFrame(this.boundGestureTrigger); } ev._requiredGestures = this.requiredGestures.get(ev.pointerId); this.gestureQueue.push(ev); } }; dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher); dispatcher.boundGestureTrigger = dispatcher.gestureTrigger.bind(dispatcher); scope.dispatcher = dispatcher; /** * Listen for `gesture` on `node` with the `handler` function * * If `handler` is the first listener for `gesture`, the underlying gesture recognizer is then enabled. * * @param {Element} node * @param {string} gesture * @return Boolean `gesture` is a valid gesture */ scope.activateGesture = function(node, gesture) { var g = gesture.toLowerCase(); var dep = dispatcher.dependencyMap[g]; if (dep) { var recognizer = dispatcher.gestures[dep.index]; if (!node._pgListeners) { dispatcher.register(node); node._pgListeners = 0; } // TODO(dfreedm): re-evaluate bookkeeping to avoid using attributes if (recognizer) { var touchAction = recognizer.defaultActions && recognizer.defaultActions[g]; var actionNode; switch(node.nodeType) { case Node.ELEMENT_NODE: actionNode = node; break; case Node.DOCUMENT_FRAGMENT_NODE: actionNode = node.host; break; default: actionNode = null; break; } if (touchAction && actionNode && !actionNode.hasAttribute('touch-action')) { actionNode.setAttribute('touch-action', touchAction); } } if (!node._pgEvents) { node._pgEvents = {}; } node._pgEvents[g] = (node._pgEvents[g] || 0) + 1; node._pgListeners++; } return Boolean(dep); }; /** * * Listen for `gesture` from `node` with `handler` function. * * @param {Element} node * @param {string} gesture * @param {Function} handler * @param {Boolean} capture */ scope.addEventListener = function(node, gesture, handler, capture) { if (handler) { scope.activateGesture(node, gesture); node.addEventListener(gesture, handler, capture); } }; /** * Tears down the gesture configuration for `node` * * If `handler` is the last listener for `gesture`, the underlying gesture recognizer is disabled. * * @param {Element} node * @param {string} gesture * @return Boolean `gesture` is a valid gesture */ scope.deactivateGesture = function(node, gesture) { var g = gesture.toLowerCase(); var dep = dispatcher.dependencyMap[g]; if (dep) { if (node._pgListeners > 0) { node._pgListeners--; } if (node._pgListeners === 0) { dispatcher.unregister(node); } if (node._pgEvents) { if (node._pgEvents[g] > 0) { node._pgEvents[g]--; } else { node._pgEvents[g] = 0; } } } return Boolean(dep); }; /** * Stop listening for `gesture` from `node` with `handler` function. * * @param {Element} node * @param {string} gesture * @param {Function} handler * @param {Boolean} capture */ scope.removeEventListener = function(node, gesture, handler, capture) { if (handler) { scope.deactivateGesture(node, gesture); node.removeEventListener(gesture, handler, capture); } }; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var pointermap = dispatcher.pointermap; // radius around touchend that swallows mouse events var DEDUP_DIST = 25; var WHICH_TO_BUTTONS = [0, 1, 4, 2]; var currentButtons = 0; var FIREFOX_LINUX = /Linux.*Firefox\//i; var HAS_BUTTONS = (function() { // firefox on linux returns spec-incorrect values for mouseup.buttons // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.buttons#See_also // https://codereview.chromium.org/727593003/#msg16 if (FIREFOX_LINUX.test(navigator.userAgent)) { return false; } try { return new MouseEvent('test', {buttons: 1}).buttons === 1; } catch (e) { return false; } })(); // handler block for native mouse events var mouseEvents = { POINTER_ID: 1, POINTER_TYPE: 'mouse', events: [ 'mousedown', 'mousemove', 'mouseup' ], exposes: [ 'down', 'up', 'move' ], register: function(target) { dispatcher.listen(target, this.events); }, unregister: function(target) { if (target === document) { return; } dispatcher.unlisten(target, this.events); }, lastTouches: [], // collide with the global mouse listener isEventSimulatedFromTouch: function(inEvent) { var lts = this.lastTouches; var x = inEvent.clientX, y = inEvent.clientY; for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) { // simulated mouse events will be swallowed near a primary touchend var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y); if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) { return true; } } }, prepareEvent: function(inEvent) { var e = dispatcher.cloneEvent(inEvent); e.pointerId = this.POINTER_ID; e.isPrimary = true; e.pointerType = this.POINTER_TYPE; e._source = 'mouse'; if (!HAS_BUTTONS) { var type = inEvent.type; var bit = WHICH_TO_BUTTONS[inEvent.which] || 0; if (type === 'mousedown') { currentButtons |= bit; } else if (type === 'mouseup') { currentButtons &= ~bit; } e.buttons = currentButtons; } return e; }, mousedown: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var p = pointermap.has(this.POINTER_ID); var e = this.prepareEvent(inEvent); e.target = scope.findTarget(inEvent); pointermap.set(this.POINTER_ID, e.target); dispatcher.down(e); } }, mousemove: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var target = pointermap.get(this.POINTER_ID); if (target) { var e = this.prepareEvent(inEvent); e.target = target; // handle case where we missed a mouseup if ((HAS_BUTTONS ? e.buttons : e.which) === 0) { if (!HAS_BUTTONS) { currentButtons = e.buttons = 0; } dispatcher.cancel(e); this.cleanupMouse(e.buttons); } else { dispatcher.move(e); } } } }, mouseup: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(this.POINTER_ID); dispatcher.up(e); this.cleanupMouse(e.buttons); } }, cleanupMouse: function(buttons) { if (buttons === 0) { pointermap.delete(this.POINTER_ID); } } }; scope.mouseEvents = mouseEvents; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var allShadows = scope.targetFinding.allShadows.bind(scope.targetFinding); var pointermap = dispatcher.pointermap; var touchMap = Array.prototype.map.call.bind(Array.prototype.map); // This should be long enough to ignore compat mouse events made by touch var DEDUP_TIMEOUT = 2500; var DEDUP_DIST = 25; var CLICK_COUNT_TIMEOUT = 200; var HYSTERESIS = 20; var ATTRIB = 'touch-action'; // TODO(dfreedm): disable until http://crbug.com/399765 is resolved // var HAS_TOUCH_ACTION = ATTRIB in document.head.style; var HAS_TOUCH_ACTION = false; // handler block for native touch events var touchEvents = { IS_IOS: false, events: [ 'touchstart', 'touchmove', 'touchend', 'touchcancel' ], exposes: [ 'down', 'up', 'move' ], register: function(target, initial) { if (this.IS_IOS ? initial : !initial) { dispatcher.listen(target, this.events); } }, unregister: function(target) { if (!this.IS_IOS) { dispatcher.unlisten(target, this.events); } }, scrollTypes: { EMITTER: 'none', XSCROLLER: 'pan-x', YSCROLLER: 'pan-y', }, touchActionToScrollType: function(touchAction) { var t = touchAction; var st = this.scrollTypes; if (t === st.EMITTER) { return 'none'; } else if (t === st.XSCROLLER) { return 'X'; } else if (t === st.YSCROLLER) { return 'Y'; } else { return 'XY'; } }, POINTER_TYPE: 'touch', firstTouch: null, isPrimaryTouch: function(inTouch) { return this.firstTouch === inTouch.identifier; }, setPrimaryTouch: function(inTouch) { // set primary touch if there no pointers, or the only pointer is the mouse if (pointermap.pointers() === 0 || (pointermap.pointers() === 1 && pointermap.has(1))) { this.firstTouch = inTouch.identifier; this.firstXY = {X: inTouch.clientX, Y: inTouch.clientY}; this.firstTarget = inTouch.target; this.scrolling = null; this.cancelResetClickCount(); } }, removePrimaryPointer: function(inPointer) { if (inPointer.isPrimary) { this.firstTouch = null; this.firstXY = null; this.resetClickCount(); } }, clickCount: 0, resetId: null, resetClickCount: function() { var fn = function() { this.clickCount = 0; this.resetId = null; }.bind(this); this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT); }, cancelResetClickCount: function() { if (this.resetId) { clearTimeout(this.resetId); } }, typeToButtons: function(type) { var ret = 0; if (type === 'touchstart' || type === 'touchmove') { ret = 1; } return ret; }, findTarget: function(touch, id) { if (this.currentTouchEvent.type === 'touchstart') { if (this.isPrimaryTouch(touch)) { var fastPath = { clientX: touch.clientX, clientY: touch.clientY, path: this.currentTouchEvent.path, target: this.currentTouchEvent.target }; return scope.findTarget(fastPath); } else { return scope.findTarget(touch); } } // reuse target we found in touchstart return pointermap.get(id); }, touchToPointer: function(inTouch) { var cte = this.currentTouchEvent; var e = dispatcher.cloneEvent(inTouch); // Spec specifies that pointerId 1 is reserved for Mouse. // Touch identifiers can start at 0. // Add 2 to the touch identifier for compatibility. var id = e.pointerId = inTouch.identifier + 2; e.target = this.findTarget(inTouch, id); e.bubbles = true; e.cancelable = true; e.detail = this.clickCount; e.buttons = this.typeToButtons(cte.type); e.width = inTouch.webkitRadiusX || inTouch.radiusX || 0; e.height = inTouch.webkitRadiusY || inTouch.radiusY || 0; e.pressure = inTouch.webkitForce || inTouch.force || 0.5; e.isPrimary = this.isPrimaryTouch(inTouch); e.pointerType = this.POINTER_TYPE; e._source = 'touch'; // forward touch preventDefaults var self = this; e.preventDefault = function() { self.scrolling = false; self.firstXY = null; cte.preventDefault(); }; return e; }, processTouches: function(inEvent, inFunction) { var tl = inEvent.changedTouches; this.currentTouchEvent = inEvent; for (var i = 0, t, p; i < tl.length; i++) { t = tl[i]; p = this.touchToPointer(t); if (inEvent.type === 'touchstart') { pointermap.set(p.pointerId, p.target); } if (pointermap.has(p.pointerId)) { inFunction.call(this, p); } if (inEvent.type === 'touchend' || inEvent._cancel) { this.cleanUpPointer(p); } } }, // For single axis scrollers, determines whether the element should emit // pointer events or behave as a scroller shouldScroll: function(inEvent) { if (this.firstXY) { var ret; var touchAction = scope.targetFinding.findTouchAction(inEvent); var scrollAxis = this.touchActionToScrollType(touchAction); if (scrollAxis === 'none') { // this element is a touch-action: none, should never scroll ret = false; } else if (scrollAxis === 'XY') { // this element should always scroll ret = true; } else { var t = inEvent.changedTouches[0]; // check the intended scroll axis, and other axis var a = scrollAxis; var oa = scrollAxis === 'Y' ? 'X' : 'Y'; var da = Math.abs(t['client' + a] - this.firstXY[a]); var doa = Math.abs(t['client' + oa] - this.firstXY[oa]); // if delta in the scroll axis > delta other axis, scroll instead of // making events ret = da >= doa; } return ret; } }, findTouch: function(inTL, inId) { for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) { if (t.identifier === inId) { return true; } } }, // In some instances, a touchstart can happen without a touchend. This // leaves the pointermap in a broken state. // Therefore, on every touchstart, we remove the touches that did not fire a // touchend event. // To keep state globally consistent, we fire a // pointercancel for this "abandoned" touch vacuumTouches: function(inEvent) { var tl = inEvent.touches; // pointermap.pointers() should be < tl.length here, as the touchstart has not // been processed yet. if (pointermap.pointers() >= tl.length) { var d = []; pointermap.forEach(function(value, key) { // Never remove pointerId == 1, which is mouse. // Touch identifiers are 2 smaller than their pointerId, which is the // index in pointermap. if (key !== 1 && !this.findTouch(tl, key - 2)) { var p = value; d.push(p); } }, this); d.forEach(function(p) { this.cancel(p); pointermap.delete(p.pointerId); }, this); } }, touchstart: function(inEvent) { this.vacuumTouches(inEvent); this.setPrimaryTouch(inEvent.changedTouches[0]); this.dedupSynthMouse(inEvent); if (!this.scrolling) { this.clickCount++; this.processTouches(inEvent, this.down); } }, down: function(inPointer) { dispatcher.down(inPointer); }, touchmove: function(inEvent) { if (HAS_TOUCH_ACTION) { // touchevent.cancelable == false is sent when the page is scrolling under native Touch Action in Chrome 36 // https://groups.google.com/a/chromium.org/d/msg/input-dev/wHnyukcYBcA/b9kmtwM1jJQJ if (inEvent.cancelable) { this.processTouches(inEvent, this.move); } } else { if (!this.scrolling) { if (this.scrolling === null && this.shouldScroll(inEvent)) { this.scrolling = true; } else { this.scrolling = false; inEvent.preventDefault(); this.processTouches(inEvent, this.move); } } else if (this.firstXY) { var t = inEvent.changedTouches[0]; var dx = t.clientX - this.firstXY.X; var dy = t.clientY - this.firstXY.Y; var dd = Math.sqrt(dx * dx + dy * dy); if (dd >= HYSTERESIS) { this.touchcancel(inEvent); this.scrolling = true; this.firstXY = null; } } } }, move: function(inPointer) { dispatcher.move(inPointer); }, touchend: function(inEvent) { this.dedupSynthMouse(inEvent); this.processTouches(inEvent, this.up); }, up: function(inPointer) { inPointer.relatedTarget = scope.findTarget(inPointer); dispatcher.up(inPointer); }, cancel: function(inPointer) { dispatcher.cancel(inPointer); }, touchcancel: function(inEvent) { inEvent._cancel = true; this.processTouches(inEvent, this.cancel); }, cleanUpPointer: function(inPointer) { pointermap['delete'](inPointer.pointerId); this.removePrimaryPointer(inPointer); }, // prevent synth mouse events from creating pointer events dedupSynthMouse: function(inEvent) { var lts = scope.mouseEvents.lastTouches; var t = inEvent.changedTouches[0]; // only the primary finger will synth mouse events if (this.isPrimaryTouch(t)) { // remember x/y of last touch var lt = {x: t.clientX, y: t.clientY}; lts.push(lt); var fn = (function(lts, lt){ var i = lts.indexOf(lt); if (i > -1) { lts.splice(i, 1); } }).bind(null, lts, lt); setTimeout(fn, DEDUP_TIMEOUT); } } }; // prevent "ghost clicks" that come from elements that were removed in a touch handler var STOP_PROP_FN = Event.prototype.stopImmediatePropagation || Event.prototype.stopPropagation; document.addEventListener('click', function(ev) { var x = ev.clientX, y = ev.clientY; // check if a click is within DEDUP_DIST px radius of the touchstart var closeTo = function(touch) { var dx = Math.abs(x - touch.x), dy = Math.abs(y - touch.y); return (dx <= DEDUP_DIST && dy <= DEDUP_DIST); }; // if click coordinates are close to touch coordinates, assume the click came from a touch var wasTouched = scope.mouseEvents.lastTouches.some(closeTo); // if the click came from touch, and the touchstart target is not in the path of the click event, // then the touchstart target was probably removed, and the click should be "busted" var path = scope.targetFinding.path(ev); if (wasTouched) { for (var i = 0; i < path.length; i++) { if (path[i] === touchEvents.firstTarget) { return; } } ev.preventDefault(); STOP_PROP_FN.call(ev); } }, true); scope.touchEvents = touchEvents; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var pointermap = dispatcher.pointermap; var HAS_BITMAP_TYPE = window.MSPointerEvent && typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number'; var msEvents = { events: [ 'MSPointerDown', 'MSPointerMove', 'MSPointerUp', 'MSPointerCancel', ], register: function(target) { dispatcher.listen(target, this.events); }, unregister: function(target) { if (target === document) { return; } dispatcher.unlisten(target, this.events); }, POINTER_TYPES: [ '', 'unavailable', 'touch', 'pen', 'mouse' ], prepareEvent: function(inEvent) { var e = inEvent; e = dispatcher.cloneEvent(inEvent); if (HAS_BITMAP_TYPE) { e.pointerType = this.POINTER_TYPES[inEvent.pointerType]; } e._source = 'ms'; return e; }, cleanup: function(id) { pointermap['delete'](id); }, MSPointerDown: function(inEvent) { var e = this.prepareEvent(inEvent); e.target = scope.findTarget(inEvent); pointermap.set(inEvent.pointerId, e.target); dispatcher.down(e); }, MSPointerMove: function(inEvent) { var target = pointermap.get(inEvent.pointerId); if (target) { var e = this.prepareEvent(inEvent); e.target = target; dispatcher.move(e); } }, MSPointerUp: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.up(e); this.cleanup(inEvent.pointerId); }, MSPointerCancel: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.cancel(e); this.cleanup(inEvent.pointerId); } }; scope.msEvents = msEvents; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var pointermap = dispatcher.pointermap; var pointerEvents = { events: [ 'pointerdown', 'pointermove', 'pointerup', 'pointercancel' ], prepareEvent: function(inEvent) { var e = dispatcher.cloneEvent(inEvent); e._source = 'pointer'; return e; }, register: function(target) { dispatcher.listen(target, this.events); }, unregister: function(target) { if (target === document) { return; } dispatcher.unlisten(target, this.events); }, cleanup: function(id) { pointermap['delete'](id); }, pointerdown: function(inEvent) { var e = this.prepareEvent(inEvent); e.target = scope.findTarget(inEvent); pointermap.set(e.pointerId, e.target); dispatcher.down(e); }, pointermove: function(inEvent) { var target = pointermap.get(inEvent.pointerId); if (target) { var e = this.prepareEvent(inEvent); e.target = target; dispatcher.move(e); } }, pointerup: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.up(e); this.cleanup(inEvent.pointerId); }, pointercancel: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.cancel(e); this.cleanup(inEvent.pointerId); } }; scope.pointerEvents = pointerEvents; })(window.PolymerGestures); /** * This module contains the handlers for native platform events. * From here, the dispatcher is called to create unified pointer events. * Included are touch events (v1), mouse events, and MSPointerEvents. */ (function(scope) { var dispatcher = scope.dispatcher; var nav = window.navigator; if (window.PointerEvent) { dispatcher.registerSource('pointer', scope.pointerEvents); } else if (nav.msPointerEnabled) { dispatcher.registerSource('ms', scope.msEvents); } else { dispatcher.registerSource('mouse', scope.mouseEvents); if (window.ontouchstart !== undefined) { dispatcher.registerSource('touch', scope.touchEvents); } } // Work around iOS bugs https://bugs.webkit.org/show_bug.cgi?id=135628 and https://bugs.webkit.org/show_bug.cgi?id=136506 var ua = navigator.userAgent; var IS_IOS = ua.match(/iPad|iPhone|iPod/) && 'ontouchstart' in window; dispatcher.IS_IOS = IS_IOS; scope.touchEvents.IS_IOS = IS_IOS; dispatcher.register(document, true); })(window.PolymerGestures); /** * This event denotes the beginning of a series of tracking events. * * @module PointerGestures * @submodule Events * @class trackstart */ /** * Pixels moved in the x direction since trackstart. * @type Number * @property dx */ /** * Pixes moved in the y direction since trackstart. * @type Number * @property dy */ /** * Pixels moved in the x direction since the last track. * @type Number * @property ddx */ /** * Pixles moved in the y direction since the last track. * @type Number * @property ddy */ /** * The clientX position of the track gesture. * @type Number * @property clientX */ /** * The clientY position of the track gesture. * @type Number * @property clientY */ /** * The pageX position of the track gesture. * @type Number * @property pageX */ /** * The pageY position of the track gesture. * @type Number * @property pageY */ /** * The screenX position of the track gesture. * @type Number * @property screenX */ /** * The screenY position of the track gesture. * @type Number * @property screenY */ /** * The last x axis direction of the pointer. * @type Number * @property xDirection */ /** * The last y axis direction of the pointer. * @type Number * @property yDirection */ /** * A shared object between all tracking events. * @type Object * @property trackInfo */ /** * The element currently under the pointer. * @type Element * @property relatedTarget */ /** * The type of pointer that make the track gesture. * @type String * @property pointerType */ /** * * This event fires for all pointer movement being tracked. * * @class track * @extends trackstart */ /** * This event fires when the pointer is no longer being tracked. * * @class trackend * @extends trackstart */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var pointermap = new scope.PointerMap(); var track = { events: [ 'down', 'move', 'up', ], exposes: [ 'trackstart', 'track', 'trackx', 'tracky', 'trackend' ], defaultActions: { 'track': 'none', 'trackx': 'pan-y', 'tracky': 'pan-x' }, WIGGLE_THRESHOLD: 4, clampDir: function(inDelta) { return inDelta > 0 ? 1 : -1; }, calcPositionDelta: function(inA, inB) { var x = 0, y = 0; if (inA && inB) { x = inB.pageX - inA.pageX; y = inB.pageY - inA.pageY; } return {x: x, y: y}; }, fireTrack: function(inType, inEvent, inTrackingData) { var t = inTrackingData; var d = this.calcPositionDelta(t.downEvent, inEvent); var dd = this.calcPositionDelta(t.lastMoveEvent, inEvent); if (dd.x) { t.xDirection = this.clampDir(dd.x); } else if (inType === 'trackx') { return; } if (dd.y) { t.yDirection = this.clampDir(dd.y); } else if (inType === 'tracky') { return; } var gestureProto = { bubbles: true, cancelable: true, trackInfo: t.trackInfo, relatedTarget: inEvent.relatedTarget, pointerType: inEvent.pointerType, pointerId: inEvent.pointerId, _source: 'track' }; if (inType !== 'tracky') { gestureProto.x = inEvent.x; gestureProto.dx = d.x; gestureProto.ddx = dd.x; gestureProto.clientX = inEvent.clientX; gestureProto.pageX = inEvent.pageX; gestureProto.screenX = inEvent.screenX; gestureProto.xDirection = t.xDirection; } if (inType !== 'trackx') { gestureProto.dy = d.y; gestureProto.ddy = dd.y; gestureProto.y = inEvent.y; gestureProto.clientY = inEvent.clientY; gestureProto.pageY = inEvent.pageY; gestureProto.screenY = inEvent.screenY; gestureProto.yDirection = t.yDirection; } var e = eventFactory.makeGestureEvent(inType, gestureProto); t.downTarget.dispatchEvent(e); }, down: function(inEvent) { if (inEvent.isPrimary && (inEvent.pointerType === 'mouse' ? inEvent.buttons === 1 : true)) { var p = { downEvent: inEvent, downTarget: inEvent.target, trackInfo: {}, lastMoveEvent: null, xDirection: 0, yDirection: 0, tracking: false }; pointermap.set(inEvent.pointerId, p); } }, move: function(inEvent) { var p = pointermap.get(inEvent.pointerId); if (p) { if (!p.tracking) { var d = this.calcPositionDelta(p.downEvent, inEvent); var move = d.x * d.x + d.y * d.y; // start tracking only if finger moves more than WIGGLE_THRESHOLD if (move > this.WIGGLE_THRESHOLD) { p.tracking = true; p.lastMoveEvent = p.downEvent; this.fireTrack('trackstart', inEvent, p); } } if (p.tracking) { this.fireTrack('track', inEvent, p); this.fireTrack('trackx', inEvent, p); this.fireTrack('tracky', inEvent, p); } p.lastMoveEvent = inEvent; } }, up: function(inEvent) { var p = pointermap.get(inEvent.pointerId); if (p) { if (p.tracking) { this.fireTrack('trackend', inEvent, p); } pointermap.delete(inEvent.pointerId); } } }; dispatcher.registerGesture('track', track); })(window.PolymerGestures); /** * This event is fired when a pointer is held down for 200ms. * * @module PointerGestures * @submodule Events * @class hold */ /** * Type of pointer that made the holding event. * @type String * @property pointerType */ /** * Screen X axis position of the held pointer * @type Number * @property clientX */ /** * Screen Y axis position of the held pointer * @type Number * @property clientY */ /** * Type of pointer that made the holding event. * @type String * @property pointerType */ /** * This event is fired every 200ms while a pointer is held down. * * @class holdpulse * @extends hold */ /** * Milliseconds pointer has been held down. * @type Number * @property holdTime */ /** * This event is fired when a held pointer is released or moved. * * @class release */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var hold = { // wait at least HOLD_DELAY ms between hold and pulse events HOLD_DELAY: 200, // pointer can move WIGGLE_THRESHOLD pixels before not counting as a hold WIGGLE_THRESHOLD: 16, events: [ 'down', 'move', 'up', ], exposes: [ 'hold', 'holdpulse', 'release' ], heldPointer: null, holdJob: null, pulse: function() { var hold = Date.now() - this.heldPointer.timeStamp; var type = this.held ? 'holdpulse' : 'hold'; this.fireHold(type, hold); this.held = true; }, cancel: function() { clearInterval(this.holdJob); if (this.held) { this.fireHold('release'); } this.held = false; this.heldPointer = null; this.target = null; this.holdJob = null; }, down: function(inEvent) { if (inEvent.isPrimary && !this.heldPointer) { this.heldPointer = inEvent; this.target = inEvent.target; this.holdJob = setInterval(this.pulse.bind(this), this.HOLD_DELAY); } }, up: function(inEvent) { if (this.heldPointer && this.heldPointer.pointerId === inEvent.pointerId) { this.cancel(); } }, move: function(inEvent) { if (this.heldPointer && this.heldPointer.pointerId === inEvent.pointerId) { var x = inEvent.clientX - this.heldPointer.clientX; var y = inEvent.clientY - this.heldPointer.clientY; if ((x * x + y * y) > this.WIGGLE_THRESHOLD) { this.cancel(); } } }, fireHold: function(inType, inHoldTime) { var p = { bubbles: true, cancelable: true, pointerType: this.heldPointer.pointerType, pointerId: this.heldPointer.pointerId, x: this.heldPointer.clientX, y: this.heldPointer.clientY, _source: 'hold' }; if (inHoldTime) { p.holdTime = inHoldTime; } var e = eventFactory.makeGestureEvent(inType, p); this.target.dispatchEvent(e); } }; dispatcher.registerGesture('hold', hold); })(window.PolymerGestures); /** * This event is fired when a pointer quickly goes down and up, and is used to * denote activation. * * Any gesture event can prevent the tap event from being created by calling * `event.preventTap`. * * Any pointer event can prevent the tap by setting the `tapPrevented` property * on itself. * * @module PointerGestures * @submodule Events * @class tap */ /** * X axis position of the tap. * @property x * @type Number */ /** * Y axis position of the tap. * @property y * @type Number */ /** * Type of the pointer that made the tap. * @property pointerType * @type String */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var pointermap = new scope.PointerMap(); var tap = { events: [ 'down', 'up' ], exposes: [ 'tap' ], down: function(inEvent) { if (inEvent.isPrimary && !inEvent.tapPrevented) { pointermap.set(inEvent.pointerId, { target: inEvent.target, buttons: inEvent.buttons, x: inEvent.clientX, y: inEvent.clientY }); } }, shouldTap: function(e, downState) { var tap = true; if (e.pointerType === 'mouse') { // only allow left click to tap for mouse tap = (e.buttons ^ 1) && (downState.buttons & 1); } return tap && !e.tapPrevented; }, up: function(inEvent) { var start = pointermap.get(inEvent.pointerId); if (start && this.shouldTap(inEvent, start)) { // up.relatedTarget is target currently under finger var t = scope.targetFinding.LCA(start.target, inEvent.relatedTarget); if (t) { var e = eventFactory.makeGestureEvent('tap', { bubbles: true, cancelable: true, x: inEvent.clientX, y: inEvent.clientY, detail: inEvent.detail, pointerType: inEvent.pointerType, pointerId: inEvent.pointerId, altKey: inEvent.altKey, ctrlKey: inEvent.ctrlKey, metaKey: inEvent.metaKey, shiftKey: inEvent.shiftKey, _source: 'tap' }); t.dispatchEvent(e); } } pointermap.delete(inEvent.pointerId); } }; // patch eventFactory to remove id from tap's pointermap for preventTap calls eventFactory.preventTap = function(e) { return function() { e.tapPrevented = true; pointermap.delete(e.pointerId); }; }; dispatcher.registerGesture('tap', tap); })(window.PolymerGestures); /* * Basic strategy: find the farthest apart points, use as diameter of circle * react to size change and rotation of the chord */ /** * @module pointer-gestures * @submodule Events * @class pinch */ /** * Scale of the pinch zoom gesture * @property scale * @type Number */ /** * Center X position of pointers causing pinch * @property centerX * @type Number */ /** * Center Y position of pointers causing pinch * @property centerY * @type Number */ /** * @module pointer-gestures * @submodule Events * @class rotate */ /** * Angle (in degrees) of rotation. Measured from starting positions of pointers. * @property angle * @type Number */ /** * Center X position of pointers causing rotation * @property centerX * @type Number */ /** * Center Y position of pointers causing rotation * @property centerY * @type Number */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var pointermap = new scope.PointerMap(); var RAD_TO_DEG = 180 / Math.PI; var pinch = { events: [ 'down', 'up', 'move', 'cancel' ], exposes: [ 'pinchstart', 'pinch', 'pinchend', 'rotate' ], defaultActions: { 'pinch': 'none', 'rotate': 'none' }, reference: {}, down: function(inEvent) { pointermap.set(inEvent.pointerId, inEvent); if (pointermap.pointers() == 2) { var points = this.calcChord(); var angle = this.calcAngle(points); this.reference = { angle: angle, diameter: points.diameter, target: scope.targetFinding.LCA(points.a.target, points.b.target) }; this.firePinch('pinchstart', points.diameter, points); } }, up: function(inEvent) { var p = pointermap.get(inEvent.pointerId); var num = pointermap.pointers(); if (p) { if (num === 2) { // fire 'pinchend' before deleting pointer var points = this.calcChord(); this.firePinch('pinchend', points.diameter, points); } pointermap.delete(inEvent.pointerId); } }, move: function(inEvent) { if (pointermap.has(inEvent.pointerId)) { pointermap.set(inEvent.pointerId, inEvent); if (pointermap.pointers() > 1) { this.calcPinchRotate(); } } }, cancel: function(inEvent) { this.up(inEvent); }, firePinch: function(type, diameter, points) { var zoom = diameter / this.reference.diameter; var e = eventFactory.makeGestureEvent(type, { bubbles: true, cancelable: true, scale: zoom, centerX: points.center.x, centerY: points.center.y, _source: 'pinch' }); this.reference.target.dispatchEvent(e); }, fireRotate: function(angle, points) { var diff = Math.round((angle - this.reference.angle) % 360); var e = eventFactory.makeGestureEvent('rotate', { bubbles: true, cancelable: true, angle: diff, centerX: points.center.x, centerY: points.center.y, _source: 'pinch' }); this.reference.target.dispatchEvent(e); }, calcPinchRotate: function() { var points = this.calcChord(); var diameter = points.diameter; var angle = this.calcAngle(points); if (diameter != this.reference.diameter) { this.firePinch('pinch', diameter, points); } if (angle != this.reference.angle) { this.fireRotate(angle, points); } }, calcChord: function() { var pointers = []; pointermap.forEach(function(p) { pointers.push(p); }); var dist = 0; // start with at least two pointers var points = {a: pointers[0], b: pointers[1]}; var x, y, d; for (var i = 0; i < pointers.length; i++) { var a = pointers[i]; for (var j = i + 1; j < pointers.length; j++) { var b = pointers[j]; x = Math.abs(a.clientX - b.clientX); y = Math.abs(a.clientY - b.clientY); d = x + y; if (d > dist) { dist = d; points = {a: a, b: b}; } } } x = Math.abs(points.a.clientX + points.b.clientX) / 2; y = Math.abs(points.a.clientY + points.b.clientY) / 2; points.center = { x: x, y: y }; points.diameter = dist; return points; }, calcAngle: function(points) { var x = points.a.clientX - points.b.clientX; var y = points.a.clientY - points.b.clientY; return (360 + Math.atan2(y, x) * RAD_TO_DEG) % 360; } }; dispatcher.registerGesture('pinch', pinch); })(window.PolymerGestures); (function (global) { 'use strict'; var Token, TokenName, Syntax, Messages, source, index, length, delegate, lookahead, state; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = '<end>'; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; Syntax = { ArrayExpression: 'ArrayExpression', BinaryExpression: 'BinaryExpression', CallExpression: 'CallExpression', ConditionalExpression: 'ConditionalExpression', EmptyStatement: 'EmptyStatement', ExpressionStatement: 'ExpressionStatement', Identifier: 'Identifier', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', ObjectExpression: 'ObjectExpression', Program: 'Program', Property: 'Property', ThisExpression: 'ThisExpression', UnaryExpression: 'UnaryExpression' }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared' }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { if (!condition) { throw new Error('ASSERT: ' + message); } } function isDecimalDigit(ch) { return (ch >= 48 && ch <= 57); // 0..9 } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 32) || // space (ch === 9) || // tab (ch === 0xB) || (ch === 0xC) || (ch === 0xA0) || (ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122); // a..z } function isIdentifierPart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch >= 48 && ch <= 57); // 0..9 } // 7.6.1.1 Keywords function isKeyword(id) { return (id === 'this') } // 7.4 Comments function skipWhitespace() { while (index < length && isWhiteSpace(source.charCodeAt(index))) { ++index; } } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; id = getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = Token.Identifier; } else if (isKeyword(id)) { type = Token.Keyword; } else if (id === 'null') { type = Token.NullLiteral; } else if (id === 'true' || id === 'false') { type = Token.BooleanLiteral; } else { type = Token.Identifier; } return { type: type, value: id, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source.charCodeAt(index), code2, ch1 = source[index], ch2; switch (code) { // Check for most common single-character punctuators. case 46: // . dot case 40: // ( open bracket case 41: // ) close bracket case 59: // ; semicolon case 44: // , comma case 123: // { open curly brace case 125: // } close curly brace case 91: // [ case 93: // ] case 58: // : case 63: // ? ++index; return { type: Token.Punctuator, value: String.fromCharCode(code), range: [start, index] }; default: code2 = source.charCodeAt(index + 1); // '=' (char #61) marks an assignment or comparison operator. if (code2 === 61) { switch (code) { case 37: // % case 38: // & case 42: // *: case 43: // + case 45: // - case 47: // / case 60: // < case 62: // > case 124: // | index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), range: [start, index] }; case 33: // ! case 61: // = index += 2; // !== and === if (source.charCodeAt(index) === 61) { ++index; } return { type: Token.Punctuator, value: source.slice(start, index), range: [start, index] }; default: break; } } break; } // Peek more characters. ch2 = source[index + 1]; // Other 2-character punctuators: && || if (ch1 === ch2 && ('&|'.indexOf(ch1) >= 0)) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, range: [start, index] }; } if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: Token.Punctuator, value: ch1, range: [start, index] }; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // 7.8.3 Numeric Literals function scanNumericLiteral() { var number, start, ch; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. if (number === '0') { // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === '.') { number += source[index++]; while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } if (isDecimalDigit(source.charCodeAt(index))) { while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } } else { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseFloat(number), range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: str += ch; break; } } else { if (ch === '\r' && source[index] === '\n') { ++index; } } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advance() { var ch; skipWhitespace(); if (index >= length) { return { type: Token.EOF, range: [index, index] }; } ch = source.charCodeAt(index); // Very common: ( and ) and ; if (ch === 40 || ch === 41 || ch === 58) { return scanPunctuator(); } // String literal starts with single quote (#39) or double quote (#34). if (ch === 39 || ch === 34) { return scanStringLiteral(); } if (isIdentifierStart(ch)) { return scanIdentifier(); } // Dot (.) char #46 can also start a floating-point number, hence the need // to check the next character. if (ch === 46) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index = token.range[1]; lookahead = advance(); index = token.range[1]; return token; } function peek() { var pos; pos = index; lookahead = advance(); index = pos; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, index) { assert(index < args.length, 'Message reference must be in range'); return args[index]; } ); error = new Error(msg); error.index = index; error.description = msg; throw error; } // Throw an exception because of the token. function throwUnexpected(token) { throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === Token.Punctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword) { return lookahead.type === Token.Keyword && lookahead.value === keyword; } function consumeSemicolon() { // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); return; } skipWhitespace(); if (match(';')) { lex(); return; } if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpected(lookahead); } } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = []; expect('['); while (!match(']')) { if (match(',')) { lex(); elements.push(null); } else { elements.push(parseExpression()); if (!match(']')) { expect(','); } } } expect(']'); return delegate.createArrayExpression(elements); } // 11.1.5 Object Initialiser function parseObjectPropertyKey() { var token; skipWhitespace(); token = lex(); // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { return delegate.createLiteral(token); } return delegate.createIdentifier(token.value); } function parseObjectProperty() { var token, key; token = lookahead; skipWhitespace(); if (token.type === Token.EOF || token.type === Token.Punctuator) { throwUnexpected(token); } key = parseObjectPropertyKey(); expect(':'); return delegate.createProperty('init', key, parseExpression()); } function parseObjectInitialiser() { var properties = []; expect('{'); while (!match('}')) { properties.push(parseObjectProperty()); if (!match('}')) { expect(','); } } expect('}'); return delegate.createObjectExpression(properties); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr; expect('('); expr = parseExpression(); expect(')'); return expr; } // 11.1 Primary Expressions function parsePrimaryExpression() { var type, token, expr; if (match('(')) { return parseGroupExpression(); } type = lookahead.type; if (type === Token.Identifier) { expr = delegate.createIdentifier(lex().value); } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { expr = delegate.createLiteral(lex()); } else if (type === Token.Keyword) { if (matchKeyword('this')) { lex(); expr = delegate.createThisExpression(); } } else if (type === Token.BooleanLiteral) { token = lex(); token.value = (token.value === 'true'); expr = delegate.createLiteral(token); } else if (type === Token.NullLiteral) { token = lex(); token.value = null; expr = delegate.createLiteral(token); } else if (match('[')) { expr = parseArrayInitialiser(); } else if (match('{')) { expr = parseObjectInitialiser(); } if (expr) { return expr; } throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = []; expect('('); if (!match(')')) { while (index < length) { args.push(parseExpression()); if (match(')')) { break; } expect(','); } } expect(')'); return args; } function parseNonComputedProperty() { var token; token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return delegate.createIdentifier(token.value); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseLeftHandSideExpression() { var expr, args, property; expr = parsePrimaryExpression(); while (true) { if (match('[')) { property = parseComputedMember(); expr = delegate.createMemberExpression('[', expr, property); } else if (match('.')) { property = parseNonComputedMember(); expr = delegate.createMemberExpression('.', expr, property); } else if (match('(')) { args = parseArguments(); expr = delegate.createCallExpression(expr, args); } else { break; } } return expr; } // 11.3 Postfix Expressions var parsePostfixExpression = parseLeftHandSideExpression; // 11.4 Unary Operators function parseUnaryExpression() { var token, expr; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { expr = parsePostfixExpression(); } else if (match('+') || match('-') || match('!')) { token = lex(); expr = parseUnaryExpression(); expr = delegate.createUnaryExpression(token.value, expr); } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { throwError({}, Messages.UnexpectedToken); } else { expr = parsePostfixExpression(); } return expr; } function binaryPrecedence(token) { var prec = 0; if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = 7; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var expr, token, prec, stack, right, operator, left, i; left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token); if (prec === 0) { return left; } token.prec = prec; lex(); right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); expr = delegate.createBinaryExpression(operator, left, right); stack.push(expr); } // Shift. token = lex(); token.prec = prec; stack.push(token); expr = parseUnaryExpression(); stack.push(expr); } // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; while (i > 1) { expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, consequent, alternate; expr = parseBinaryExpression(); if (match('?')) { lex(); consequent = parseConditionalExpression(); expect(':'); alternate = parseConditionalExpression(); expr = delegate.createConditionalExpression(expr, consequent, alternate); } return expr; } // Simplification since we do not support AssignmentExpression. var parseExpression = parseConditionalExpression; // Polymer Syntax extensions // Filter :: // Identifier // Identifier "(" ")" // Identifier "(" FilterArguments ")" function parseFilter() { var identifier, args; identifier = lex(); if (identifier.type !== Token.Identifier) { throwUnexpected(identifier); } args = match('(') ? parseArguments() : []; return delegate.createFilter(identifier.value, args); } // Filters :: // "|" Filter // Filters "|" Filter function parseFilters() { while (match('|')) { lex(); parseFilter(); } } // TopLevel :: // LabelledExpressions // AsExpression // InExpression // FilterExpression // AsExpression :: // FilterExpression as Identifier // InExpression :: // Identifier, Identifier in FilterExpression // Identifier in FilterExpression // FilterExpression :: // Expression // Expression Filters function parseTopLevel() { skipWhitespace(); peek(); var expr = parseExpression(); if (expr) { if (lookahead.value === ',' || lookahead.value == 'in' && expr.type === Syntax.Identifier) { parseInExpression(expr); } else { parseFilters(); if (lookahead.value === 'as') { parseAsExpression(expr); } else { delegate.createTopLevel(expr); } } } if (lookahead.type !== Token.EOF) { throwUnexpected(lookahead); } } function parseAsExpression(expr) { lex(); // as var identifier = lex().value; delegate.createAsExpression(expr, identifier); } function parseInExpression(identifier) { var indexName; if (lookahead.value === ',') { lex(); if (lookahead.type !== Token.Identifier) throwUnexpected(lookahead); indexName = lex().value; } lex(); // in var expr = parseExpression(); parseFilters(); delegate.createInExpression(identifier.name, indexName, expr); } function parse(code, inDelegate) { delegate = inDelegate; source = code; index = 0; length = source.length; lookahead = null; state = { labelSet: {} }; return parseTopLevel(); } global.esprima = { parse: parse }; })(this); // Copyright (c) 2014 The Polymer Project Authors. All rights reserved. // This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt // The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt // The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt // Code distributed by Google as part of the polymer project is also // subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt (function (global) { 'use strict'; function prepareBinding(expressionText, name, node, filterRegistry) { var expression; try { expression = getExpression(expressionText); if (expression.scopeIdent && (node.nodeType !== Node.ELEMENT_NODE || node.tagName !== 'TEMPLATE' || (name !== 'bind' && name !== 'repeat'))) { throw Error('as and in can only be used within <template bind/repeat>'); } } catch (ex) { console.error('Invalid expression syntax: ' + expressionText, ex); return; } return function(model, node, oneTime) { var binding = expression.getBinding(model, filterRegistry, oneTime); if (expression.scopeIdent && binding) { node.polymerExpressionScopeIdent_ = expression.scopeIdent; if (expression.indexIdent) node.polymerExpressionIndexIdent_ = expression.indexIdent; } return binding; } } // TODO(rafaelw): Implement simple LRU. var expressionParseCache = Object.create(null); function getExpression(expressionText) { var expression = expressionParseCache[expressionText]; if (!expression) { var delegate = new ASTDelegate(); esprima.parse(expressionText, delegate); expression = new Expression(delegate); expressionParseCache[expressionText] = expression; } return expression; } function Literal(value) { this.value = value; this.valueFn_ = undefined; } Literal.prototype = { valueFn: function() { if (!this.valueFn_) { var value = this.value; this.valueFn_ = function() { return value; } } return this.valueFn_; } } function IdentPath(name) { this.name = name; this.path = Path.get(name); } IdentPath.prototype = { valueFn: function() { if (!this.valueFn_) { var name = this.name; var path = this.path; this.valueFn_ = function(model, observer) { if (observer) observer.addPath(model, path); return path.getValueFrom(model); } } return this.valueFn_; }, setValue: function(model, newValue) { if (this.path.length == 1) model = findScope(model, this.path[0]); return this.path.setValueFrom(model, newValue); } }; function MemberExpression(object, property, accessor) { this.computed = accessor == '['; this.dynamicDeps = typeof object == 'function' || object.dynamicDeps || (this.computed && !(property instanceof Literal)); this.simplePath = !this.dynamicDeps && (property instanceof IdentPath || property instanceof Literal) && (object instanceof MemberExpression || object instanceof IdentPath); this.object = this.simplePath ? object : getFn(object); this.property = !this.computed || this.simplePath ? property : getFn(property); } MemberExpression.prototype = { get fullPath() { if (!this.fullPath_) { var parts = this.object instanceof MemberExpression ? this.object.fullPath.slice() : [this.object.name]; parts.push(this.property instanceof IdentPath ? this.property.name : this.property.value); this.fullPath_ = Path.get(parts); } return this.fullPath_; }, valueFn: function() { if (!this.valueFn_) { var object = this.object; if (this.simplePath) { var path = this.fullPath; this.valueFn_ = function(model, observer) { if (observer) observer.addPath(model, path); return path.getValueFrom(model); }; } else if (!this.computed) { var path = Path.get(this.property.name); this.valueFn_ = function(model, observer, filterRegistry) { var context = object(model, observer, filterRegistry); if (observer) observer.addPath(context, path); return path.getValueFrom(context); } } else { // Computed property. var property = this.property; this.valueFn_ = function(model, observer, filterRegistry) { var context = object(model, observer, filterRegistry); var propName = property(model, observer, filterRegistry); if (observer) observer.addPath(context, [propName]); return context ? context[propName] : undefined; }; } } return this.valueFn_; }, setValue: function(model, newValue) { if (this.simplePath) { this.fullPath.setValueFrom(model, newValue); return newValue; } var object = this.object(model); var propName = this.property instanceof IdentPath ? this.property.name : this.property(model); return object[propName] = newValue; } }; function Filter(name, args) { this.name = name; this.args = []; for (var i = 0; i < args.length; i++) { this.args[i] = getFn(args[i]); } } Filter.prototype = { transform: function(model, observer, filterRegistry, toModelDirection, initialArgs) { var fn = filterRegistry[this.name]; var context = model; if (fn) { context = undefined; } else { fn = context[this.name]; if (!fn) { console.error('Cannot find function or filter: ' + this.name); return; } } // If toModelDirection is falsey, then the "normal" (dom-bound) direction // is used. Otherwise, it looks for a 'toModel' property function on the // object. if (toModelDirection) { fn = fn.toModel; } else if (typeof fn.toDOM == 'function') { fn = fn.toDOM; } if (typeof fn != 'function') { console.error('Cannot find function or filter: ' + this.name); return; } var args = initialArgs || []; for (var i = 0; i < this.args.length; i++) { args.push(getFn(this.args[i])(model, observer, filterRegistry)); } return fn.apply(context, args); } }; function notImplemented() { throw Error('Not Implemented'); } var unaryOperators = { '+': function(v) { return +v; }, '-': function(v) { return -v; }, '!': function(v) { return !v; } }; var binaryOperators = { '+': function(l, r) { return l+r; }, '-': function(l, r) { return l-r; }, '*': function(l, r) { return l*r; }, '/': function(l, r) { return l/r; }, '%': function(l, r) { return l%r; }, '<': function(l, r) { return l<r; }, '>': function(l, r) { return l>r; }, '<=': function(l, r) { return l<=r; }, '>=': function(l, r) { return l>=r; }, '==': function(l, r) { return l==r; }, '!=': function(l, r) { return l!=r; }, '===': function(l, r) { return l===r; }, '!==': function(l, r) { return l!==r; }, '&&': function(l, r) { return l&&r; }, '||': function(l, r) { return l||r; }, }; function getFn(arg) { return typeof arg == 'function' ? arg : arg.valueFn(); } function ASTDelegate() { this.expression = null; this.filters = []; this.deps = {}; this.currentPath = undefined; this.scopeIdent = undefined; this.indexIdent = undefined; this.dynamicDeps = false; } ASTDelegate.prototype = { createUnaryExpression: function(op, argument) { if (!unaryOperators[op]) throw Error('Disallowed operator: ' + op); argument = getFn(argument); return function(model, observer, filterRegistry) { return unaryOperators[op](argument(model, observer, filterRegistry)); }; }, createBinaryExpression: function(op, left, right) { if (!binaryOperators[op]) throw Error('Disallowed operator: ' + op); left = getFn(left); right = getFn(right); switch (op) { case '||': this.dynamicDeps = true; return function(model, observer, filterRegistry) { return left(model, observer, filterRegistry) || right(model, observer, filterRegistry); }; case '&&': this.dynamicDeps = true; return function(model, observer, filterRegistry) { return left(model, observer, filterRegistry) && right(model, observer, filterRegistry); }; } return function(model, observer, filterRegistry) { return binaryOperators[op](left(model, observer, filterRegistry), right(model, observer, filterRegistry)); }; }, createConditionalExpression: function(test, consequent, alternate) { test = getFn(test); consequent = getFn(consequent); alternate = getFn(alternate); this.dynamicDeps = true; return function(model, observer, filterRegistry) { return test(model, observer, filterRegistry) ? consequent(model, observer, filterRegistry) : alternate(model, observer, filterRegistry); } }, createIdentifier: function(name) { var ident = new IdentPath(name); ident.type = 'Identifier'; return ident; }, createMemberExpression: function(accessor, object, property) { var ex = new MemberExpression(object, property, accessor); if (ex.dynamicDeps) this.dynamicDeps = true; return ex; }, createCallExpression: function(expression, args) { if (!(expression instanceof IdentPath)) throw Error('Only identifier function invocations are allowed'); var filter = new Filter(expression.name, args); return function(model, observer, filterRegistry) { return filter.transform(model, observer, filterRegistry, false); }; }, createLiteral: function(token) { return new Literal(token.value); }, createArrayExpression: function(elements) { for (var i = 0; i < elements.length; i++) elements[i] = getFn(elements[i]); return function(model, observer, filterRegistry) { var arr = [] for (var i = 0; i < elements.length; i++) arr.push(elements[i](model, observer, filterRegistry)); return arr; } }, createProperty: function(kind, key, value) { return { key: key instanceof IdentPath ? key.name : key.value, value: value }; }, createObjectExpression: function(properties) { for (var i = 0; i < properties.length; i++) properties[i].value = getFn(properties[i].value); return function(model, observer, filterRegistry) { var obj = {}; for (var i = 0; i < properties.length; i++) obj[properties[i].key] = properties[i].value(model, observer, filterRegistry); return obj; } }, createFilter: function(name, args) { this.filters.push(new Filter(name, args)); }, createAsExpression: function(expression, scopeIdent) { this.expression = expression; this.scopeIdent = scopeIdent; }, createInExpression: function(scopeIdent, indexIdent, expression) { this.expression = expression; this.scopeIdent = scopeIdent; this.indexIdent = indexIdent; }, createTopLevel: function(expression) { this.expression = expression; }, createThisExpression: notImplemented } function ConstantObservable(value) { this.value_ = value; } ConstantObservable.prototype = { open: function() { return this.value_; }, discardChanges: function() { return this.value_; }, deliver: function() {}, close: function() {}, } function Expression(delegate) { this.scopeIdent = delegate.scopeIdent; this.indexIdent = delegate.indexIdent; if (!delegate.expression) throw Error('No expression found.'); this.expression = delegate.expression; getFn(this.expression); // forces enumeration of path dependencies this.filters = delegate.filters; this.dynamicDeps = delegate.dynamicDeps; } Expression.prototype = { getBinding: function(model, filterRegistry, oneTime) { if (oneTime) return this.getValue(model, undefined, filterRegistry); var observer = new CompoundObserver(); // captures deps. var firstValue = this.getValue(model, observer, filterRegistry); var firstTime = true; var self = this; function valueFn() { // deps cannot have changed on first value retrieval. if (firstTime) { firstTime = false; return firstValue; } if (self.dynamicDeps) observer.startReset(); var value = self.getValue(model, self.dynamicDeps ? observer : undefined, filterRegistry); if (self.dynamicDeps) observer.finishReset(); return value; } function setValueFn(newValue) { self.setValue(model, newValue, filterRegistry); return newValue; } return new ObserverTransform(observer, valueFn, setValueFn, true); }, getValue: function(model, observer, filterRegistry) { var value = getFn(this.expression)(model, observer, filterRegistry); for (var i = 0; i < this.filters.length; i++) { value = this.filters[i].transform(model, observer, filterRegistry, false, [value]); } return value; }, setValue: function(model, newValue, filterRegistry) { var count = this.filters ? this.filters.length : 0; while (count-- > 0) { newValue = this.filters[count].transform(model, undefined, filterRegistry, true, [newValue]); } if (this.expression.setValue) return this.expression.setValue(model, newValue); } } /** * Converts a style property name to a css property name. For example: * "WebkitUserSelect" to "-webkit-user-select" */ function convertStylePropertyName(name) { return String(name).replace(/[A-Z]/g, function(c) { return '-' + c.toLowerCase(); }); } var parentScopeName = '@' + Math.random().toString(36).slice(2); // Single ident paths must bind directly to the appropriate scope object. // I.e. Pushed values in two-bindings need to be assigned to the actual model // object. function findScope(model, prop) { while (model[parentScopeName] && !Object.prototype.hasOwnProperty.call(model, prop)) { model = model[parentScopeName]; } return model; } function isLiteralExpression(pathString) { switch (pathString) { case '': return false; case 'false': case 'null': case 'true': return true; } if (!isNaN(Number(pathString))) return true; return false; }; function PolymerExpressions() {} PolymerExpressions.prototype = { // "built-in" filters styleObject: function(value) { var parts = []; for (var key in value) { parts.push(convertStylePropertyName(key) + ': ' + value[key]); } return parts.join('; '); }, tokenList: function(value) { var tokens = []; for (var key in value) { if (value[key]) tokens.push(key); } return tokens.join(' '); }, // binding delegate API prepareInstancePositionChanged: function(template) { var indexIdent = template.polymerExpressionIndexIdent_; if (!indexIdent) return; return function(templateInstance, index) { templateInstance.model[indexIdent] = index; }; }, prepareBinding: function(pathString, name, node) { var path = Path.get(pathString); if (!isLiteralExpression(pathString) && path.valid) { if (path.length == 1) { return function(model, node, oneTime) { if (oneTime) return path.getValueFrom(model); var scope = findScope(model, path[0]); return new PathObserver(scope, path); }; } return; // bail out early if pathString is simple path. } return prepareBinding(pathString, name, node, this); }, prepareInstanceModel: function(template) { var scopeName = template.polymerExpressionScopeIdent_; if (!scopeName) return; var parentScope = template.templateInstance ? template.templateInstance.model : template.model; var indexName = template.polymerExpressionIndexIdent_; return function(model) { return createScopeObject(parentScope, model, scopeName, indexName); }; } }; var createScopeObject = ('__proto__' in {}) ? function(parentScope, model, scopeName, indexName) { var scope = {}; scope[scopeName] = model; scope[indexName] = undefined; scope[parentScopeName] = parentScope; scope.__proto__ = parentScope; return scope; } : function(parentScope, model, scopeName, indexName) { var scope = Object.create(parentScope); Object.defineProperty(scope, scopeName, { value: model, configurable: true, writable: true }); Object.defineProperty(scope, indexName, { value: undefined, configurable: true, writable: true }); Object.defineProperty(scope, parentScopeName, { value: parentScope, configurable: true, writable: true }); return scope; }; global.PolymerExpressions = PolymerExpressions; PolymerExpressions.getExpression = getExpression; })(this); Polymer = { version: '0.5.3' }; // TODO(sorvell): this ensures Polymer is an object and not a function // Platform is currently defining it as a function to allow for async loading // of polymer; once we refine the loading process this likely goes away. if (typeof window.Polymer === 'function') { Polymer = {}; } (function(scope) { function withDependencies(task, depends) { depends = depends || []; if (!depends.map) { depends = [depends]; } return task.apply(this, depends.map(marshal)); } function module(name, dependsOrFactory, moduleFactory) { var module; switch (arguments.length) { case 0: return; case 1: module = null; break; case 2: // dependsOrFactory is `factory` in this case module = dependsOrFactory.apply(this); break; default: // dependsOrFactory is `depends` in this case module = withDependencies(moduleFactory, dependsOrFactory); break; } modules[name] = module; }; function marshal(name) { return modules[name]; } var modules = {}; function using(depends, task) { HTMLImports.whenImportsReady(function() { withDependencies(task, depends); }); }; // exports scope.marshal = marshal; // `module` confuses commonjs detectors scope.modularize = module; scope.using = using; })(window); /* Build only script. Ensures scripts needed for basic x-platform compatibility will be run when platform.js is not loaded. */ if (!window.WebComponents) { /* On supported platforms, platform.js is not needed. To retain compatibility with the polyfills, we stub out minimal functionality. */ if (!window.WebComponents) { WebComponents = { flush: function() {}, flags: {log: {}} }; Platform = WebComponents; CustomElements = { useNative: true, ready: true, takeRecords: function() {}, instanceof: function(obj, base) { return obj instanceof base; } }; HTMLImports = { useNative: true }; addEventListener('HTMLImportsLoaded', function() { document.dispatchEvent( new CustomEvent('WebComponentsReady', {bubbles: true}) ); }); // ShadowDOM ShadowDOMPolyfill = null; wrap = unwrap = function(n){ return n; }; } /* Create polyfill scope and feature detect native support. */ window.HTMLImports = window.HTMLImports || {flags:{}}; (function(scope) { /** Basic setup and simple module executer. We collect modules and then execute the code later, only if it's necessary for polyfilling. */ var IMPORT_LINK_TYPE = 'import'; var useNative = Boolean(IMPORT_LINK_TYPE in document.createElement('link')); /** Support `currentScript` on all browsers as `document._currentScript.` NOTE: We cannot polyfill `document.currentScript` because it's not possible both to override and maintain the ability to capture the native value. Therefore we choose to expose `_currentScript` both when native imports and the polyfill are in use. */ // NOTE: ShadowDOMPolyfill intrusion. var hasShadowDOMPolyfill = Boolean(window.ShadowDOMPolyfill); var wrap = function(node) { return hasShadowDOMPolyfill ? ShadowDOMPolyfill.wrapIfNeeded(node) : node; }; var rootDocument = wrap(document); var currentScriptDescriptor = { get: function() { var script = HTMLImports.currentScript || document.currentScript || // NOTE: only works when called in synchronously executing code. // readyState should check if `loading` but IE10 is // interactive when scripts run so we cheat. (document.readyState !== 'complete' ? document.scripts[document.scripts.length - 1] : null); return wrap(script); }, configurable: true }; Object.defineProperty(document, '_currentScript', currentScriptDescriptor); Object.defineProperty(rootDocument, '_currentScript', currentScriptDescriptor); /** Add support for the `HTMLImportsLoaded` event and the `HTMLImports.whenReady` method. This api is necessary because unlike the native implementation, script elements do not force imports to resolve. Instead, users should wrap code in either an `HTMLImportsLoaded` hander or after load time in an `HTMLImports.whenReady(callback)` call. NOTE: This module also supports these apis under the native implementation. Therefore, if this file is loaded, the same code can be used under both the polyfill and native implementation. */ var isIE = /Trident/.test(navigator.userAgent); // call a callback when all HTMLImports in the document at call time // (or at least document ready) have loaded. // 1. ensure the document is in a ready state (has dom), then // 2. watch for loading of imports and call callback when done function whenReady(callback, doc) { doc = doc || rootDocument; // if document is loading, wait and try again whenDocumentReady(function() { watchImportsLoad(callback, doc); }, doc); } // call the callback when the document is in a ready state (has dom) var requiredReadyState = isIE ? 'complete' : 'interactive'; var READY_EVENT = 'readystatechange'; function isDocumentReady(doc) { return (doc.readyState === 'complete' || doc.readyState === requiredReadyState); } // call <callback> when we ensure the document is in a ready state function whenDocumentReady(callback, doc) { if (!isDocumentReady(doc)) { var checkReady = function() { if (doc.readyState === 'complete' || doc.readyState === requiredReadyState) { doc.removeEventListener(READY_EVENT, checkReady); whenDocumentReady(callback, doc); } }; doc.addEventListener(READY_EVENT, checkReady); } else if (callback) { callback(); } } function markTargetLoaded(event) { event.target.__loaded = true; } // call <callback> when we ensure all imports have loaded function watchImportsLoad(callback, doc) { var imports = doc.querySelectorAll('link[rel=import]'); var loaded = 0, l = imports.length; function checkDone(d) { if ((loaded == l) && callback) { callback(); } } function loadedImport(e) { markTargetLoaded(e); loaded++; checkDone(); } if (l) { for (var i=0, imp; (i<l) && (imp=imports[i]); i++) { if (isImportLoaded(imp)) { loadedImport.call(imp, {target: imp}); } else { imp.addEventListener('load', loadedImport); imp.addEventListener('error', loadedImport); } } } else { checkDone(); } } // NOTE: test for native imports loading is based on explicitly watching // all imports (see below). // However, we cannot rely on this entirely without watching the entire document // for import links. For perf reasons, currently only head is watched. // Instead, we fallback to checking if the import property is available // and the document is not itself loading. function isImportLoaded(link) { return useNative ? link.__loaded || (link.import && link.import.readyState !== 'loading') : link.__importParsed; } // TODO(sorvell): Workaround for // https://www.w3.org/Bugs/Public/show_bug.cgi?id=25007, should be removed when // this bug is addressed. // (1) Install a mutation observer to see when HTMLImports have loaded // (2) if this script is run during document load it will watch any existing // imports for loading. // // NOTE: The workaround has restricted functionality: (1) it's only compatible // with imports that are added to document.head since the mutation observer // watches only head for perf reasons, (2) it requires this script // to run before any imports have completed loading. if (useNative) { new MutationObserver(function(mxns) { for (var i=0, l=mxns.length, m; (i < l) && (m=mxns[i]); i++) { if (m.addedNodes) { handleImports(m.addedNodes); } } }).observe(document.head, {childList: true}); function handleImports(nodes) { for (var i=0, l=nodes.length, n; (i<l) && (n=nodes[i]); i++) { if (isImport(n)) { handleImport(n); } } } function isImport(element) { return element.localName === 'link' && element.rel === 'import'; } function handleImport(element) { var loaded = element.import; if (loaded) { markTargetLoaded({target: element}); } else { element.addEventListener('load', markTargetLoaded); element.addEventListener('error', markTargetLoaded); } } // make sure to catch any imports that are in the process of loading // when this script is run. (function() { if (document.readyState === 'loading') { var imports = document.querySelectorAll('link[rel=import]'); for (var i=0, l=imports.length, imp; (i<l) && (imp=imports[i]); i++) { handleImport(imp); } } })(); } // Fire the 'HTMLImportsLoaded' event when imports in document at load time // have loaded. This event is required to simulate the script blocking // behavior of native imports. A main document script that needs to be sure // imports have loaded should wait for this event. whenReady(function() { HTMLImports.ready = true; HTMLImports.readyTime = new Date().getTime(); rootDocument.dispatchEvent( new CustomEvent('HTMLImportsLoaded', {bubbles: true}) ); }); // exports scope.IMPORT_LINK_TYPE = IMPORT_LINK_TYPE; scope.useNative = useNative; scope.rootDocument = rootDocument; scope.whenReady = whenReady; scope.isIE = isIE; })(HTMLImports); (function(scope) { // TODO(sorvell): It's desireable to provide a default stylesheet // that's convenient for styling unresolved elements, but // it's cumbersome to have to include this manually in every page. // It would make sense to put inside some HTMLImport but // the HTMLImports polyfill does not allow loading of stylesheets // that block rendering. Therefore this injection is tolerated here. var style = document.createElement('style'); style.textContent = '' + 'body {' + 'transition: opacity ease-in 0.2s;' + ' } \n' + 'body[unresolved] {' + 'opacity: 0; display: block; overflow: hidden;' + ' } \n' ; var head = document.querySelector('head'); head.insertBefore(style, head.firstChild); })(Platform); /* Build only script. Ensures scripts needed for basic x-platform compatibility will be run when platform.js is not loaded. */ } (function(global) { 'use strict'; var testingExposeCycleCount = global.testingExposeCycleCount; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); function detectEval() { // Don't test for eval if we're running in a Chrome App environment. // We check for APIs set that only exist in a Chrome App context. if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) { return false; } // Firefox OS Apps do not allow eval. This feature detection is very hacky // but even if some other platform adds support for this function this code // will continue to work. if (typeof navigator != 'undefined' && navigator.getDeviceStorage) { return false; } try { var f = new Function('', 'return true;'); return f(); } catch (ex) { return false; } } var hasEval = detectEval(); function isIndex(s) { return +s === s >>> 0 && s !== ''; } function toNumber(s) { return +s; } function isObject(obj) { return obj === Object(obj); } var numberIsNaN = global.Number.isNaN || function(value) { return typeof value === 'number' && global.isNaN(value); } function areSameValue(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; if (numberIsNaN(left) && numberIsNaN(right)) return true; return left !== left && right !== right; } var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var identStart = '[\$_a-zA-Z]'; var identPart = '[\$_a-zA-Z0-9]'; var identRegExp = new RegExp('^' + identStart + '+' + identPart + '*' + '$'); function getPathCharType(char) { if (char === undefined) return 'eof'; var code = char.charCodeAt(0); switch(code) { case 0x5B: // [ case 0x5D: // ] case 0x2E: // . case 0x22: // " case 0x27: // ' case 0x30: // 0 return char; case 0x5F: // _ case 0x24: // $ return 'ident'; case 0x20: // Space case 0x09: // Tab case 0x0A: // Newline case 0x0D: // Return case 0xA0: // No-break space case 0xFEFF: // Byte Order Mark case 0x2028: // Line Separator case 0x2029: // Paragraph Separator return 'ws'; } // a-z, A-Z if ((0x61 <= code && code <= 0x7A) || (0x41 <= code && code <= 0x5A)) return 'ident'; // 1-9 if (0x31 <= code && code <= 0x39) return 'number'; return 'else'; } var pathStateMachine = { 'beforePath': { 'ws': ['beforePath'], 'ident': ['inIdent', 'append'], '[': ['beforeElement'], 'eof': ['afterPath'] }, 'inPath': { 'ws': ['inPath'], '.': ['beforeIdent'], '[': ['beforeElement'], 'eof': ['afterPath'] }, 'beforeIdent': { 'ws': ['beforeIdent'], 'ident': ['inIdent', 'append'] }, 'inIdent': { 'ident': ['inIdent', 'append'], '0': ['inIdent', 'append'], 'number': ['inIdent', 'append'], 'ws': ['inPath', 'push'], '.': ['beforeIdent', 'push'], '[': ['beforeElement', 'push'], 'eof': ['afterPath', 'push'] }, 'beforeElement': { 'ws': ['beforeElement'], '0': ['afterZero', 'append'], 'number': ['inIndex', 'append'], "'": ['inSingleQuote', 'append', ''], '"': ['inDoubleQuote', 'append', ''] }, 'afterZero': { 'ws': ['afterElement', 'push'], ']': ['inPath', 'push'] }, 'inIndex': { '0': ['inIndex', 'append'], 'number': ['inIndex', 'append'], 'ws': ['afterElement'], ']': ['inPath', 'push'] }, 'inSingleQuote': { "'": ['afterElement'], 'eof': ['error'], 'else': ['inSingleQuote', 'append'] }, 'inDoubleQuote': { '"': ['afterElement'], 'eof': ['error'], 'else': ['inDoubleQuote', 'append'] }, 'afterElement': { 'ws': ['afterElement'], ']': ['inPath', 'push'] } } function noop() {} function parsePath(path) { var keys = []; var index = -1; var c, newChar, key, type, transition, action, typeMap, mode = 'beforePath'; var actions = { push: function() { if (key === undefined) return; keys.push(key); key = undefined; }, append: function() { if (key === undefined) key = newChar else key += newChar; } }; function maybeUnescapeQuote() { if (index >= path.length) return; var nextChar = path[index + 1]; if ((mode == 'inSingleQuote' && nextChar == "'") || (mode == 'inDoubleQuote' && nextChar == '"')) { index++; newChar = nextChar; actions.append(); return true; } } while (mode) { index++; c = path[index]; if (c == '\\' && maybeUnescapeQuote(mode)) continue; type = getPathCharType(c); typeMap = pathStateMachine[mode]; transition = typeMap[type] || typeMap['else'] || 'error'; if (transition == 'error') return; // parse error; mode = transition[0]; action = actions[transition[1]] || noop; newChar = transition[2] === undefined ? c : transition[2]; action(); if (mode === 'afterPath') { return keys; } } return; // parse error } function isIdent(s) { return identRegExp.test(s); } var constructorIsPrivate = {}; function Path(parts, privateToken) { if (privateToken !== constructorIsPrivate) throw Error('Use Path.get to retrieve path objects'); for (var i = 0; i < parts.length; i++) { this.push(String(parts[i])); } if (hasEval && this.length) { this.getValueFrom = this.compiledGetValueFromFn(); } } // TODO(rafaelw): Make simple LRU cache var pathCache = {}; function getPath(pathString) { if (pathString instanceof Path) return pathString; if (pathString == null || pathString.length == 0) pathString = ''; if (typeof pathString != 'string') { if (isIndex(pathString.length)) { // Constructed with array-like (pre-parsed) keys return new Path(pathString, constructorIsPrivate); } pathString = String(pathString); } var path = pathCache[pathString]; if (path) return path; var parts = parsePath(pathString); if (!parts) return invalidPath; var path = new Path(parts, constructorIsPrivate); pathCache[pathString] = path; return path; } Path.get = getPath; function formatAccessor(key) { if (isIndex(key)) { return '[' + key + ']'; } else { return '["' + key.replace(/"/g, '\\"') + '"]'; } } Path.prototype = createObject({ __proto__: [], valid: true, toString: function() { var pathString = ''; for (var i = 0; i < this.length; i++) { var key = this[i]; if (isIdent(key)) { pathString += i ? '.' + key : key; } else { pathString += formatAccessor(key); } } return pathString; }, getValueFrom: function(obj, directObserver) { for (var i = 0; i < this.length; i++) { if (obj == null) return; obj = obj[this[i]]; } return obj; }, iterateObjects: function(obj, observe) { for (var i = 0; i < this.length; i++) { if (i) obj = obj[this[i - 1]]; if (!isObject(obj)) return; observe(obj, this[i]); } }, compiledGetValueFromFn: function() { var str = ''; var pathString = 'obj'; str += 'if (obj != null'; var i = 0; var key; for (; i < (this.length - 1); i++) { key = this[i]; pathString += isIdent(key) ? '.' + key : formatAccessor(key); str += ' &&\n ' + pathString + ' != null'; } str += ')\n'; var key = this[i]; pathString += isIdent(key) ? '.' + key : formatAccessor(key); str += ' return ' + pathString + ';\nelse\n return undefined;'; return new Function('obj', str); }, setValueFrom: function(obj, value) { if (!this.length) return false; for (var i = 0; i < this.length - 1; i++) { if (!isObject(obj)) return false; obj = obj[this[i]]; } if (!isObject(obj)) return false; obj[this[i]] = value; return true; } }); var invalidPath = new Path('', constructorIsPrivate); invalidPath.valid = false; invalidPath.getValueFrom = invalidPath.setValueFrom = function() {}; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function diffObjectFromOldObject(object, oldObject) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (newValue !== undefined && newValue === oldObject[prop]) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ return function(fn) { return Promise.resolve().then(fn); } })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } /* * The observedSet abstraction is a perf optimization which reduces the total * number of Object.observe observations of a set of objects. The idea is that * groups of Observers will have some object dependencies in common and this * observed set ensures that each object in the transitive closure of * dependencies is only observed once. The observedSet acts as a write barrier * such that whenever any change comes through, all Observers are checked for * changed values. * * Note that this optimization is explicitly moving work from setup-time to * change-time. * * TODO(rafaelw): Implement "garbage collection". In order to move work off * the critical path, when Observers are closed, their observed objects are * not Object.unobserve(d). As a result, it's possible that if the observedSet * is kept open, but some Observers have been closed, it could cause "leaks" * (prevent otherwise collectable objects from being collected). At some * point, we should implement incremental "gc" which keeps a list of * observedSets which may need clean-up and does small amounts of cleanup on a * timeout until all is clean. */ function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var observedSetCache = []; function newObservedSet() { var observerCount = 0; var observers = []; var objects = []; var rootObj; var rootObjProps; function observe(obj, prop) { if (!obj) return; if (obj === rootObj) rootObjProps[prop] = true; if (objects.indexOf(obj) < 0) { objects.push(obj); Object.observe(obj, callback); } observe(Object.getPrototypeOf(obj), prop); } function allRootObjNonObservedProps(recs) { for (var i = 0; i < recs.length; i++) { var rec = recs[i]; if (rec.object !== rootObj || rootObjProps[rec.name] || rec.type === 'setPrototype') { return false; } } return true; } function callback(recs) { if (allRootObjNonObservedProps(recs)) return; var observer; for (var i = 0; i < observers.length; i++) { observer = observers[i]; if (observer.state_ == OPENED) { observer.iterateObjects_(observe); } } for (var i = 0; i < observers.length; i++) { observer = observers[i]; if (observer.state_ == OPENED) { observer.check_(); } } } var record = { objects: objects, get rootObject() { return rootObj; }, set rootObject(value) { rootObj = value; rootObjProps = {}; }, open: function(obs, object) { observers.push(obs); observerCount++; obs.iterateObjects_(observe); }, close: function(obs) { observerCount--; if (observerCount > 0) { return; } for (var i = 0; i < objects.length; i++) { Object.unobserve(objects[i], callback); Observer.unobservedCount++; } observers.length = 0; objects.length = 0; rootObj = undefined; rootObjProps = undefined; observedSetCache.push(this); if (lastObservedSet === this) lastObservedSet = null; }, }; return record; } var lastObservedSet; function getObservedSet(observer, obj) { if (!lastObservedSet || lastObservedSet.rootObject !== obj) { lastObservedSet = observedSetCache.pop() || newObservedSet(); lastObservedSet.rootObject = obj; } lastObservedSet.open(observer, obj); return lastObservedSet; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var RESETTING = 3; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); function ArrayObserver(array) { if (!Array.isArray(array)) throw Error('Provided object is not an Array'); ObjectObserver.call(this, array); } ArrayObserver.prototype = createObject({ __proto__: ObjectObserver.prototype, arrayObserve: true, copyObject: function(arr) { return arr.slice(); }, check_: function(changeRecords) { var splices; if (hasObserve) { if (!changeRecords) return false; splices = projectArraySplices(this.value_, changeRecords); } else { splices = calcSplices(this.value_, 0, this.value_.length, this.oldObject_, 0, this.oldObject_.length); } if (!splices || !splices.length) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([splices]); return true; } }); ArrayObserver.applySplices = function(previous, current, splices) { splices.forEach(function(splice) { var spliceArgs = [splice.index, splice.removed.length]; var addIndex = splice.index; while (addIndex < splice.index + splice.addedCount) { spliceArgs.push(current[addIndex]); addIndex++; } Array.prototype.splice.apply(previous, spliceArgs); }); }; function PathObserver(object, path) { Observer.call(this); this.object_ = object; this.path_ = getPath(path); this.directObserver_ = undefined; } PathObserver.prototype = createObject({ __proto__: Observer.prototype, get path() { return this.path_; }, connect_: function() { if (hasObserve) this.directObserver_ = getObservedSet(this, this.object_); this.check_(undefined, true); }, disconnect_: function() { this.value_ = undefined; if (this.directObserver_) { this.directObserver_.close(this); this.directObserver_ = undefined; } }, iterateObjects_: function(observe) { this.path_.iterateObjects(this.object_, observe); }, check_: function(changeRecords, skipChanges) { var oldValue = this.value_; this.value_ = this.path_.getValueFrom(this.object_); if (skipChanges || areSameValue(this.value_, oldValue)) return false; this.report_([this.value_, oldValue, this]); return true; }, setValue: function(newValue) { if (this.path_) this.path_.setValueFrom(this.object_, newValue); } }); function CompoundObserver(reportChangesOnOpen) { Observer.call(this); this.reportChangesOnOpen_ = reportChangesOnOpen; this.value_ = []; this.directObserver_ = undefined; this.observed_ = []; } var observerSentinel = {}; CompoundObserver.prototype = createObject({ __proto__: Observer.prototype, connect_: function() { if (hasObserve) { var object; var needsDirectObserver = false; for (var i = 0; i < this.observed_.length; i += 2) { object = this.observed_[i] if (object !== observerSentinel) { needsDirectObserver = true; break; } } if (needsDirectObserver) this.directObserver_ = getObservedSet(this, object); } this.check_(undefined, !this.reportChangesOnOpen_); }, disconnect_: function() { for (var i = 0; i < this.observed_.length; i += 2) { if (this.observed_[i] === observerSentinel) this.observed_[i + 1].close(); } this.observed_.length = 0; this.value_.length = 0; if (this.directObserver_) { this.directObserver_.close(this); this.directObserver_ = undefined; } }, addPath: function(object, path) { if (this.state_ != UNOPENED && this.state_ != RESETTING) throw Error('Cannot add paths once started.'); var path = getPath(path); this.observed_.push(object, path); if (!this.reportChangesOnOpen_) return; var index = this.observed_.length / 2 - 1; this.value_[index] = path.getValueFrom(object); }, addObserver: function(observer) { if (this.state_ != UNOPENED && this.state_ != RESETTING) throw Error('Cannot add observers once started.'); this.observed_.push(observerSentinel, observer); if (!this.reportChangesOnOpen_) return; var index = this.observed_.length / 2 - 1; this.value_[index] = observer.open(this.deliver, this); }, startReset: function() { if (this.state_ != OPENED) throw Error('Can only reset while open'); this.state_ = RESETTING; this.disconnect_(); }, finishReset: function() { if (this.state_ != RESETTING) throw Error('Can only finishReset after startReset'); this.state_ = OPENED; this.connect_(); return this.value_; }, iterateObjects_: function(observe) { var object; for (var i = 0; i < this.observed_.length; i += 2) { object = this.observed_[i] if (object !== observerSentinel) this.observed_[i + 1].iterateObjects(object, observe) } }, check_: function(changeRecords, skipChanges) { var oldValues; for (var i = 0; i < this.observed_.length; i += 2) { var object = this.observed_[i]; var path = this.observed_[i+1]; var value; if (object === observerSentinel) { var observable = path; value = this.state_ === UNOPENED ? observable.open(this.deliver, this) : observable.discardChanges(); } else { value = path.getValueFrom(object); } if (skipChanges) { this.value_[i / 2] = value; continue; } if (areSameValue(value, this.value_[i / 2])) continue; oldValues = oldValues || []; oldValues[i / 2] = this.value_[i / 2]; this.value_[i / 2] = value; } if (!oldValues) return false; // TODO(rafaelw): Having observed_ as the third callback arg here is // pretty lame API. Fix. this.report_([this.value_, oldValues, this.observed_]); return true; } }); function identFn(value) { return value; } function ObserverTransform(observable, getValueFn, setValueFn, dontPassThroughSet) { this.callback_ = undefined; this.target_ = undefined; this.value_ = undefined; this.observable_ = observable; this.getValueFn_ = getValueFn || identFn; this.setValueFn_ = setValueFn || identFn; // TODO(rafaelw): This is a temporary hack. PolymerExpressions needs this // at the moment because of a bug in it's dependency tracking. this.dontPassThroughSet_ = dontPassThroughSet; } ObserverTransform.prototype = { open: function(callback, target) { this.callback_ = callback; this.target_ = target; this.value_ = this.getValueFn_(this.observable_.open(this.observedCallback_, this)); return this.value_; }, observedCallback_: function(value) { value = this.getValueFn_(value); if (areSameValue(value, this.value_)) return; var oldValue = this.value_; this.value_ = value; this.callback_.call(this.target_, this.value_, oldValue); }, discardChanges: function() { this.value_ = this.getValueFn_(this.observable_.discardChanges()); return this.value_; }, deliver: function() { return this.observable_.deliver(); }, setValue: function(value) { value = this.setValueFn_(value); if (!this.dontPassThroughSet_ && this.observable_.setValue) return this.observable_.setValue(value); }, close: function() { if (this.observable_) this.observable_.close(); this.callback_ = undefined; this.target_ = undefined; this.observable_ = undefined; this.value_ = undefined; this.getValueFn_ = undefined; this.setValueFn_ = undefined; } } var expectedRecordTypes = { add: true, update: true, delete: true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } function newSplice(index, removed, addedCount) { return { index: index, removed: removed, addedCount: addedCount }; } var EDIT_LEAVE = 0; var EDIT_UPDATE = 1; var EDIT_ADD = 2; var EDIT_DELETE = 3; function ArraySplice() {} ArraySplice.prototype = { // Note: This function is *based* on the computation of the Levenshtein // "edit" distance. The one change is that "updates" are treated as two // edits - not one. With Array splices, an update is really a delete // followed by an add. By retaining this, we optimize for "keeping" the // maximum array items in the original array. For example: // // 'xxxx123' -> '123yyyy' // // With 1-edit updates, the shortest path would be just to update all seven // characters. With 2-edit updates, we delete 4, leave 3, and add 4. This // leaves the substring '123' intact. calcEditDistances: function(current, currentStart, currentEnd, old, oldStart, oldEnd) { // "Deletion" columns var rowCount = oldEnd - oldStart + 1; var columnCount = currentEnd - currentStart + 1; var distances = new Array(rowCount); // "Addition" rows. Initialize null column. for (var i = 0; i < rowCount; i++) { distances[i] = new Array(columnCount); distances[i][0] = i; } // Initialize null row for (var j = 0; j < columnCount; j++) distances[0][j] = j; for (var i = 1; i < rowCount; i++) { for (var j = 1; j < columnCount; j++) { if (this.equals(current[currentStart + j - 1], old[oldStart + i - 1])) distances[i][j] = distances[i - 1][j - 1]; else { var north = distances[i - 1][j] + 1; var west = distances[i][j - 1] + 1; distances[i][j] = north < west ? north : west; } } } return distances; }, // This starts at the final weight, and walks "backward" by finding // the minimum previous weight recursively until the origin of the weight // matrix. spliceOperationsFromEditDistances: function(distances) { var i = distances.length - 1; var j = distances[0].length - 1; var current = distances[i][j]; var edits = []; while (i > 0 || j > 0) { if (i == 0) { edits.push(EDIT_ADD); j--; continue; } if (j == 0) { edits.push(EDIT_DELETE); i--; continue; } var northWest = distances[i - 1][j - 1]; var west = distances[i - 1][j]; var north = distances[i][j - 1]; var min; if (west < north) min = west < northWest ? west : northWest; else min = north < northWest ? north : northWest; if (min == northWest) { if (northWest == current) { edits.push(EDIT_LEAVE); } else { edits.push(EDIT_UPDATE); current = northWest; } i--; j--; } else if (min == west) { edits.push(EDIT_DELETE); i--; current = west; } else { edits.push(EDIT_ADD); j--; current = north; } } edits.reverse(); return edits; }, /** * Splice Projection functions: * * A splice map is a representation of how a previous array of items * was transformed into a new array of items. Conceptually it is a list of * tuples of * * <index, removed, addedCount> * * which are kept in ascending index order of. The tuple represents that at * the |index|, |removed| sequence of items were removed, and counting forward * from |index|, |addedCount| items were added. */ /** * Lacking individual splice mutation information, the minimal set of * splices can be synthesized given the previous state and final state of an * array. The basic approach is to calculate the edit distance matrix and * choose the shortest path through it. * * Complexity: O(l * p) * l: The length of the current array * p: The length of the old array */ calcSplices: function(current, currentStart, currentEnd, old, oldStart, oldEnd) { var prefixCount = 0; var suffixCount = 0; var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); if (currentStart == 0 && oldStart == 0) prefixCount = this.sharedPrefix(current, old, minLength); if (currentEnd == current.length && oldEnd == old.length) suffixCount = this.sharedSuffix(current, old, minLength - prefixCount); currentStart += prefixCount; oldStart += prefixCount; currentEnd -= suffixCount; oldEnd -= suffixCount; if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) return []; if (currentStart == currentEnd) { var splice = newSplice(currentStart, [], 0); while (oldStart < oldEnd) splice.removed.push(old[oldStart++]); return [ splice ]; } else if (oldStart == oldEnd) return [ newSplice(currentStart, [], currentEnd - currentStart) ]; var ops = this.spliceOperationsFromEditDistances( this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd)); var splice = undefined; var splices = []; var index = currentStart; var oldIndex = oldStart; for (var i = 0; i < ops.length; i++) { switch(ops[i]) { case EDIT_LEAVE: if (splice) { splices.push(splice); splice = undefined; } index++; oldIndex++; break; case EDIT_UPDATE: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; splice.removed.push(old[oldIndex]); oldIndex++; break; case EDIT_ADD: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; break; case EDIT_DELETE: if (!splice) splice = newSplice(index, [], 0); splice.removed.push(old[oldIndex]); oldIndex++; break; } } if (splice) { splices.push(splice); } return splices; }, sharedPrefix: function(current, old, searchLength) { for (var i = 0; i < searchLength; i++) if (!this.equals(current[i], old[i])) return i; return searchLength; }, sharedSuffix: function(current, old, searchLength) { var index1 = current.length; var index2 = old.length; var count = 0; while (count < searchLength && this.equals(current[--index1], old[--index2])) count++; return count; }, calculateSplices: function(current, previous) { return this.calcSplices(current, 0, current.length, previous, 0, previous.length); }, equals: function(currentValue, previousValue) { return currentValue === previousValue; } }; var arraySplice = new ArraySplice(); function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) { return arraySplice.calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd); } function intersect(start1, end1, start2, end2) { // Disjoint if (end1 < start2 || end2 < start1) return -1; // Adjacent if (end1 == start2 || end2 == start1) return 0; // Non-zero intersect, span1 first if (start1 < start2) { if (end1 < end2) return end1 - start2; // Overlap else return end2 - start2; // Contained } else { // Non-zero intersect, span2 first if (end2 < end1) return end2 - start1; // Overlap else return end1 - start1; // Contained } } function mergeSplice(splices, index, removed, addedCount) { var splice = newSplice(index, removed, addedCount); var inserted = false; var insertionOffset = 0; for (var i = 0; i < splices.length; i++) { var current = splices[i]; current.index += insertionOffset; if (inserted) continue; var intersectCount = intersect(splice.index, splice.index + splice.removed.length, current.index, current.index + current.addedCount); if (intersectCount >= 0) { // Merge the two splices splices.splice(i, 1); i--; insertionOffset -= current.addedCount - current.removed.length; splice.addedCount += current.addedCount - intersectCount; var deleteCount = splice.removed.length + current.removed.length - intersectCount; if (!splice.addedCount && !deleteCount) { // merged splice is a noop. discard. inserted = true; } else { var removed = current.removed; if (splice.index < current.index) { // some prefix of splice.removed is prepended to current.removed. var prepend = splice.removed.slice(0, current.index - splice.index); Array.prototype.push.apply(prepend, removed); removed = prepend; } if (splice.index + splice.removed.length > current.index + current.addedCount) { // some suffix of splice.removed is appended to current.removed. var append = splice.removed.slice(current.index + current.addedCount - splice.index); Array.prototype.push.apply(removed, append); } splice.removed = removed; if (current.index < splice.index) { splice.index = current.index; } } } else if (splice.index < current.index) { // Insert splice here. inserted = true; splices.splice(i, 0, splice); i++; var offset = splice.addedCount - splice.removed.length current.index += offset; insertionOffset += offset; } } if (!inserted) splices.push(splice); } function createInitialSplices(array, changeRecords) { var splices = []; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; switch(record.type) { case 'splice': mergeSplice(splices, record.index, record.removed.slice(), record.addedCount); break; case 'add': case 'update': case 'delete': if (!isIndex(record.name)) continue; var index = toNumber(record.name); if (index < 0) continue; mergeSplice(splices, index, [record.oldValue], 1); break; default: console.error('Unexpected record type: ' + JSON.stringify(record)); break; } } return splices; } function projectArraySplices(array, changeRecords) { var splices = []; createInitialSplices(array, changeRecords).forEach(function(splice) { if (splice.addedCount == 1 && splice.removed.length == 1) { if (splice.removed[0] !== array[splice.index]) splices.push(splice); return }; splices = splices.concat(calcSplices(array, splice.index, splice.index + splice.addedCount, splice.removed, 0, splice.removed.length)); }); return splices; } // Export the observe-js object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, export as a global object. var expose = global; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { expose = exports = module.exports; } expose = exports; } expose.Observer = Observer; expose.Observer.runEOM_ = runEOM; expose.Observer.observerSentinel_ = observerSentinel; // for testing. expose.Observer.hasObjectObserve = hasObserve; expose.ArrayObserver = ArrayObserver; expose.ArrayObserver.calculateSplices = function(current, previous) { return arraySplice.calculateSplices(current, previous); }; expose.ArraySplice = ArraySplice; expose.ObjectObserver = ObjectObserver; expose.PathObserver = PathObserver; expose.CompoundObserver = CompoundObserver; expose.Path = Path; expose.ObserverTransform = ObserverTransform; })(typeof global !== 'undefined' && global && typeof module !== 'undefined' && module ? global : this || window); // Copyright (c) 2014 The Polymer Project Authors. All rights reserved. // This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt // The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt // The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt // Code distributed by Google as part of the polymer project is also // subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt (function(global) { 'use strict'; var filter = Array.prototype.filter.call.bind(Array.prototype.filter); function getTreeScope(node) { while (node.parentNode) { node = node.parentNode; } return typeof node.getElementById === 'function' ? node : null; } Node.prototype.bind = function(name, observable) { console.error('Unhandled binding to Node: ', this, name, observable); }; Node.prototype.bindFinished = function() {}; function updateBindings(node, name, binding) { var bindings = node.bindings_; if (!bindings) bindings = node.bindings_ = {}; if (bindings[name]) binding[name].close(); return bindings[name] = binding; } function returnBinding(node, name, binding) { return binding; } function sanitizeValue(value) { return value == null ? '' : value; } function updateText(node, value) { node.data = sanitizeValue(value); } function textBinding(node) { return function(value) { return updateText(node, value); }; } var maybeUpdateBindings = returnBinding; Object.defineProperty(Platform, 'enableBindingsReflection', { get: function() { return maybeUpdateBindings === updateBindings; }, set: function(enable) { maybeUpdateBindings = enable ? updateBindings : returnBinding; return enable; }, configurable: true }); Text.prototype.bind = function(name, value, oneTime) { if (name !== 'textContent') return Node.prototype.bind.call(this, name, value, oneTime); if (oneTime) return updateText(this, value); var observable = value; updateText(this, observable.open(textBinding(this))); return maybeUpdateBindings(this, name, observable); } function updateAttribute(el, name, conditional, value) { if (conditional) { if (value) el.setAttribute(name, ''); else el.removeAttribute(name); return; } el.setAttribute(name, sanitizeValue(value)); } function attributeBinding(el, name, conditional) { return function(value) { updateAttribute(el, name, conditional, value); }; } Element.prototype.bind = function(name, value, oneTime) { var conditional = name[name.length - 1] == '?'; if (conditional) { this.removeAttribute(name); name = name.slice(0, -1); } if (oneTime) return updateAttribute(this, name, conditional, value); var observable = value; updateAttribute(this, name, conditional, observable.open(attributeBinding(this, name, conditional))); return maybeUpdateBindings(this, name, observable); }; var checkboxEventType; (function() { // Attempt to feature-detect which event (change or click) is fired first // for checkboxes. var div = document.createElement('div'); var checkbox = div.appendChild(document.createElement('input')); checkbox.setAttribute('type', 'checkbox'); var first; var count = 0; checkbox.addEventListener('click', function(e) { count++; first = first || 'click'; }); checkbox.addEventListener('change', function() { count++; first = first || 'change'; }); var event = document.createEvent('MouseEvent'); event.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); checkbox.dispatchEvent(event); // WebKit/Blink don't fire the change event if the element is outside the // document, so assume 'change' for that case. checkboxEventType = count == 1 ? 'change' : first; })(); function getEventForInputType(element) { switch (element.type) { case 'checkbox': return checkboxEventType; case 'radio': case 'select-multiple': case 'select-one': return 'change'; case 'range': if (/Trident|MSIE/.test(navigator.userAgent)) return 'change'; default: return 'input'; } } function updateInput(input, property, value, santizeFn) { input[property] = (santizeFn || sanitizeValue)(value); } function inputBinding(input, property, santizeFn) { return function(value) { return updateInput(input, property, value, santizeFn); } } function noop() {} function bindInputEvent(input, property, observable, postEventFn) { var eventType = getEventForInputType(input); function eventHandler() { observable.setValue(input[property]); observable.discardChanges(); (postEventFn || noop)(input); Platform.performMicrotaskCheckpoint(); } input.addEventListener(eventType, eventHandler); return { close: function() { input.removeEventListener(eventType, eventHandler); observable.close(); }, observable_: observable } } function booleanSanitize(value) { return Boolean(value); } // |element| is assumed to be an HTMLInputElement with |type| == 'radio'. // Returns an array containing all radio buttons other than |element| that // have the same |name|, either in the form that |element| belongs to or, // if no form, in the document tree to which |element| belongs. // // This implementation is based upon the HTML spec definition of a // "radio button group": // http://www.whatwg.org/specs/web-apps/current-work/multipage/number-state.html#radio-button-group // function getAssociatedRadioButtons(element) { if (element.form) { return filter(element.form.elements, function(el) { return el != element && el.tagName == 'INPUT' && el.type == 'radio' && el.name == element.name; }); } else { var treeScope = getTreeScope(element); if (!treeScope) return []; var radios = treeScope.querySelectorAll( 'input[type="radio"][name="' + element.name + '"]'); return filter(radios, function(el) { return el != element && !el.form; }); } } function checkedPostEvent(input) { // Only the radio button that is getting checked gets an event. We // therefore find all the associated radio buttons and update their // check binding manually. if (input.tagName === 'INPUT' && input.type === 'radio') { getAssociatedRadioButtons(input).forEach(function(radio) { var checkedBinding = radio.bindings_.checked; if (checkedBinding) { // Set the value directly to avoid an infinite call stack. checkedBinding.observable_.setValue(false); } }); } } HTMLInputElement.prototype.bind = function(name, value, oneTime) { if (name !== 'value' && name !== 'checked') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute(name); var sanitizeFn = name == 'checked' ? booleanSanitize : sanitizeValue; var postEventFn = name == 'checked' ? checkedPostEvent : noop; if (oneTime) return updateInput(this, name, value, sanitizeFn); var observable = value; var binding = bindInputEvent(this, name, observable, postEventFn); updateInput(this, name, observable.open(inputBinding(this, name, sanitizeFn)), sanitizeFn); // Checkboxes may need to update bindings of other checkboxes. return updateBindings(this, name, binding); } HTMLTextAreaElement.prototype.bind = function(name, value, oneTime) { if (name !== 'value') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute('value'); if (oneTime) return updateInput(this, 'value', value); var observable = value; var binding = bindInputEvent(this, 'value', observable); updateInput(this, 'value', observable.open(inputBinding(this, 'value', sanitizeValue))); return maybeUpdateBindings(this, name, binding); } function updateOption(option, value) { var parentNode = option.parentNode;; var select; var selectBinding; var oldValue; if (parentNode instanceof HTMLSelectElement && parentNode.bindings_ && parentNode.bindings_.value) { select = parentNode; selectBinding = select.bindings_.value; oldValue = select.value; } option.value = sanitizeValue(value); if (select && select.value != oldValue) { selectBinding.observable_.setValue(select.value); selectBinding.observable_.discardChanges(); Platform.performMicrotaskCheckpoint(); } } function optionBinding(option) { return function(value) { updateOption(option, value); } } HTMLOptionElement.prototype.bind = function(name, value, oneTime) { if (name !== 'value') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute('value'); if (oneTime) return updateOption(this, value); var observable = value; var binding = bindInputEvent(this, 'value', observable); updateOption(this, observable.open(optionBinding(this))); return maybeUpdateBindings(this, name, binding); } HTMLSelectElement.prototype.bind = function(name, value, oneTime) { if (name === 'selectedindex') name = 'selectedIndex'; if (name !== 'selectedIndex' && name !== 'value') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute(name); if (oneTime) return updateInput(this, name, value); var observable = value; var binding = bindInputEvent(this, name, observable); updateInput(this, name, observable.open(inputBinding(this, name))); // Option update events may need to access select bindings. return updateBindings(this, name, binding); } })(this); // Copyright (c) 2014 The Polymer Project Authors. All rights reserved. // This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt // The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt // The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt // Code distributed by Google as part of the polymer project is also // subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt (function(global) { 'use strict'; function assert(v) { if (!v) throw new Error('Assertion failed'); } var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); function getFragmentRoot(node) { var p; while (p = node.parentNode) { node = p; } return node; } function searchRefId(node, id) { if (!id) return; var ref; var selector = '#' + id; while (!ref) { node = getFragmentRoot(node); if (node.protoContent_) ref = node.protoContent_.querySelector(selector); else if (node.getElementById) ref = node.getElementById(id); if (ref || !node.templateCreator_) break node = node.templateCreator_; } return ref; } function getInstanceRoot(node) { while (node.parentNode) { node = node.parentNode; } return node.templateCreator_ ? node : null; } var Map; if (global.Map && typeof global.Map.prototype.forEach === 'function') { Map = global.Map; } else { Map = function() { this.keys = []; this.values = []; }; Map.prototype = { set: function(key, value) { var index = this.keys.indexOf(key); if (index < 0) { this.keys.push(key); this.values.push(value); } else { this.values[index] = value; } }, get: function(key) { var index = this.keys.indexOf(key); if (index < 0) return; return this.values[index]; }, delete: function(key, value) { var index = this.keys.indexOf(key); if (index < 0) return false; this.keys.splice(index, 1); this.values.splice(index, 1); return true; }, forEach: function(f, opt_this) { for (var i = 0; i < this.keys.length; i++) f.call(opt_this || this, this.values[i], this.keys[i], this); } }; } // JScript does not have __proto__. We wrap all object literals with // createObject which uses Object.create, Object.defineProperty and // Object.getOwnPropertyDescriptor to create a new object that does the exact // same thing. The main downside to this solution is that we have to extract // all those property descriptors for IE. var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; // IE does not support have Document.prototype.contains. if (typeof document.contains != 'function') { Document.prototype.contains = function(node) { if (node === this || node.parentNode === this) return true; return this.documentElement.contains(node); } } var BIND = 'bind'; var REPEAT = 'repeat'; var IF = 'if'; var templateAttributeDirectives = { 'template': true, 'repeat': true, 'bind': true, 'ref': true, 'if': true }; var semanticTemplateElements = { 'THEAD': true, 'TBODY': true, 'TFOOT': true, 'TH': true, 'TR': true, 'TD': true, 'COLGROUP': true, 'COL': true, 'CAPTION': true, 'OPTION': true, 'OPTGROUP': true }; var hasTemplateElement = typeof HTMLTemplateElement !== 'undefined'; if (hasTemplateElement) { // TODO(rafaelw): Remove when fix for // https://codereview.chromium.org/164803002/ // makes it to Chrome release. (function() { var t = document.createElement('template'); var d = t.content.ownerDocument; var html = d.appendChild(d.createElement('html')); var head = html.appendChild(d.createElement('head')); var base = d.createElement('base'); base.href = document.baseURI; head.appendChild(base); })(); } var allTemplatesSelectors = 'template, ' + Object.keys(semanticTemplateElements).map(function(tagName) { return tagName.toLowerCase() + '[template]'; }).join(', '); function isSVGTemplate(el) { return el.tagName == 'template' && el.namespaceURI == 'http://www.w3.org/2000/svg'; } function isHTMLTemplate(el) { return el.tagName == 'TEMPLATE' && el.namespaceURI == 'http://www.w3.org/1999/xhtml'; } function isAttributeTemplate(el) { return Boolean(semanticTemplateElements[el.tagName] && el.hasAttribute('template')); } function isTemplate(el) { if (el.isTemplate_ === undefined) el.isTemplate_ = el.tagName == 'TEMPLATE' || isAttributeTemplate(el); return el.isTemplate_; } // FIXME: Observe templates being added/removed from documents // FIXME: Expose imperative API to decorate and observe templates in // "disconnected tress" (e.g. ShadowRoot) document.addEventListener('DOMContentLoaded', function(e) { bootstrapTemplatesRecursivelyFrom(document); // FIXME: Is this needed? Seems like it shouldn't be. Platform.performMicrotaskCheckpoint(); }, false); function forAllTemplatesFrom(node, fn) { var subTemplates = node.querySelectorAll(allTemplatesSelectors); if (isTemplate(node)) fn(node) forEach(subTemplates, fn); } function bootstrapTemplatesRecursivelyFrom(node) { function bootstrap(template) { if (!HTMLTemplateElement.decorate(template)) bootstrapTemplatesRecursivelyFrom(template.content); } forAllTemplatesFrom(node, bootstrap); } if (!hasTemplateElement) { /** * This represents a <template> element. * @constructor * @extends {HTMLElement} */ global.HTMLTemplateElement = function() { throw TypeError('Illegal constructor'); }; } var hasProto = '__proto__' in {}; function mixin(to, from) { Object.getOwnPropertyNames(from).forEach(function(name) { Object.defineProperty(to, name, Object.getOwnPropertyDescriptor(from, name)); }); } // http://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/templates/index.html#dfn-template-contents-owner function getOrCreateTemplateContentsOwner(template) { var doc = template.ownerDocument if (!doc.defaultView) return doc; var d = doc.templateContentsOwner_; if (!d) { // TODO(arv): This should either be a Document or HTMLDocument depending // on doc. d = doc.implementation.createHTMLDocument(''); while (d.lastChild) { d.removeChild(d.lastChild); } doc.templateContentsOwner_ = d; } return d; } function getTemplateStagingDocument(template) { if (!template.stagingDocument_) { var owner = template.ownerDocument; if (!owner.stagingDocument_) { owner.stagingDocument_ = owner.implementation.createHTMLDocument(''); owner.stagingDocument_.isStagingDocument = true; // TODO(rafaelw): Remove when fix for // https://codereview.chromium.org/164803002/ // makes it to Chrome release. var base = owner.stagingDocument_.createElement('base'); base.href = document.baseURI; owner.stagingDocument_.head.appendChild(base); owner.stagingDocument_.stagingDocument_ = owner.stagingDocument_; } template.stagingDocument_ = owner.stagingDocument_; } return template.stagingDocument_; } // For non-template browsers, the parser will disallow <template> in certain // locations, so we allow "attribute templates" which combine the template // element with the top-level container node of the content, e.g. // // <tr template repeat="{{ foo }}"" class="bar"><td>Bar</td></tr> // // becomes // // <template repeat="{{ foo }}"> // + #document-fragment // + <tr class="bar"> // + <td>Bar</td> // function extractTemplateFromAttributeTemplate(el) { var template = el.ownerDocument.createElement('template'); el.parentNode.insertBefore(template, el); var attribs = el.attributes; var count = attribs.length; while (count-- > 0) { var attrib = attribs[count]; if (templateAttributeDirectives[attrib.name]) { if (attrib.name !== 'template') template.setAttribute(attrib.name, attrib.value); el.removeAttribute(attrib.name); } } return template; } function extractTemplateFromSVGTemplate(el) { var template = el.ownerDocument.createElement('template'); el.parentNode.insertBefore(template, el); var attribs = el.attributes; var count = attribs.length; while (count-- > 0) { var attrib = attribs[count]; template.setAttribute(attrib.name, attrib.value); el.removeAttribute(attrib.name); } el.parentNode.removeChild(el); return template; } function liftNonNativeTemplateChildrenIntoContent(template, el, useRoot) { var content = template.content; if (useRoot) { content.appendChild(el); return; } var child; while (child = el.firstChild) { content.appendChild(child); } } var templateObserver; if (typeof MutationObserver == 'function') { templateObserver = new MutationObserver(function(records) { for (var i = 0; i < records.length; i++) { records[i].target.refChanged_(); } }); } /** * Ensures proper API and content model for template elements. * @param {HTMLTemplateElement} opt_instanceRef The template element which * |el| template element will return as the value of its ref(), and whose * content will be used as source when createInstance() is invoked. */ HTMLTemplateElement.decorate = function(el, opt_instanceRef) { if (el.templateIsDecorated_) return false; var templateElement = el; templateElement.templateIsDecorated_ = true; var isNativeHTMLTemplate = isHTMLTemplate(templateElement) && hasTemplateElement; var bootstrapContents = isNativeHTMLTemplate; var liftContents = !isNativeHTMLTemplate; var liftRoot = false; if (!isNativeHTMLTemplate) { if (isAttributeTemplate(templateElement)) { assert(!opt_instanceRef); templateElement = extractTemplateFromAttributeTemplate(el); templateElement.templateIsDecorated_ = true; isNativeHTMLTemplate = hasTemplateElement; liftRoot = true; } else if (isSVGTemplate(templateElement)) { templateElement = extractTemplateFromSVGTemplate(el); templateElement.templateIsDecorated_ = true; isNativeHTMLTemplate = hasTemplateElement; } } if (!isNativeHTMLTemplate) { fixTemplateElementPrototype(templateElement); var doc = getOrCreateTemplateContentsOwner(templateElement); templateElement.content_ = doc.createDocumentFragment(); } if (opt_instanceRef) { // template is contained within an instance, its direct content must be // empty templateElement.instanceRef_ = opt_instanceRef; } else if (liftContents) { liftNonNativeTemplateChildrenIntoContent(templateElement, el, liftRoot); } else if (bootstrapContents) { bootstrapTemplatesRecursivelyFrom(templateElement.content); } return true; }; // TODO(rafaelw): This used to decorate recursively all templates from a given // node. This happens by default on 'DOMContentLoaded', but may be needed // in subtrees not descendent from document (e.g. ShadowRoot). // Review whether this is the right public API. HTMLTemplateElement.bootstrap = bootstrapTemplatesRecursivelyFrom; var htmlElement = global.HTMLUnknownElement || HTMLElement; var contentDescriptor = { get: function() { return this.content_; }, enumerable: true, configurable: true }; if (!hasTemplateElement) { // Gecko is more picky with the prototype than WebKit. Make sure to use the // same prototype as created in the constructor. HTMLTemplateElement.prototype = Object.create(htmlElement.prototype); Object.defineProperty(HTMLTemplateElement.prototype, 'content', contentDescriptor); } function fixTemplateElementPrototype(el) { if (hasProto) el.__proto__ = HTMLTemplateElement.prototype; else mixin(el, HTMLTemplateElement.prototype); } function ensureSetModelScheduled(template) { if (!template.setModelFn_) { template.setModelFn_ = function() { template.setModelFnScheduled_ = false; var map = getBindings(template, template.delegate_ && template.delegate_.prepareBinding); processBindings(template, map, template.model_); }; } if (!template.setModelFnScheduled_) { template.setModelFnScheduled_ = true; Observer.runEOM_(template.setModelFn_); } } mixin(HTMLTemplateElement.prototype, { bind: function(name, value, oneTime) { if (name != 'ref') return Element.prototype.bind.call(this, name, value, oneTime); var self = this; var ref = oneTime ? value : value.open(function(ref) { self.setAttribute('ref', ref); self.refChanged_(); }); this.setAttribute('ref', ref); this.refChanged_(); if (oneTime) return; if (!this.bindings_) { this.bindings_ = { ref: value }; } else { this.bindings_.ref = value; } return value; }, processBindingDirectives_: function(directives) { if (this.iterator_) this.iterator_.closeDeps(); if (!directives.if && !directives.bind && !directives.repeat) { if (this.iterator_) { this.iterator_.close(); this.iterator_ = undefined; } return; } if (!this.iterator_) { this.iterator_ = new TemplateIterator(this); } this.iterator_.updateDependencies(directives, this.model_); if (templateObserver) { templateObserver.observe(this, { attributes: true, attributeFilter: ['ref'] }); } return this.iterator_; }, createInstance: function(model, bindingDelegate, delegate_) { if (bindingDelegate) delegate_ = this.newDelegate_(bindingDelegate); else if (!delegate_) delegate_ = this.delegate_; if (!this.refContent_) this.refContent_ = this.ref_.content; var content = this.refContent_; if (content.firstChild === null) return emptyInstance; var map = getInstanceBindingMap(content, delegate_); var stagingDocument = getTemplateStagingDocument(this); var instance = stagingDocument.createDocumentFragment(); instance.templateCreator_ = this; instance.protoContent_ = content; instance.bindings_ = []; instance.terminator_ = null; var instanceRecord = instance.templateInstance_ = { firstNode: null, lastNode: null, model: model }; var i = 0; var collectTerminator = false; for (var child = content.firstChild; child; child = child.nextSibling) { // The terminator of the instance is the clone of the last child of the // content. If the last child is an active template, it may produce // instances as a result of production, so simply collecting the last // child of the instance after it has finished producing may be wrong. if (child.nextSibling === null) collectTerminator = true; var clone = cloneAndBindInstance(child, instance, stagingDocument, map.children[i++], model, delegate_, instance.bindings_); clone.templateInstance_ = instanceRecord; if (collectTerminator) instance.terminator_ = clone; } instanceRecord.firstNode = instance.firstChild; instanceRecord.lastNode = instance.lastChild; instance.templateCreator_ = undefined; instance.protoContent_ = undefined; return instance; }, get model() { return this.model_; }, set model(model) { this.model_ = model; ensureSetModelScheduled(this); }, get bindingDelegate() { return this.delegate_ && this.delegate_.raw; }, refChanged_: function() { if (!this.iterator_ || this.refContent_ === this.ref_.content) return; this.refContent_ = undefined; this.iterator_.valueChanged(); this.iterator_.updateIteratedValue(this.iterator_.getUpdatedValue()); }, clear: function() { this.model_ = undefined; this.delegate_ = undefined; if (this.bindings_ && this.bindings_.ref) this.bindings_.ref.close() this.refContent_ = undefined; if (!this.iterator_) return; this.iterator_.valueChanged(); this.iterator_.close() this.iterator_ = undefined; }, setDelegate_: function(delegate) { this.delegate_ = delegate; this.bindingMap_ = undefined; if (this.iterator_) { this.iterator_.instancePositionChangedFn_ = undefined; this.iterator_.instanceModelFn_ = undefined; } }, newDelegate_: function(bindingDelegate) { if (!bindingDelegate) return; function delegateFn(name) { var fn = bindingDelegate && bindingDelegate[name]; if (typeof fn != 'function') return; return function() { return fn.apply(bindingDelegate, arguments); }; } return { bindingMaps: {}, raw: bindingDelegate, prepareBinding: delegateFn('prepareBinding'), prepareInstanceModel: delegateFn('prepareInstanceModel'), prepareInstancePositionChanged: delegateFn('prepareInstancePositionChanged') }; }, set bindingDelegate(bindingDelegate) { if (this.delegate_) { throw Error('Template must be cleared before a new bindingDelegate ' + 'can be assigned'); } this.setDelegate_(this.newDelegate_(bindingDelegate)); }, get ref_() { var ref = searchRefId(this, this.getAttribute('ref')); if (!ref) ref = this.instanceRef_; if (!ref) return this; var nextRef = ref.ref_; return nextRef ? nextRef : ref; } }); // Returns // a) undefined if there are no mustaches. // b) [TEXT, (ONE_TIME?, PATH, DELEGATE_FN, TEXT)+] if there is at least one mustache. function parseMustaches(s, name, node, prepareBindingFn) { if (!s || !s.length) return; var tokens; var length = s.length; var startIndex = 0, lastIndex = 0, endIndex = 0; var onlyOneTime = true; while (lastIndex < length) { var startIndex = s.indexOf('{{', lastIndex); var oneTimeStart = s.indexOf('[[', lastIndex); var oneTime = false; var terminator = '}}'; if (oneTimeStart >= 0 && (startIndex < 0 || oneTimeStart < startIndex)) { startIndex = oneTimeStart; oneTime = true; terminator = ']]'; } endIndex = startIndex < 0 ? -1 : s.indexOf(terminator, startIndex + 2); if (endIndex < 0) { if (!tokens) return; tokens.push(s.slice(lastIndex)); // TEXT break; } tokens = tokens || []; tokens.push(s.slice(lastIndex, startIndex)); // TEXT var pathString = s.slice(startIndex + 2, endIndex).trim(); tokens.push(oneTime); // ONE_TIME? onlyOneTime = onlyOneTime && oneTime; var delegateFn = prepareBindingFn && prepareBindingFn(pathString, name, node); // Don't try to parse the expression if there's a prepareBinding function if (delegateFn == null) { tokens.push(Path.get(pathString)); // PATH } else { tokens.push(null); } tokens.push(delegateFn); // DELEGATE_FN lastIndex = endIndex + 2; } if (lastIndex === length) tokens.push(''); // TEXT tokens.hasOnePath = tokens.length === 5; tokens.isSimplePath = tokens.hasOnePath && tokens[0] == '' && tokens[4] == ''; tokens.onlyOneTime = onlyOneTime; tokens.combinator = function(values) { var newValue = tokens[0]; for (var i = 1; i < tokens.length; i += 4) { var value = tokens.hasOnePath ? values : values[(i - 1) / 4]; if (value !== undefined) newValue += value; newValue += tokens[i + 3]; } return newValue; } return tokens; }; function processOneTimeBinding(name, tokens, node, model) { if (tokens.hasOnePath) { var delegateFn = tokens[3]; var value = delegateFn ? delegateFn(model, node, true) : tokens[2].getValueFrom(model); return tokens.isSimplePath ? value : tokens.combinator(value); } var values = []; for (var i = 1; i < tokens.length; i += 4) { var delegateFn = tokens[i + 2]; values[(i - 1) / 4] = delegateFn ? delegateFn(model, node) : tokens[i + 1].getValueFrom(model); } return tokens.combinator(values); } function processSinglePathBinding(name, tokens, node, model) { var delegateFn = tokens[3]; var observer = delegateFn ? delegateFn(model, node, false) : new PathObserver(model, tokens[2]); return tokens.isSimplePath ? observer : new ObserverTransform(observer, tokens.combinator); } function processBinding(name, tokens, node, model) { if (tokens.onlyOneTime) return processOneTimeBinding(name, tokens, node, model); if (tokens.hasOnePath) return processSinglePathBinding(name, tokens, node, model); var observer = new CompoundObserver(); for (var i = 1; i < tokens.length; i += 4) { var oneTime = tokens[i]; var delegateFn = tokens[i + 2]; if (delegateFn) { var value = delegateFn(model, node, oneTime); if (oneTime) observer.addPath(value) else observer.addObserver(value); continue; } var path = tokens[i + 1]; if (oneTime) observer.addPath(path.getValueFrom(model)) else observer.addPath(model, path); } return new ObserverTransform(observer, tokens.combinator); } function processBindings(node, bindings, model, instanceBindings) { for (var i = 0; i < bindings.length; i += 2) { var name = bindings[i] var tokens = bindings[i + 1]; var value = processBinding(name, tokens, node, model); var binding = node.bind(name, value, tokens.onlyOneTime); if (binding && instanceBindings) instanceBindings.push(binding); } node.bindFinished(); if (!bindings.isTemplate) return; node.model_ = model; var iter = node.processBindingDirectives_(bindings); if (instanceBindings && iter) instanceBindings.push(iter); } function parseWithDefault(el, name, prepareBindingFn) { var v = el.getAttribute(name); return parseMustaches(v == '' ? '{{}}' : v, name, el, prepareBindingFn); } function parseAttributeBindings(element, prepareBindingFn) { assert(element); var bindings = []; var ifFound = false; var bindFound = false; for (var i = 0; i < element.attributes.length; i++) { var attr = element.attributes[i]; var name = attr.name; var value = attr.value; // Allow bindings expressed in attributes to be prefixed with underbars. // We do this to allow correct semantics for browsers that don't implement // <template> where certain attributes might trigger side-effects -- and // for IE which sanitizes certain attributes, disallowing mustache // replacements in their text. while (name[0] === '_') { name = name.substring(1); } if (isTemplate(element) && (name === IF || name === BIND || name === REPEAT)) { continue; } var tokens = parseMustaches(value, name, element, prepareBindingFn); if (!tokens) continue; bindings.push(name, tokens); } if (isTemplate(element)) { bindings.isTemplate = true; bindings.if = parseWithDefault(element, IF, prepareBindingFn); bindings.bind = parseWithDefault(element, BIND, prepareBindingFn); bindings.repeat = parseWithDefault(element, REPEAT, prepareBindingFn); if (bindings.if && !bindings.bind && !bindings.repeat) bindings.bind = parseMustaches('{{}}', BIND, element, prepareBindingFn); } return bindings; } function getBindings(node, prepareBindingFn) { if (node.nodeType === Node.ELEMENT_NODE) return parseAttributeBindings(node, prepareBindingFn); if (node.nodeType === Node.TEXT_NODE) { var tokens = parseMustaches(node.data, 'textContent', node, prepareBindingFn); if (tokens) return ['textContent', tokens]; } return []; } function cloneAndBindInstance(node, parent, stagingDocument, bindings, model, delegate, instanceBindings, instanceRecord) { var clone = parent.appendChild(stagingDocument.importNode(node, false)); var i = 0; for (var child = node.firstChild; child; child = child.nextSibling) { cloneAndBindInstance(child, clone, stagingDocument, bindings.children[i++], model, delegate, instanceBindings); } if (bindings.isTemplate) { HTMLTemplateElement.decorate(clone, node); if (delegate) clone.setDelegate_(delegate); } processBindings(clone, bindings, model, instanceBindings); return clone; } function createInstanceBindingMap(node, prepareBindingFn) { var map = getBindings(node, prepareBindingFn); map.children = {}; var index = 0; for (var child = node.firstChild; child; child = child.nextSibling) { map.children[index++] = createInstanceBindingMap(child, prepareBindingFn); } return map; } var contentUidCounter = 1; // TODO(rafaelw): Setup a MutationObserver on content which clears the id // so that bindingMaps regenerate when the template.content changes. function getContentUid(content) { var id = content.id_; if (!id) id = content.id_ = contentUidCounter++; return id; } // Each delegate is associated with a set of bindingMaps, one for each // content which may be used by a template. The intent is that each binding // delegate gets the opportunity to prepare the instance (via the prepare* // delegate calls) once across all uses. // TODO(rafaelw): Separate out the parse map from the binding map. In the // current implementation, if two delegates need a binding map for the same // content, the second will have to reparse. function getInstanceBindingMap(content, delegate_) { var contentId = getContentUid(content); if (delegate_) { var map = delegate_.bindingMaps[contentId]; if (!map) { map = delegate_.bindingMaps[contentId] = createInstanceBindingMap(content, delegate_.prepareBinding) || []; } return map; } var map = content.bindingMap_; if (!map) { map = content.bindingMap_ = createInstanceBindingMap(content, undefined) || []; } return map; } Object.defineProperty(Node.prototype, 'templateInstance', { get: function() { var instance = this.templateInstance_; return instance ? instance : (this.parentNode ? this.parentNode.templateInstance : undefined); } }); var emptyInstance = document.createDocumentFragment(); emptyInstance.bindings_ = []; emptyInstance.terminator_ = null; function TemplateIterator(templateElement) { this.closed = false; this.templateElement_ = templateElement; this.instances = []; this.deps = undefined; this.iteratedValue = []; this.presentValue = undefined; this.arrayObserver = undefined; } TemplateIterator.prototype = { closeDeps: function() { var deps = this.deps; if (deps) { if (deps.ifOneTime === false) deps.ifValue.close(); if (deps.oneTime === false) deps.value.close(); } }, updateDependencies: function(directives, model) { this.closeDeps(); var deps = this.deps = {}; var template = this.templateElement_; var ifValue = true; if (directives.if) { deps.hasIf = true; deps.ifOneTime = directives.if.onlyOneTime; deps.ifValue = processBinding(IF, directives.if, template, model); ifValue = deps.ifValue; // oneTime if & predicate is false. nothing else to do. if (deps.ifOneTime && !ifValue) { this.valueChanged(); return; } if (!deps.ifOneTime) ifValue = ifValue.open(this.updateIfValue, this); } if (directives.repeat) { deps.repeat = true; deps.oneTime = directives.repeat.onlyOneTime; deps.value = processBinding(REPEAT, directives.repeat, template, model); } else { deps.repeat = false; deps.oneTime = directives.bind.onlyOneTime; deps.value = processBinding(BIND, directives.bind, template, model); } var value = deps.value; if (!deps.oneTime) value = value.open(this.updateIteratedValue, this); if (!ifValue) { this.valueChanged(); return; } this.updateValue(value); }, /** * Gets the updated value of the bind/repeat. This can potentially call * user code (if a bindingDelegate is set up) so we try to avoid it if we * already have the value in hand (from Observer.open). */ getUpdatedValue: function() { var value = this.deps.value; if (!this.deps.oneTime) value = value.discardChanges(); return value; }, updateIfValue: function(ifValue) { if (!ifValue) { this.valueChanged(); return; } this.updateValue(this.getUpdatedValue()); }, updateIteratedValue: function(value) { if (this.deps.hasIf) { var ifValue = this.deps.ifValue; if (!this.deps.ifOneTime) ifValue = ifValue.discardChanges(); if (!ifValue) { this.valueChanged(); return; } } this.updateValue(value); }, updateValue: function(value) { if (!this.deps.repeat) value = [value]; var observe = this.deps.repeat && !this.deps.oneTime && Array.isArray(value); this.valueChanged(value, observe); }, valueChanged: function(value, observeValue) { if (!Array.isArray(value)) value = []; if (value === this.iteratedValue) return; this.unobserve(); this.presentValue = value; if (observeValue) { this.arrayObserver = new ArrayObserver(this.presentValue); this.arrayObserver.open(this.handleSplices, this); } this.handleSplices(ArrayObserver.calculateSplices(this.presentValue, this.iteratedValue)); }, getLastInstanceNode: function(index) { if (index == -1) return this.templateElement_; var instance = this.instances[index]; var terminator = instance.terminator_; if (!terminator) return this.getLastInstanceNode(index - 1); if (terminator.nodeType !== Node.ELEMENT_NODE || this.templateElement_ === terminator) { return terminator; } var subtemplateIterator = terminator.iterator_; if (!subtemplateIterator) return terminator; return subtemplateIterator.getLastTemplateNode(); }, getLastTemplateNode: function() { return this.getLastInstanceNode(this.instances.length - 1); }, insertInstanceAt: function(index, fragment) { var previousInstanceLast = this.getLastInstanceNode(index - 1); var parent = this.templateElement_.parentNode; this.instances.splice(index, 0, fragment); parent.insertBefore(fragment, previousInstanceLast.nextSibling); }, extractInstanceAt: function(index) { var previousInstanceLast = this.getLastInstanceNode(index - 1); var lastNode = this.getLastInstanceNode(index); var parent = this.templateElement_.parentNode; var instance = this.instances.splice(index, 1)[0]; while (lastNode !== previousInstanceLast) { var node = previousInstanceLast.nextSibling; if (node == lastNode) lastNode = previousInstanceLast; instance.appendChild(parent.removeChild(node)); } return instance; }, getDelegateFn: function(fn) { fn = fn && fn(this.templateElement_); return typeof fn === 'function' ? fn : null; }, handleSplices: function(splices) { if (this.closed || !splices.length) return; var template = this.templateElement_; if (!template.parentNode) { this.close(); return; } ArrayObserver.applySplices(this.iteratedValue, this.presentValue, splices); var delegate = template.delegate_; if (this.instanceModelFn_ === undefined) { this.instanceModelFn_ = this.getDelegateFn(delegate && delegate.prepareInstanceModel); } if (this.instancePositionChangedFn_ === undefined) { this.instancePositionChangedFn_ = this.getDelegateFn(delegate && delegate.prepareInstancePositionChanged); } // Instance Removals var instanceCache = new Map; var removeDelta = 0; for (var i = 0; i < splices.length; i++) { var splice = splices[i]; var removed = splice.removed; for (var j = 0; j < removed.length; j++) { var model = removed[j]; var instance = this.extractInstanceAt(splice.index + removeDelta); if (instance !== emptyInstance) { instanceCache.set(model, instance); } } removeDelta -= splice.addedCount; } // Instance Insertions for (var i = 0; i < splices.length; i++) { var splice = splices[i]; var addIndex = splice.index; for (; addIndex < splice.index + splice.addedCount; addIndex++) { var model = this.iteratedValue[addIndex]; var instance = instanceCache.get(model); if (instance) { instanceCache.delete(model); } else { if (this.instanceModelFn_) { model = this.instanceModelFn_(model); } if (model === undefined) { instance = emptyInstance; } else { instance = template.createInstance(model, undefined, delegate); } } this.insertInstanceAt(addIndex, instance); } } instanceCache.forEach(function(instance) { this.closeInstanceBindings(instance); }, this); if (this.instancePositionChangedFn_) this.reportInstancesMoved(splices); }, reportInstanceMoved: function(index) { var instance = this.instances[index]; if (instance === emptyInstance) return; this.instancePositionChangedFn_(instance.templateInstance_, index); }, reportInstancesMoved: function(splices) { var index = 0; var offset = 0; for (var i = 0; i < splices.length; i++) { var splice = splices[i]; if (offset != 0) { while (index < splice.index) { this.reportInstanceMoved(index); index++; } } else { index = splice.index; } while (index < splice.index + splice.addedCount) { this.reportInstanceMoved(index); index++; } offset += splice.addedCount - splice.removed.length; } if (offset == 0) return; var length = this.instances.length; while (index < length) { this.reportInstanceMoved(index); index++; } }, closeInstanceBindings: function(instance) { var bindings = instance.bindings_; for (var i = 0; i < bindings.length; i++) { bindings[i].close(); } }, unobserve: function() { if (!this.arrayObserver) return; this.arrayObserver.close(); this.arrayObserver = undefined; }, close: function() { if (this.closed) return; this.unobserve(); for (var i = 0; i < this.instances.length; i++) { this.closeInstanceBindings(this.instances[i]); } this.instances.length = 0; this.closeDeps(); this.templateElement_.iterator_ = undefined; this.closed = true; } }; // Polyfill-specific API. HTMLTemplateElement.forAllTemplatesFrom_ = forAllTemplatesFrom; })(this); (function(scope) { 'use strict'; // feature detect for URL constructor var hasWorkingUrl = false; if (!scope.forceJURL) { try { var u = new URL('b', 'http://a'); u.pathname = 'c%20d'; hasWorkingUrl = u.href === 'http://a/c%20d'; } catch(e) {} } if (hasWorkingUrl) return; var relative = Object.create(null); relative['ftp'] = 21; relative['file'] = 0; relative['gopher'] = 70; relative['http'] = 80; relative['https'] = 443; relative['ws'] = 80; relative['wss'] = 443; var relativePathDotMapping = Object.create(null); relativePathDotMapping['%2e'] = '.'; relativePathDotMapping['.%2e'] = '..'; relativePathDotMapping['%2e.'] = '..'; relativePathDotMapping['%2e%2e'] = '..'; function isRelativeScheme(scheme) { return relative[scheme] !== undefined; } function invalid() { clear.call(this); this._isInvalid = true; } function IDNAToASCII(h) { if ('' == h) { invalid.call(this) } // XXX return h.toLowerCase() } function percentEscape(c) { var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ? ` [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1 ) { return c; } return encodeURIComponent(c); } function percentEscapeQuery(c) { // XXX This actually needs to encode c using encoding and then // convert the bytes one-by-one. var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ` (do not escape '?') [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1 ) { return c; } return encodeURIComponent(c); } var EOF = undefined, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/; function parse(input, stateOverride, base) { function err(message) { errors.push(message) } var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = []; loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) { var c = input[cursor]; switch (state) { case 'scheme start': if (c && ALPHA.test(c)) { buffer += c.toLowerCase(); // ASCII-safe state = 'scheme'; } else if (!stateOverride) { buffer = ''; state = 'no scheme'; continue; } else { err('Invalid scheme.'); break loop; } break; case 'scheme': if (c && ALPHANUMERIC.test(c)) { buffer += c.toLowerCase(); // ASCII-safe } else if (':' == c) { this._scheme = buffer; buffer = ''; if (stateOverride) { break loop; } if (isRelativeScheme(this._scheme)) { this._isRelative = true; } if ('file' == this._scheme) { state = 'relative'; } else if (this._isRelative && base && base._scheme == this._scheme) { state = 'relative or authority'; } else if (this._isRelative) { state = 'authority first slash'; } else { state = 'scheme data'; } } else if (!stateOverride) { buffer = ''; cursor = 0; state = 'no scheme'; continue; } else if (EOF == c) { break loop; } else { err('Code point not allowed in scheme: ' + c) break loop; } break; case 'scheme data': if ('?' == c) { query = '?'; state = 'query'; } else if ('#' == c) { this._fragment = '#'; state = 'fragment'; } else { // XXX error handling if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._schemeData += percentEscape(c); } } break; case 'no scheme': if (!base || !(isRelativeScheme(base._scheme))) { err('Missing scheme.'); invalid.call(this); } else { state = 'relative'; continue; } break; case 'relative or authority': if ('/' == c && '/' == input[cursor+1]) { state = 'authority ignore slashes'; } else { err('Expected /, got: ' + c); state = 'relative'; continue } break; case 'relative': this._isRelative = true; if ('file' != this._scheme) this._scheme = base._scheme; if (EOF == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; break loop; } else if ('/' == c || '\\' == c) { if ('\\' == c) err('\\ is an invalid code point.'); state = 'relative slash'; } else if ('?' == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = '?'; state = 'query'; } else if ('#' == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._fragment = '#'; state = 'fragment'; } else { var nextC = input[cursor+1] var nextNextC = input[cursor+2] if ( 'file' != this._scheme || !ALPHA.test(c) || (nextC != ':' && nextC != '|') || (EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC)) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._path.pop(); } state = 'relative path'; continue; } break; case 'relative slash': if ('/' == c || '\\' == c) { if ('\\' == c) { err('\\ is an invalid code point.'); } if ('file' == this._scheme) { state = 'file host'; } else { state = 'authority ignore slashes'; } } else { if ('file' != this._scheme) { this._host = base._host; this._port = base._port; } state = 'relative path'; continue; } break; case 'authority first slash': if ('/' == c) { state = 'authority second slash'; } else { err("Expected '/', got: " + c); state = 'authority ignore slashes'; continue; } break; case 'authority second slash': state = 'authority ignore slashes'; if ('/' != c) { err("Expected '/', got: " + c); continue; } break; case 'authority ignore slashes': if ('/' != c && '\\' != c) { state = 'authority'; continue; } else { err('Expected authority, got: ' + c); } break; case 'authority': if ('@' == c) { if (seenAt) { err('@ already seen.'); buffer += '%40'; } seenAt = true; for (var i = 0; i < buffer.length; i++) { var cp = buffer[i]; if ('\t' == cp || '\n' == cp || '\r' == cp) { err('Invalid whitespace in authority.'); continue; } // XXX check URL code points if (':' == cp && null === this._password) { this._password = ''; continue; } var tempC = percentEscape(cp); (null !== this._password) ? this._password += tempC : this._username += tempC; } buffer = ''; } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { cursor -= buffer.length; buffer = ''; state = 'host'; continue; } else { buffer += c; } break; case 'file host': if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) { state = 'relative path'; } else if (buffer.length == 0) { state = 'relative path start'; } else { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; } continue; } else if ('\t' == c || '\n' == c || '\r' == c) { err('Invalid whitespace in file host.'); } else { buffer += c; } break; case 'host': case 'hostname': if (':' == c && !seenBracket) { // XXX host parsing this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'port'; if ('hostname' == stateOverride) { break loop; } } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; if (stateOverride) { break loop; } continue; } else if ('\t' != c && '\n' != c && '\r' != c) { if ('[' == c) { seenBracket = true; } else if (']' == c) { seenBracket = false; } buffer += c; } else { err('Invalid code point in host/hostname: ' + c); } break; case 'port': if (/[0-9]/.test(c)) { buffer += c; } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) { if ('' != buffer) { var temp = parseInt(buffer, 10); if (temp != relative[this._scheme]) { this._port = temp + ''; } buffer = ''; } if (stateOverride) { break loop; } state = 'relative path start'; continue; } else if ('\t' == c || '\n' == c || '\r' == c) { err('Invalid code point in port: ' + c); } else { invalid.call(this); } break; case 'relative path start': if ('\\' == c) err("'\\' not allowed in path."); state = 'relative path'; if ('/' != c && '\\' != c) { continue; } break; case 'relative path': if (EOF == c || '/' == c || '\\' == c || (!stateOverride && ('?' == c || '#' == c))) { if ('\\' == c) { err('\\ not allowed in relative path.'); } var tmp; if (tmp = relativePathDotMapping[buffer.toLowerCase()]) { buffer = tmp; } if ('..' == buffer) { this._path.pop(); if ('/' != c && '\\' != c) { this._path.push(''); } } else if ('.' == buffer && '/' != c && '\\' != c) { this._path.push(''); } else if ('.' != buffer) { if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') { buffer = buffer[0] + ':'; } this._path.push(buffer); } buffer = ''; if ('?' == c) { this._query = '?'; state = 'query'; } else if ('#' == c) { this._fragment = '#'; state = 'fragment'; } } else if ('\t' != c && '\n' != c && '\r' != c) { buffer += percentEscape(c); } break; case 'query': if (!stateOverride && '#' == c) { this._fragment = '#'; state = 'fragment'; } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._query += percentEscapeQuery(c); } break; case 'fragment': if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._fragment += c; } break; } cursor++; } } function clear() { this._scheme = ''; this._schemeData = ''; this._username = ''; this._password = null; this._host = ''; this._port = ''; this._path = []; this._query = ''; this._fragment = ''; this._isInvalid = false; this._isRelative = false; } // Does not process domain names or IP addresses. // Does not handle encoding for the query parameter. function jURL(url, base /* , encoding */) { if (base !== undefined && !(base instanceof jURL)) base = new jURL(String(base)); this._url = url; clear.call(this); var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, ''); // encoding = encoding || 'utf-8' parse.call(this, input, null, base); } jURL.prototype = { get href() { if (this._isInvalid) return this._url; var authority = ''; if ('' != this._username || null != this._password) { authority = this._username + (null != this._password ? ':' + this._password : '') + '@'; } return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment; }, set href(href) { clear.call(this); parse.call(this, href); }, get protocol() { return this._scheme + ':'; }, set protocol(protocol) { if (this._isInvalid) return; parse.call(this, protocol + ':', 'scheme start'); }, get host() { return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host; }, set host(host) { if (this._isInvalid || !this._isRelative) return; parse.call(this, host, 'host'); }, get hostname() { return this._host; }, set hostname(hostname) { if (this._isInvalid || !this._isRelative) return; parse.call(this, hostname, 'hostname'); }, get port() { return this._port; }, set port(port) { if (this._isInvalid || !this._isRelative) return; parse.call(this, port, 'port'); }, get pathname() { return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData; }, set pathname(pathname) { if (this._isInvalid || !this._isRelative) return; this._path = []; parse.call(this, pathname, 'relative path start'); }, get search() { return this._isInvalid || !this._query || '?' == this._query ? '' : this._query; }, set search(search) { if (this._isInvalid || !this._isRelative) return; this._query = '?'; if ('?' == search[0]) search = search.slice(1); parse.call(this, search, 'query'); }, get hash() { return this._isInvalid || !this._fragment || '#' == this._fragment ? '' : this._fragment; }, set hash(hash) { if (this._isInvalid) return; this._fragment = '#'; if ('#' == hash[0]) hash = hash.slice(1); parse.call(this, hash, 'fragment'); }, get origin() { var host; if (this._isInvalid || !this._scheme) { return ''; } // javascript: Gecko returns String(""), WebKit/Blink String("null") // Gecko throws error for "data://" // data: Gecko returns "", Blink returns "data://", WebKit returns "null" // Gecko returns String("") for file: mailto: // WebKit/Blink returns String("SCHEME://") for file: mailto: switch (this._scheme) { case 'data': case 'file': case 'javascript': case 'mailto': return 'null'; } host = this.host; if (!host) { return ''; } return this._scheme + '://' + host; } }; // Copy over the static methods var OriginalURL = scope.URL; if (OriginalURL) { jURL.createObjectURL = function(blob) { // IE extension allows a second optional options argument. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx return OriginalURL.createObjectURL.apply(OriginalURL, arguments); }; jURL.revokeObjectURL = function(url) { OriginalURL.revokeObjectURL(url); }; } scope.URL = jURL; })(this); (function(scope) { var iterations = 0; var callbacks = []; var twiddle = document.createTextNode(''); function endOfMicrotask(callback) { twiddle.textContent = iterations++; callbacks.push(callback); } function atEndOfMicrotask() { while (callbacks.length) { callbacks.shift()(); } } new (window.MutationObserver || JsMutationObserver)(atEndOfMicrotask) .observe(twiddle, {characterData: true}) ; // exports scope.endOfMicrotask = endOfMicrotask; // bc Platform.endOfMicrotask = endOfMicrotask; })(Polymer); (function(scope) { /** * @class Polymer */ // imports var endOfMicrotask = scope.endOfMicrotask; // logging var log = window.WebComponents ? WebComponents.flags.log : {}; // inject style sheet var style = document.createElement('style'); style.textContent = 'template {display: none !important;} /* injected by platform.js */'; var head = document.querySelector('head'); head.insertBefore(style, head.firstChild); /** * Force any pending data changes to be observed before * the next task. Data changes are processed asynchronously but are guaranteed * to be processed, for example, before painting. This method should rarely be * needed. It does nothing when Object.observe is available; * when Object.observe is not available, Polymer automatically flushes data * changes approximately every 1/10 second. * Therefore, `flush` should only be used when a data mutation should be * observed sooner than this. * * @method flush */ // flush (with logging) var flushing; function flush() { if (!flushing) { flushing = true; endOfMicrotask(function() { flushing = false; log.data && console.group('flush'); Platform.performMicrotaskCheckpoint(); log.data && console.groupEnd(); }); } }; // polling dirty checker // flush periodically if platform does not have object observe. if (!Observer.hasObjectObserve) { var FLUSH_POLL_INTERVAL = 125; window.addEventListener('WebComponentsReady', function() { flush(); // watch document visiblity to toggle dirty-checking var visibilityHandler = function() { // only flush if the page is visibile if (document.visibilityState === 'hidden') { if (scope.flushPoll) { clearInterval(scope.flushPoll); } } else { scope.flushPoll = setInterval(flush, FLUSH_POLL_INTERVAL); } }; if (typeof document.visibilityState === 'string') { document.addEventListener('visibilitychange', visibilityHandler); } visibilityHandler(); }); } else { // make flush a no-op when we have Object.observe flush = function() {}; } if (window.CustomElements && !CustomElements.useNative) { var originalImportNode = Document.prototype.importNode; Document.prototype.importNode = function(node, deep) { var imported = originalImportNode.call(this, node, deep); CustomElements.upgradeAll(imported); return imported; }; } // exports scope.flush = flush; // bc Platform.flush = flush; })(window.Polymer); (function(scope) { var urlResolver = { resolveDom: function(root, url) { url = url || baseUrl(root); this.resolveAttributes(root, url); this.resolveStyles(root, url); // handle template.content var templates = root.querySelectorAll('template'); if (templates) { for (var i = 0, l = templates.length, t; (i < l) && (t = templates[i]); i++) { if (t.content) { this.resolveDom(t.content, url); } } } }, resolveTemplate: function(template) { this.resolveDom(template.content, baseUrl(template)); }, resolveStyles: function(root, url) { var styles = root.querySelectorAll('style'); if (styles) { for (var i = 0, l = styles.length, s; (i < l) && (s = styles[i]); i++) { this.resolveStyle(s, url); } } }, resolveStyle: function(style, url) { url = url || baseUrl(style); style.textContent = this.resolveCssText(style.textContent, url); }, resolveCssText: function(cssText, baseUrl, keepAbsolute) { cssText = replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, CSS_URL_REGEXP); return replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, CSS_IMPORT_REGEXP); }, resolveAttributes: function(root, url) { if (root.hasAttributes && root.hasAttributes()) { this.resolveElementAttributes(root, url); } // search for attributes that host urls var nodes = root && root.querySelectorAll(URL_ATTRS_SELECTOR); if (nodes) { for (var i = 0, l = nodes.length, n; (i < l) && (n = nodes[i]); i++) { this.resolveElementAttributes(n, url); } } }, resolveElementAttributes: function(node, url) { url = url || baseUrl(node); URL_ATTRS.forEach(function(v) { var attr = node.attributes[v]; var value = attr && attr.value; var replacement; if (value && value.search(URL_TEMPLATE_SEARCH) < 0) { if (v === 'style') { replacement = replaceUrlsInCssText(value, url, false, CSS_URL_REGEXP); } else { replacement = resolveRelativeUrl(url, value); } attr.value = replacement; } }); } }; var CSS_URL_REGEXP = /(url\()([^)]*)(\))/g; var CSS_IMPORT_REGEXP = /(@import[\s]+(?!url\())([^;]*)(;)/g; var URL_ATTRS = ['href', 'src', 'action', 'style', 'url']; var URL_ATTRS_SELECTOR = '[' + URL_ATTRS.join('],[') + ']'; var URL_TEMPLATE_SEARCH = '{{.*}}'; var URL_HASH = '#'; function baseUrl(node) { var u = new URL(node.ownerDocument.baseURI); u.search = ''; u.hash = ''; return u; } function replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, regexp) { return cssText.replace(regexp, function(m, pre, url, post) { var urlPath = url.replace(/["']/g, ''); urlPath = resolveRelativeUrl(baseUrl, urlPath, keepAbsolute); return pre + '\'' + urlPath + '\'' + post; }); } function resolveRelativeUrl(baseUrl, url, keepAbsolute) { // do not resolve '/' absolute urls if (url && url[0] === '/') { return url; } // do not resolve '#' links, they are used for routing if (url && url[0] === '#') { return url; } var u = new URL(url, baseUrl); return keepAbsolute ? u.href : makeDocumentRelPath(u.href); } function makeDocumentRelPath(url) { var root = baseUrl(document.documentElement); var u = new URL(url, root); if (u.host === root.host && u.port === root.port && u.protocol === root.protocol) { return makeRelPath(root, u); } else { return url; } } // make a relative path from source to target function makeRelPath(sourceUrl, targetUrl) { var source = sourceUrl.pathname; var target = targetUrl.pathname; var s = source.split('/'); var t = target.split('/'); while (s.length && s[0] === t[0]){ s.shift(); t.shift(); } for (var i = 0, l = s.length - 1; i < l; i++) { t.unshift('..'); } // empty '#' is discarded but we need to preserve it. var hash = (targetUrl.href.slice(-1) === URL_HASH) ? URL_HASH : targetUrl.hash; return t.join('/') + targetUrl.search + hash; } // exports scope.urlResolver = urlResolver; })(Polymer); (function(scope) { var endOfMicrotask = Polymer.endOfMicrotask; // Generic url loader function Loader(regex) { this.cache = Object.create(null); this.map = Object.create(null); this.requests = 0; this.regex = regex; } Loader.prototype = { // TODO(dfreedm): there may be a better factoring here // extract absolute urls from the text (full of relative urls) extractUrls: function(text, base) { var matches = []; var matched, u; while ((matched = this.regex.exec(text))) { u = new URL(matched[1], base); matches.push({matched: matched[0], url: u.href}); } return matches; }, // take a text blob, a root url, and a callback and load all the urls found within the text // returns a map of absolute url to text process: function(text, root, callback) { var matches = this.extractUrls(text, root); // every call to process returns all the text this loader has ever received var done = callback.bind(null, this.map); this.fetch(matches, done); }, // build a mapping of url -> text from matches fetch: function(matches, callback) { var inflight = matches.length; // return early if there is no fetching to be done if (!inflight) { return callback(); } // wait for all subrequests to return var done = function() { if (--inflight === 0) { callback(); } }; // start fetching all subrequests var m, req, url; for (var i = 0; i < inflight; i++) { m = matches[i]; url = m.url; req = this.cache[url]; // if this url has already been requested, skip requesting it again if (!req) { req = this.xhr(url); req.match = m; this.cache[url] = req; } // wait for the request to process its subrequests req.wait(done); } }, handleXhr: function(request) { var match = request.match; var url = match.url; // handle errors with an empty string var response = request.response || request.responseText || ''; this.map[url] = response; this.fetch(this.extractUrls(response, url), request.resolve); }, xhr: function(url) { this.requests++; var request = new XMLHttpRequest(); request.open('GET', url, true); request.send(); request.onerror = request.onload = this.handleXhr.bind(this, request); // queue of tasks to run after XHR returns request.pending = []; request.resolve = function() { var pending = request.pending; for(var i = 0; i < pending.length; i++) { pending[i](); } request.pending = null; }; // if we have already resolved, pending is null, async call the callback request.wait = function(fn) { if (request.pending) { request.pending.push(fn); } else { endOfMicrotask(fn); } }; return request; } }; scope.Loader = Loader; })(Polymer); (function(scope) { var urlResolver = scope.urlResolver; var Loader = scope.Loader; function StyleResolver() { this.loader = new Loader(this.regex); } StyleResolver.prototype = { regex: /@import\s+(?:url)?["'\(]*([^'"\)]*)['"\)]*;/g, // Recursively replace @imports with the text at that url resolve: function(text, url, callback) { var done = function(map) { callback(this.flatten(text, url, map)); }.bind(this); this.loader.process(text, url, done); }, // resolve the textContent of a style node resolveNode: function(style, url, callback) { var text = style.textContent; var done = function(text) { style.textContent = text; callback(style); }; this.resolve(text, url, done); }, // flatten all the @imports to text flatten: function(text, base, map) { var matches = this.loader.extractUrls(text, base); var match, url, intermediate; for (var i = 0; i < matches.length; i++) { match = matches[i]; url = match.url; // resolve any css text to be relative to the importer, keep absolute url intermediate = urlResolver.resolveCssText(map[url], url, true); // flatten intermediate @imports intermediate = this.flatten(intermediate, base, map); text = text.replace(match.matched, intermediate); } return text; }, loadStyles: function(styles, base, callback) { var loaded=0, l = styles.length; // called in the context of the style function loadedStyle(style) { loaded++; if (loaded === l && callback) { callback(); } } for (var i=0, s; (i<l) && (s=styles[i]); i++) { this.resolveNode(s, base, loadedStyle); } } }; var styleResolver = new StyleResolver(); // exports scope.styleResolver = styleResolver; })(Polymer); (function(scope) { // copy own properties from 'api' to 'prototype, with name hinting for 'super' function extend(prototype, api) { if (prototype && api) { // use only own properties of 'api' Object.getOwnPropertyNames(api).forEach(function(n) { // acquire property descriptor var pd = Object.getOwnPropertyDescriptor(api, n); if (pd) { // clone property via descriptor Object.defineProperty(prototype, n, pd); // cache name-of-method for 'super' engine if (typeof pd.value == 'function') { // hint the 'super' engine pd.value.nom = n; } } }); } return prototype; } // mixin // copy all properties from inProps (et al) to inObj function mixin(inObj/*, inProps, inMoreProps, ...*/) { var obj = inObj || {}; for (var i = 1; i < arguments.length; i++) { var p = arguments[i]; try { for (var n in p) { copyProperty(n, p, obj); } } catch(x) { } } return obj; } // copy property inName from inSource object to inTarget object function copyProperty(inName, inSource, inTarget) { var pd = getPropertyDescriptor(inSource, inName); Object.defineProperty(inTarget, inName, pd); } // get property descriptor for inName on inObject, even if // inName exists on some link in inObject's prototype chain function getPropertyDescriptor(inObject, inName) { if (inObject) { var pd = Object.getOwnPropertyDescriptor(inObject, inName); return pd || getPropertyDescriptor(Object.getPrototypeOf(inObject), inName); } } // exports scope.extend = extend; scope.mixin = mixin; // for bc Platform.mixin = mixin; })(Polymer); (function(scope) { // usage // invoke cb.call(this) in 100ms, unless the job is re-registered, // which resets the timer // // this.myJob = this.job(this.myJob, cb, 100) // // returns a job handle which can be used to re-register a job var Job = function(inContext) { this.context = inContext; this.boundComplete = this.complete.bind(this) }; Job.prototype = { go: function(callback, wait) { this.callback = callback; var h; if (!wait) { h = requestAnimationFrame(this.boundComplete); this.handle = function() { cancelAnimationFrame(h); } } else { h = setTimeout(this.boundComplete, wait); this.handle = function() { clearTimeout(h); } } }, stop: function() { if (this.handle) { this.handle(); this.handle = null; } }, complete: function() { if (this.handle) { this.stop(); this.callback.call(this.context); } } }; function job(job, callback, wait) { if (job) { job.stop(); } else { job = new Job(this); } job.go(callback, wait); return job; } // exports scope.job = job; })(Polymer); (function(scope) { // dom polyfill, additions, and utility methods var registry = {}; HTMLElement.register = function(tag, prototype) { registry[tag] = prototype; }; // get prototype mapped to node <tag> HTMLElement.getPrototypeForTag = function(tag) { var prototype = !tag ? HTMLElement.prototype : registry[tag]; // TODO(sjmiles): creating <tag> is likely to have wasteful side-effects return prototype || Object.getPrototypeOf(document.createElement(tag)); }; // we have to flag propagation stoppage for the event dispatcher var originalStopPropagation = Event.prototype.stopPropagation; Event.prototype.stopPropagation = function() { this.cancelBubble = true; originalStopPropagation.apply(this, arguments); }; // polyfill DOMTokenList // * add/remove: allow these methods to take multiple classNames // * toggle: add a 2nd argument which forces the given state rather // than toggling. var add = DOMTokenList.prototype.add; var remove = DOMTokenList.prototype.remove; DOMTokenList.prototype.add = function() { for (var i = 0; i < arguments.length; i++) { add.call(this, arguments[i]); } }; DOMTokenList.prototype.remove = function() { for (var i = 0; i < arguments.length; i++) { remove.call(this, arguments[i]); } }; DOMTokenList.prototype.toggle = function(name, bool) { if (arguments.length == 1) { bool = !this.contains(name); } bool ? this.add(name) : this.remove(name); }; DOMTokenList.prototype.switch = function(oldName, newName) { oldName && this.remove(oldName); newName && this.add(newName); }; // add array() to NodeList, NamedNodeMap, HTMLCollection var ArraySlice = function() { return Array.prototype.slice.call(this); }; var namedNodeMap = (window.NamedNodeMap || window.MozNamedAttrMap || {}); NodeList.prototype.array = ArraySlice; namedNodeMap.prototype.array = ArraySlice; HTMLCollection.prototype.array = ArraySlice; // utility function createDOM(inTagOrNode, inHTML, inAttrs) { var dom = typeof inTagOrNode == 'string' ? document.createElement(inTagOrNode) : inTagOrNode.cloneNode(true); dom.innerHTML = inHTML; if (inAttrs) { for (var n in inAttrs) { dom.setAttribute(n, inAttrs[n]); } } return dom; } // exports scope.createDOM = createDOM; })(Polymer); (function(scope) { // super // `arrayOfArgs` is an optional array of args like one might pass // to `Function.apply` // TODO(sjmiles): // $super must be installed on an instance or prototype chain // as `super`, and invoked via `this`, e.g. // `this.super();` // will not work if function objects are not unique, for example, // when using mixins. // The memoization strategy assumes each function exists on only one // prototype chain i.e. we use the function object for memoizing) // perhaps we can bookkeep on the prototype itself instead function $super(arrayOfArgs) { // since we are thunking a method call, performance is important here: // memoize all lookups, once memoized the fast path calls no other // functions // // find the caller (cannot be `strict` because of 'caller') var caller = $super.caller; // memoized 'name of method' var nom = caller.nom; // memoized next implementation prototype var _super = caller._super; if (!_super) { if (!nom) { nom = caller.nom = nameInThis.call(this, caller); } if (!nom) { console.warn('called super() on a method not installed declaratively (has no .nom property)'); } // super prototype is either cached or we have to find it // by searching __proto__ (at the 'top') // invariant: because we cache _super on fn below, we never reach // here from inside a series of calls to super(), so it's ok to // start searching from the prototype of 'this' (at the 'top') // we must never memoize a null super for this reason _super = memoizeSuper(caller, nom, getPrototypeOf(this)); } // our super function var fn = _super[nom]; if (fn) { // memoize information so 'fn' can call 'super' if (!fn._super) { // must not memoize null, or we lose our invariant above memoizeSuper(fn, nom, _super); } // invoke the inherited method // if 'fn' is not function valued, this will throw return fn.apply(this, arrayOfArgs || []); } } function nameInThis(value) { var p = this.__proto__; while (p && p !== HTMLElement.prototype) { // TODO(sjmiles): getOwnPropertyNames is absurdly expensive var n$ = Object.getOwnPropertyNames(p); for (var i=0, l=n$.length, n; i<l && (n=n$[i]); i++) { var d = Object.getOwnPropertyDescriptor(p, n); if (typeof d.value === 'function' && d.value === value) { return n; } } p = p.__proto__; } } function memoizeSuper(method, name, proto) { // find and cache next prototype containing `name` // we need the prototype so we can do another lookup // from here var s = nextSuper(proto, name, method); if (s[name]) { // `s` is a prototype, the actual method is `s[name]` // tag super method with it's name for quicker lookups s[name].nom = name; } return method._super = s; } function nextSuper(proto, name, caller) { // look for an inherited prototype that implements name while (proto) { if ((proto[name] !== caller) && proto[name]) { return proto; } proto = getPrototypeOf(proto); } // must not return null, or we lose our invariant above // in this case, a super() call was invoked where no superclass // method exists // TODO(sjmiles): thow an exception? return Object; } // NOTE: In some platforms (IE10) the prototype chain is faked via // __proto__. Therefore, always get prototype via __proto__ instead of // the more standard Object.getPrototypeOf. function getPrototypeOf(prototype) { return prototype.__proto__; } // utility function to precompute name tags for functions // in a (unchained) prototype function hintSuper(prototype) { // tag functions with their prototype name to optimize // super call invocations for (var n in prototype) { var pd = Object.getOwnPropertyDescriptor(prototype, n); if (pd && typeof pd.value === 'function') { pd.value.nom = n; } } } // exports scope.super = $super; })(Polymer); (function(scope) { function noopHandler(value) { return value; } // helper for deserializing properties of various types to strings var typeHandlers = { string: noopHandler, 'undefined': noopHandler, date: function(value) { return new Date(Date.parse(value) || Date.now()); }, boolean: function(value) { if (value === '') { return true; } return value === 'false' ? false : !!value; }, number: function(value) { var n = parseFloat(value); // hex values like "0xFFFF" parseFloat as 0 if (n === 0) { n = parseInt(value); } return isNaN(n) ? value : n; // this code disabled because encoded values (like "0xFFFF") // do not round trip to their original format //return (String(floatVal) === value) ? floatVal : value; }, object: function(value, currentValue) { if (currentValue === null) { return value; } try { // If the string is an object, we can parse is with the JSON library. // include convenience replace for single-quotes. If the author omits // quotes altogether, parse will fail. return JSON.parse(value.replace(/'/g, '"')); } catch(e) { // The object isn't valid JSON, return the raw value return value; } }, // avoid deserialization of functions 'function': function(value, currentValue) { return currentValue; } }; function deserializeValue(value, currentValue) { // attempt to infer type from default value var inferredType = typeof currentValue; // invent 'date' type value for Date if (currentValue instanceof Date) { inferredType = 'date'; } // delegate deserialization via type string return typeHandlers[inferredType](value, currentValue); } // exports scope.deserializeValue = deserializeValue; })(Polymer); (function(scope) { // imports var extend = scope.extend; // module var api = {}; api.declaration = {}; api.instance = {}; api.publish = function(apis, prototype) { for (var n in apis) { extend(prototype, apis[n]); } }; // exports scope.api = api; })(Polymer); (function(scope) { /** * @class polymer-base */ var utils = { /** * Invokes a function asynchronously. The context of the callback * function is bound to 'this' automatically. Returns a handle which may * be passed to <a href="#cancelAsync">cancelAsync</a> to cancel the * asynchronous call. * * @method async * @param {Function|String} method * @param {any|Array} args * @param {number} timeout */ async: function(method, args, timeout) { // when polyfilling Object.observe, ensure changes // propagate before executing the async method Polymer.flush(); // second argument to `apply` must be an array args = (args && args.length) ? args : [args]; // function to invoke var fn = function() { (this[method] || method).apply(this, args); }.bind(this); // execute `fn` sooner or later var handle = timeout ? setTimeout(fn, timeout) : requestAnimationFrame(fn); // NOTE: switch on inverting handle to determine which time is used. return timeout ? handle : ~handle; }, /** * Cancels a pending callback that was scheduled via * <a href="#async">async</a>. * * @method cancelAsync * @param {handle} handle Handle of the `async` to cancel. */ cancelAsync: function(handle) { if (handle < 0) { cancelAnimationFrame(~handle); } else { clearTimeout(handle); } }, /** * Fire an event. * * @method fire * @returns {Object} event * @param {string} type An event name. * @param {any} detail * @param {Node} onNode Target node. * @param {Boolean} bubbles Set false to prevent bubbling, defaults to true * @param {Boolean} cancelable Set false to prevent cancellation, defaults to true */ fire: function(type, detail, onNode, bubbles, cancelable) { var node = onNode || this; var detail = detail === null || detail === undefined ? {} : detail; var event = new CustomEvent(type, { bubbles: bubbles !== undefined ? bubbles : true, cancelable: cancelable !== undefined ? cancelable : true, detail: detail }); node.dispatchEvent(event); return event; }, /** * Fire an event asynchronously. * * @method asyncFire * @param {string} type An event name. * @param detail * @param {Node} toNode Target node. */ asyncFire: function(/*inType, inDetail*/) { this.async("fire", arguments); }, /** * Remove class from old, add class to anew, if they exist. * * @param classFollows * @param anew A node. * @param old A node * @param className */ classFollows: function(anew, old, className) { if (old) { old.classList.remove(className); } if (anew) { anew.classList.add(className); } }, /** * Inject HTML which contains markup bound to this element into * a target element (replacing target element content). * * @param String html to inject * @param Element target element */ injectBoundHTML: function(html, element) { var template = document.createElement('template'); template.innerHTML = html; var fragment = this.instanceTemplate(template); if (element) { element.textContent = ''; element.appendChild(fragment); } return fragment; } }; // no-operation function for handy stubs var nop = function() {}; // null-object for handy stubs var nob = {}; // deprecated utils.asyncMethod = utils.async; // exports scope.api.instance.utils = utils; scope.nop = nop; scope.nob = nob; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var EVENT_PREFIX = 'on-'; // instance events api var events = { // read-only EVENT_PREFIX: EVENT_PREFIX, // event listeners on host addHostListeners: function() { var events = this.eventDelegates; log.events && (Object.keys(events).length > 0) && console.log('[%s] addHostListeners:', this.localName, events); // NOTE: host events look like bindings but really are not; // (1) we don't want the attribute to be set and (2) we want to support // multiple event listeners ('host' and 'instance') and Node.bind // by default supports 1 thing being bound. for (var type in events) { var methodName = events[type]; PolymerGestures.addEventListener(this, type, this.element.getEventHandler(this, this, methodName)); } }, // call 'method' or function method on 'obj' with 'args', if the method exists dispatchMethod: function(obj, method, args) { if (obj) { log.events && console.group('[%s] dispatch [%s]', obj.localName, method); var fn = typeof method === 'function' ? method : obj[method]; if (fn) { fn[args ? 'apply' : 'call'](obj, args); } log.events && console.groupEnd(); // NOTE: dirty check right after calling method to ensure // changes apply quickly; in a very complicated app using high // frequency events, this can be a perf concern; in this case, // imperative handlers can be used to avoid flushing. Polymer.flush(); } } }; // exports scope.api.instance.events = events; /** * @class Polymer */ /** * Add a gesture aware event handler to the given `node`. Can be used * in place of `element.addEventListener` and ensures gestures will function * as expected on mobile platforms. Please note that Polymer's declarative * event handlers include this functionality by default. * * @method addEventListener * @param {Node} node node on which to listen * @param {String} eventType name of the event * @param {Function} handlerFn event handler function * @param {Boolean} capture set to true to invoke event capturing * @type Function */ // alias PolymerGestures event listener logic scope.addEventListener = function(node, eventType, handlerFn, capture) { PolymerGestures.addEventListener(wrap(node), eventType, handlerFn, capture); }; /** * Remove a gesture aware event handler on the given `node`. To remove an * event listener, the exact same arguments are required that were passed * to `Polymer.addEventListener`. * * @method removeEventListener * @param {Node} node node on which to listen * @param {String} eventType name of the event * @param {Function} handlerFn event handler function * @param {Boolean} capture set to true to invoke event capturing * @type Function */ scope.removeEventListener = function(node, eventType, handlerFn, capture) { PolymerGestures.removeEventListener(wrap(node), eventType, handlerFn, capture); }; })(Polymer); (function(scope) { // instance api for attributes var attributes = { // copy attributes defined in the element declaration to the instance // e.g. <polymer-element name="x-foo" tabIndex="0"> tabIndex is copied // to the element instance here. copyInstanceAttributes: function () { var a$ = this._instanceAttributes; for (var k in a$) { if (!this.hasAttribute(k)) { this.setAttribute(k, a$[k]); } } }, // for each attribute on this, deserialize value to property as needed takeAttributes: function() { // if we have no publish lookup table, we have no attributes to take // TODO(sjmiles): ad hoc if (this._publishLC) { for (var i=0, a$=this.attributes, l=a$.length, a; (a=a$[i]) && i<l; i++) { this.attributeToProperty(a.name, a.value); } } }, // if attribute 'name' is mapped to a property, deserialize // 'value' into that property attributeToProperty: function(name, value) { // try to match this attribute to a property (attributes are // all lower-case, so this is case-insensitive search) var name = this.propertyForAttribute(name); if (name) { // filter out 'mustached' values, these are to be // replaced with bound-data and are not yet values // themselves if (value && value.search(scope.bindPattern) >= 0) { return; } // get original value var currentValue = this[name]; // deserialize Boolean or Number values from attribute var value = this.deserializeValue(value, currentValue); // only act if the value has changed if (value !== currentValue) { // install new value (has side-effects) this[name] = value; } } }, // return the published property matching name, or undefined propertyForAttribute: function(name) { var match = this._publishLC && this._publishLC[name]; return match; }, // convert representation of `stringValue` based on type of `currentValue` deserializeValue: function(stringValue, currentValue) { return scope.deserializeValue(stringValue, currentValue); }, // convert to a string value based on the type of `inferredType` serializeValue: function(value, inferredType) { if (inferredType === 'boolean') { return value ? '' : undefined; } else if (inferredType !== 'object' && inferredType !== 'function' && value !== undefined) { return value; } }, // serializes `name` property value and updates the corresponding attribute // note that reflection is opt-in. reflectPropertyToAttribute: function(name) { var inferredType = typeof this[name]; // try to intelligently serialize property value var serializedValue = this.serializeValue(this[name], inferredType); // boolean properties must reflect as boolean attributes if (serializedValue !== undefined) { this.setAttribute(name, serializedValue); // TODO(sorvell): we should remove attr for all properties // that have undefined serialization; however, we will need to // refine the attr reflection system to achieve this; pica, for example, // relies on having inferredType object properties not removed as // attrs. } else if (inferredType === 'boolean') { this.removeAttribute(name); } } }; // exports scope.api.instance.attributes = attributes; })(Polymer); (function(scope) { /** * @class polymer-base */ // imports var log = window.WebComponents ? WebComponents.flags.log : {}; // magic words var OBSERVE_SUFFIX = 'Changed'; // element api var empty = []; var updateRecord = { object: undefined, type: 'update', name: undefined, oldValue: undefined }; var numberIsNaN = Number.isNaN || function(value) { return typeof value === 'number' && isNaN(value); }; function areSameValue(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; if (numberIsNaN(left) && numberIsNaN(right)) return true; return left !== left && right !== right; } // capture A's value if B's value is null or undefined, // otherwise use B's value function resolveBindingValue(oldValue, value) { if (value === undefined && oldValue === null) { return value; } return (value === null || value === undefined) ? oldValue : value; } var properties = { // creates a CompoundObserver to observe property changes // NOTE, this is only done there are any properties in the `observe` object createPropertyObserver: function() { var n$ = this._observeNames; if (n$ && n$.length) { var o = this._propertyObserver = new CompoundObserver(true); this.registerObserver(o); // TODO(sorvell): may not be kosher to access the value here (this[n]); // previously we looked at the descriptor on the prototype // this doesn't work for inheritance and not for accessors without // a value property for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) { o.addPath(this, n); this.observeArrayValue(n, this[n], null); } } }, // start observing property changes openPropertyObserver: function() { if (this._propertyObserver) { this._propertyObserver.open(this.notifyPropertyChanges, this); } }, // handler for property changes; routes changes to observing methods // note: array valued properties are observed for array splices notifyPropertyChanges: function(newValues, oldValues, paths) { var name, method, called = {}; for (var i in oldValues) { // note: paths is of form [object, path, object, path] name = paths[2 * i + 1]; method = this.observe[name]; if (method) { var ov = oldValues[i], nv = newValues[i]; // observes the value if it is an array this.observeArrayValue(name, nv, ov); if (!called[method]) { // only invoke change method if one of ov or nv is not (undefined | null) if ((ov !== undefined && ov !== null) || (nv !== undefined && nv !== null)) { called[method] = true; // TODO(sorvell): call method with the set of values it's expecting; // e.g. 'foo bar': 'invalidate' expects the new and old values for // foo and bar. Currently we give only one of these and then // deliver all the arguments. this.invokeMethod(method, [ov, nv, arguments]); } } } } }, // call method iff it exists. invokeMethod: function(method, args) { var fn = this[method] || method; if (typeof fn === 'function') { fn.apply(this, args); } }, /** * Force any pending property changes to synchronously deliver to * handlers specified in the `observe` object. * Note, normally changes are processed at microtask time. * * @method deliverChanges */ deliverChanges: function() { if (this._propertyObserver) { this._propertyObserver.deliver(); } }, observeArrayValue: function(name, value, old) { // we only care if there are registered side-effects var callbackName = this.observe[name]; if (callbackName) { // if we are observing the previous value, stop if (Array.isArray(old)) { log.observe && console.log('[%s] observeArrayValue: unregister observer [%s]', this.localName, name); this.closeNamedObserver(name + '__array'); } // if the new value is an array, being observing it if (Array.isArray(value)) { log.observe && console.log('[%s] observeArrayValue: register observer [%s]', this.localName, name, value); var observer = new ArrayObserver(value); observer.open(function(splices) { this.invokeMethod(callbackName, [splices]); }, this); this.registerNamedObserver(name + '__array', observer); } } }, emitPropertyChangeRecord: function(name, value, oldValue) { var object = this; if (areSameValue(value, oldValue)) { return; } // invoke property change side effects this._propertyChanged(name, value, oldValue); // emit change record if (!Observer.hasObjectObserve) { return; } var notifier = this._objectNotifier; if (!notifier) { notifier = this._objectNotifier = Object.getNotifier(this); } updateRecord.object = this; updateRecord.name = name; updateRecord.oldValue = oldValue; notifier.notify(updateRecord); }, _propertyChanged: function(name, value, oldValue) { if (this.reflect[name]) { this.reflectPropertyToAttribute(name); } }, // creates a property binding (called via bind) to a published property. bindProperty: function(property, observable, oneTime) { if (oneTime) { this[property] = observable; return; } var computed = this.element.prototype.computed; // Binding an "out-only" value to a computed property. Note that // since this observer isn't opened, it doesn't need to be closed on // cleanup. if (computed && computed[property]) { var privateComputedBoundValue = property + 'ComputedBoundObservable_'; this[privateComputedBoundValue] = observable; return; } return this.bindToAccessor(property, observable, resolveBindingValue); }, // NOTE property `name` must be published. This makes it an accessor. bindToAccessor: function(name, observable, resolveFn) { var privateName = name + '_'; var privateObservable = name + 'Observable_'; // Present for properties which are computed and published and have a // bound value. var privateComputedBoundValue = name + 'ComputedBoundObservable_'; this[privateObservable] = observable; var oldValue = this[privateName]; // observable callback var self = this; function updateValue(value, oldValue) { self[privateName] = value; var setObserveable = self[privateComputedBoundValue]; if (setObserveable && typeof setObserveable.setValue == 'function') { setObserveable.setValue(value); } self.emitPropertyChangeRecord(name, value, oldValue); } // resolve initial value var value = observable.open(updateValue); if (resolveFn && !areSameValue(oldValue, value)) { var resolvedValue = resolveFn(oldValue, value); if (!areSameValue(value, resolvedValue)) { value = resolvedValue; if (observable.setValue) { observable.setValue(value); } } } updateValue(value, oldValue); // register and return observable var observer = { close: function() { observable.close(); self[privateObservable] = undefined; self[privateComputedBoundValue] = undefined; } }; this.registerObserver(observer); return observer; }, createComputedProperties: function() { if (!this._computedNames) { return; } for (var i = 0; i < this._computedNames.length; i++) { var name = this._computedNames[i]; var expressionText = this.computed[name]; try { var expression = PolymerExpressions.getExpression(expressionText); var observable = expression.getBinding(this, this.element.syntax); this.bindToAccessor(name, observable); } catch (ex) { console.error('Failed to create computed property', ex); } } }, // property bookkeeping registerObserver: function(observer) { if (!this._observers) { this._observers = [observer]; return; } this._observers.push(observer); }, closeObservers: function() { if (!this._observers) { return; } // observer array items are arrays of observers. var observers = this._observers; for (var i = 0; i < observers.length; i++) { var observer = observers[i]; if (observer && typeof observer.close == 'function') { observer.close(); } } this._observers = []; }, // bookkeeping observers for memory management registerNamedObserver: function(name, observer) { var o$ = this._namedObservers || (this._namedObservers = {}); o$[name] = observer; }, closeNamedObserver: function(name) { var o$ = this._namedObservers; if (o$ && o$[name]) { o$[name].close(); o$[name] = null; return true; } }, closeNamedObservers: function() { if (this._namedObservers) { for (var i in this._namedObservers) { this.closeNamedObserver(i); } this._namedObservers = {}; } } }; // logging var LOG_OBSERVE = '[%s] watching [%s]'; var LOG_OBSERVED = '[%s#%s] watch: [%s] now [%s] was [%s]'; var LOG_CHANGED = '[%s#%s] propertyChanged: [%s] now [%s] was [%s]'; // exports scope.api.instance.properties = properties; })(Polymer); (function(scope) { /** * @class polymer-base */ // imports var log = window.WebComponents ? WebComponents.flags.log : {}; // element api supporting mdv var mdv = { /** * Creates dom cloned from the given template, instantiating bindings * with this element as the template model and `PolymerExpressions` as the * binding delegate. * * @method instanceTemplate * @param {Template} template source template from which to create dom. */ instanceTemplate: function(template) { // ensure template is decorated (lets' things like <tr template ...> work) HTMLTemplateElement.decorate(template); // ensure a default bindingDelegate var syntax = this.syntax || (!template.bindingDelegate && this.element.syntax); var dom = template.createInstance(this, syntax); var observers = dom.bindings_; for (var i = 0; i < observers.length; i++) { this.registerObserver(observers[i]); } return dom; }, // Called by TemplateBinding/NodeBind to setup a binding to the given // property. It's overridden here to support property bindings // in addition to attribute bindings that are supported by default. bind: function(name, observable, oneTime) { var property = this.propertyForAttribute(name); if (!property) { // TODO(sjmiles): this mixin method must use the special form // of `super` installed by `mixinMethod` in declaration/prototype.js return this.mixinSuper(arguments); } else { // use n-way Polymer binding var observer = this.bindProperty(property, observable, oneTime); // NOTE: reflecting binding information is typically required only for // tooling. It has a performance cost so it's opt-in in Node.bind. if (Platform.enableBindingsReflection && observer) { observer.path = observable.path_; this._recordBinding(property, observer); } if (this.reflect[property]) { this.reflectPropertyToAttribute(property); } return observer; } }, _recordBinding: function(name, observer) { this.bindings_ = this.bindings_ || {}; this.bindings_[name] = observer; }, // Called by TemplateBinding when all bindings on an element have been // executed. This signals that all element inputs have been gathered // and it's safe to ready the element, create shadow-root and start // data-observation. bindFinished: function() { this.makeElementReady(); }, // called at detached time to signal that an element's bindings should be // cleaned up. This is done asynchronously so that users have the chance // to call `cancelUnbindAll` to prevent unbinding. asyncUnbindAll: function() { if (!this._unbound) { log.unbind && console.log('[%s] asyncUnbindAll', this.localName); this._unbindAllJob = this.job(this._unbindAllJob, this.unbindAll, 0); } }, /** * This method should rarely be used and only if * <a href="#cancelUnbindAll">`cancelUnbindAll`</a> has been called to * prevent element unbinding. In this case, the element's bindings will * not be automatically cleaned up and it cannot be garbage collected * by the system. If memory pressure is a concern or a * large amount of elements need to be managed in this way, `unbindAll` * can be called to deactivate the element's bindings and allow its * memory to be reclaimed. * * @method unbindAll */ unbindAll: function() { if (!this._unbound) { this.closeObservers(); this.closeNamedObservers(); this._unbound = true; } }, /** * Call in `detached` to prevent the element from unbinding when it is * detached from the dom. The element is unbound as a cleanup step that * allows its memory to be reclaimed. * If `cancelUnbindAll` is used, consider calling * <a href="#unbindAll">`unbindAll`</a> when the element is no longer * needed. This will allow its memory to be reclaimed. * * @method cancelUnbindAll */ cancelUnbindAll: function() { if (this._unbound) { log.unbind && console.warn('[%s] already unbound, cannot cancel unbindAll', this.localName); return; } log.unbind && console.log('[%s] cancelUnbindAll', this.localName); if (this._unbindAllJob) { this._unbindAllJob = this._unbindAllJob.stop(); } } }; function unbindNodeTree(node) { forNodeTree(node, _nodeUnbindAll); } function _nodeUnbindAll(node) { node.unbindAll(); } function forNodeTree(node, callback) { if (node) { callback(node); for (var child = node.firstChild; child; child = child.nextSibling) { forNodeTree(child, callback); } } } var mustachePattern = /\{\{([^{}]*)}}/; // exports scope.bindPattern = mustachePattern; scope.api.instance.mdv = mdv; })(Polymer); (function(scope) { /** * Common prototype for all Polymer Elements. * * @class polymer-base * @homepage polymer.github.io */ var base = { /** * Tags this object as the canonical Base prototype. * * @property PolymerBase * @type boolean * @default true */ PolymerBase: true, /** * Debounce signals. * * Call `job` to defer a named signal, and all subsequent matching signals, * until a wait time has elapsed with no new signal. * * debouncedClickAction: function(e) { * // processClick only when it's been 100ms since the last click * this.job('click', function() { * this.processClick; * }, 100); * } * * @method job * @param String {String} job A string identifier for the job to debounce. * @param Function {Function} callback A function that is called (with `this` context) when the wait time elapses. * @param Number {Number} wait Time in milliseconds (ms) after the last signal that must elapse before invoking `callback` * @type Handle */ job: function(job, callback, wait) { if (typeof job === 'string') { var n = '___' + job; this[n] = Polymer.job.call(this, this[n], callback, wait); } else { // TODO(sjmiles): suggest we deprecate this call signature return Polymer.job.call(this, job, callback, wait); } }, /** * Invoke a superclass method. * * Use `super()` to invoke the most recently overridden call to the * currently executing function. * * To pass arguments through, use the literal `arguments` as the parameter * to `super()`. * * nextPageAction: function(e) { * // invoke the superclass version of `nextPageAction` * this.super(arguments); * } * * To pass custom arguments, arrange them in an array. * * appendSerialNo: function(value, serial) { * // prefix the superclass serial number with our lot # before * // invoking the superlcass * return this.super([value, this.lotNo + serial]) * } * * @method super * @type Any * @param {args) An array of arguments to use when calling the superclass method, or null. */ super: Polymer.super, /** * Lifecycle method called when the element is instantiated. * * Override `created` to perform custom create-time tasks. No need to call * super-class `created` unless you are extending another Polymer element. * Created is called before the element creates `shadowRoot` or prepares * data-observation. * * @method created * @type void */ created: function() { }, /** * Lifecycle method called when the element has populated it's `shadowRoot`, * prepared data-observation, and made itself ready for API interaction. * * @method ready * @type void */ ready: function() { }, /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom create-time tasks, implement `created` * instead, which is called immediately after `createdCallback`. * * @method createdCallback */ createdCallback: function() { if (this.templateInstance && this.templateInstance.model) { console.warn('Attributes on ' + this.localName + ' were data bound ' + 'prior to Polymer upgrading the element. This may result in ' + 'incorrect binding types.'); } this.created(); this.prepareElement(); if (!this.ownerDocument.isStagingDocument) { this.makeElementReady(); } }, // system entry point, do not override prepareElement: function() { if (this._elementPrepared) { console.warn('Element already prepared', this.localName); return; } this._elementPrepared = true; // storage for shadowRoots info this.shadowRoots = {}; // install property observers this.createPropertyObserver(); this.openPropertyObserver(); // install boilerplate attributes this.copyInstanceAttributes(); // process input attributes this.takeAttributes(); // add event listeners this.addHostListeners(); }, // system entry point, do not override makeElementReady: function() { if (this._readied) { return; } this._readied = true; this.createComputedProperties(); this.parseDeclarations(this.__proto__); // NOTE: Support use of the `unresolved` attribute to help polyfill // custom elements' `:unresolved` feature. this.removeAttribute('unresolved'); // user entry point this.ready(); }, /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom tasks in your element, implement `attributeChanged` * instead, which is called immediately after `attributeChangedCallback`. * * @method attributeChangedCallback */ attributeChangedCallback: function(name, oldValue) { // TODO(sjmiles): adhoc filter if (name !== 'class' && name !== 'style') { this.attributeToProperty(name, this.getAttribute(name)); } if (this.attributeChanged) { this.attributeChanged.apply(this, arguments); } }, /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom create-time tasks, implement `attached` * instead, which is called immediately after `attachedCallback`. * * @method attachedCallback */ attachedCallback: function() { // when the element is attached, prevent it from unbinding. this.cancelUnbindAll(); // invoke user action if (this.attached) { this.attached(); } if (!this.hasBeenAttached) { this.hasBeenAttached = true; if (this.domReady) { this.async('domReady'); } } }, /** * Implement to access custom elements in dom descendants, ancestors, * or siblings. Because custom elements upgrade in document order, * elements accessed in `ready` or `attached` may not be upgraded. When * `domReady` is called, all registered custom elements are guaranteed * to have been upgraded. * * @method domReady */ /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom create-time tasks, implement `detached` * instead, which is called immediately after `detachedCallback`. * * @method detachedCallback */ detachedCallback: function() { if (!this.preventDispose) { this.asyncUnbindAll(); } // invoke user action if (this.detached) { this.detached(); } // TODO(sorvell): bc if (this.leftView) { this.leftView(); } }, /** * Walks the prototype-chain of this element and allows specific * classes a chance to process static declarations. * * In particular, each polymer-element has it's own `template`. * `parseDeclarations` is used to accumulate all element `template`s * from an inheritance chain. * * `parseDeclaration` static methods implemented in the chain are called * recursively, oldest first, with the `<polymer-element>` associated * with the current prototype passed as an argument. * * An element may override this method to customize shadow-root generation. * * @method parseDeclarations */ parseDeclarations: function(p) { if (p && p.element) { this.parseDeclarations(p.__proto__); p.parseDeclaration.call(this, p.element); } }, /** * Perform init-time actions based on static information in the * `<polymer-element>` instance argument. * * For example, the standard implementation locates the template associated * with the given `<polymer-element>` and stamps it into a shadow-root to * implement shadow inheritance. * * An element may override this method for custom behavior. * * @method parseDeclaration */ parseDeclaration: function(elementElement) { var template = this.fetchTemplate(elementElement); if (template) { var root = this.shadowFromTemplate(template); this.shadowRoots[elementElement.name] = root; } }, /** * Given a `<polymer-element>`, find an associated template (if any) to be * used for shadow-root generation. * * An element may override this method for custom behavior. * * @method fetchTemplate */ fetchTemplate: function(elementElement) { return elementElement.querySelector('template'); }, /** * Create a shadow-root in this host and stamp `template` as it's * content. * * An element may override this method for custom behavior. * * @method shadowFromTemplate */ shadowFromTemplate: function(template) { if (template) { // make a shadow root var root = this.createShadowRoot(); // stamp template // which includes parsing and applying MDV bindings before being // inserted (to avoid {{}} in attribute values) // e.g. to prevent <img src="images/{{icon}}"> from generating a 404. var dom = this.instanceTemplate(template); // append to shadow dom root.appendChild(dom); // perform post-construction initialization tasks on shadow root this.shadowRootReady(root, template); // return the created shadow root return root; } }, // utility function that stamps a <template> into light-dom lightFromTemplate: function(template, refNode) { if (template) { // TODO(sorvell): mark this element as an eventController so that // event listeners on bound nodes inside it will be called on it. // Note, the expectation here is that events on all descendants // should be handled by this element. this.eventController = this; // stamp template // which includes parsing and applying MDV bindings before being // inserted (to avoid {{}} in attribute values) // e.g. to prevent <img src="images/{{icon}}"> from generating a 404. var dom = this.instanceTemplate(template); // append to shadow dom if (refNode) { this.insertBefore(dom, refNode); } else { this.appendChild(dom); } // perform post-construction initialization tasks on ahem, light root this.shadowRootReady(this); // return the created shadow root return dom; } }, shadowRootReady: function(root) { // locate nodes with id and store references to them in this.$ hash this.marshalNodeReferences(root); }, // locate nodes with id and store references to them in this.$ hash marshalNodeReferences: function(root) { // establish $ instance variable var $ = this.$ = this.$ || {}; // populate $ from nodes with ID from the LOCAL tree if (root) { var n$ = root.querySelectorAll("[id]"); for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) { $[n.id] = n; }; } }, /** * Register a one-time callback when a child-list or sub-tree mutation * occurs on node. * * For persistent callbacks, call onMutation from your listener. * * @method onMutation * @param Node {Node} node Node to watch for mutations. * @param Function {Function} listener Function to call on mutation. The function is invoked as `listener.call(this, observer, mutations);` where `observer` is the MutationObserver that triggered the notification, and `mutations` is the native mutation list. */ onMutation: function(node, listener) { var observer = new MutationObserver(function(mutations) { listener.call(this, observer, mutations); observer.disconnect(); }.bind(this)); observer.observe(node, {childList: true, subtree: true}); } }; /** * @class Polymer */ /** * Returns true if the object includes <a href="#polymer-base">polymer-base</a> in it's prototype chain. * * @method isBase * @param Object {Object} object Object to test. * @type Boolean */ function isBase(object) { return object.hasOwnProperty('PolymerBase') } // name a base constructor for dev tools /** * The Polymer base-class constructor. * * @property Base * @type Function */ function PolymerBase() {}; PolymerBase.prototype = base; base.constructor = PolymerBase; // exports scope.Base = PolymerBase; scope.isBase = isBase; scope.api.instance.base = base; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var hasShadowDOMPolyfill = window.ShadowDOMPolyfill; // magic words var STYLE_SCOPE_ATTRIBUTE = 'element'; var STYLE_CONTROLLER_SCOPE = 'controller'; var styles = { STYLE_SCOPE_ATTRIBUTE: STYLE_SCOPE_ATTRIBUTE, /** * Installs external stylesheets and <style> elements with the attribute * polymer-scope='controller' into the scope of element. This is intended * to be a called during custom element construction. */ installControllerStyles: function() { // apply controller styles, but only if they are not yet applied var scope = this.findStyleScope(); if (scope && !this.scopeHasNamedStyle(scope, this.localName)) { // allow inherited controller styles var proto = getPrototypeOf(this), cssText = ''; while (proto && proto.element) { cssText += proto.element.cssTextForScope(STYLE_CONTROLLER_SCOPE); proto = getPrototypeOf(proto); } if (cssText) { this.installScopeCssText(cssText, scope); } } }, installScopeStyle: function(style, name, scope) { var scope = scope || this.findStyleScope(), name = name || ''; if (scope && !this.scopeHasNamedStyle(scope, this.localName + name)) { var cssText = ''; if (style instanceof Array) { for (var i=0, l=style.length, s; (i<l) && (s=style[i]); i++) { cssText += s.textContent + '\n\n'; } } else { cssText = style.textContent; } this.installScopeCssText(cssText, scope, name); } }, installScopeCssText: function(cssText, scope, name) { scope = scope || this.findStyleScope(); name = name || ''; if (!scope) { return; } if (hasShadowDOMPolyfill) { cssText = shimCssText(cssText, scope.host); } var style = this.element.cssTextToScopeStyle(cssText, STYLE_CONTROLLER_SCOPE); Polymer.applyStyleToScope(style, scope); // cache that this style has been applied this.styleCacheForScope(scope)[this.localName + name] = true; }, findStyleScope: function(node) { // find the shadow root that contains this element var n = node || this; while (n.parentNode) { n = n.parentNode; } return n; }, scopeHasNamedStyle: function(scope, name) { var cache = this.styleCacheForScope(scope); return cache[name]; }, styleCacheForScope: function(scope) { if (hasShadowDOMPolyfill) { var scopeName = scope.host ? scope.host.localName : scope.localName; return polyfillScopeStyleCache[scopeName] || (polyfillScopeStyleCache[scopeName] = {}); } else { return scope._scopeStyles = (scope._scopeStyles || {}); } } }; var polyfillScopeStyleCache = {}; // NOTE: use raw prototype traversal so that we ensure correct traversal // on platforms where the protoype chain is simulated via __proto__ (IE10) function getPrototypeOf(prototype) { return prototype.__proto__; } function shimCssText(cssText, host) { var name = '', is = false; if (host) { name = host.localName; is = host.hasAttribute('is'); } var selector = WebComponents.ShadowCSS.makeScopeSelector(name, is); return WebComponents.ShadowCSS.shimCssText(cssText, selector); } // exports scope.api.instance.styles = styles; })(Polymer); (function(scope) { // imports var extend = scope.extend; var api = scope.api; // imperative implementation: Polymer() // specify an 'own' prototype for tag `name` function element(name, prototype) { if (typeof name !== 'string') { var script = prototype || document._currentScript; prototype = name; name = script && script.parentNode && script.parentNode.getAttribute ? script.parentNode.getAttribute('name') : ''; if (!name) { throw 'Element name could not be inferred.'; } } if (getRegisteredPrototype(name)) { throw 'Already registered (Polymer) prototype for element ' + name; } // cache the prototype registerPrototype(name, prototype); // notify the registrar waiting for 'name', if any notifyPrototype(name); } // async prototype source function waitingForPrototype(name, client) { waitPrototype[name] = client; } var waitPrototype = {}; function notifyPrototype(name) { if (waitPrototype[name]) { waitPrototype[name].registerWhenReady(); delete waitPrototype[name]; } } // utility and bookkeeping // maps tag names to prototypes, as registered with // Polymer. Prototypes associated with a tag name // using document.registerElement are available from // HTMLElement.getPrototypeForTag(). // If an element was fully registered by Polymer, then // Polymer.getRegisteredPrototype(name) === // HTMLElement.getPrototypeForTag(name) var prototypesByName = {}; function registerPrototype(name, prototype) { return prototypesByName[name] = prototype || {}; } function getRegisteredPrototype(name) { return prototypesByName[name]; } function instanceOfType(element, type) { if (typeof type !== 'string') { return false; } var proto = HTMLElement.getPrototypeForTag(type); var ctor = proto && proto.constructor; if (!ctor) { return false; } if (CustomElements.instanceof) { return CustomElements.instanceof(element, ctor); } return element instanceof ctor; } // exports scope.getRegisteredPrototype = getRegisteredPrototype; scope.waitingForPrototype = waitingForPrototype; scope.instanceOfType = instanceOfType; // namespace shenanigans so we can expose our scope on the registration // function // make window.Polymer reference `element()` window.Polymer = element; // TODO(sjmiles): find a way to do this that is less terrible // copy window.Polymer properties onto `element()` extend(Polymer, scope); // Under the HTMLImports polyfill, scripts in the main document // do not block on imports; we want to allow calls to Polymer in the main // document. WebComponents collects those calls until we can process them, which // we do here. if (WebComponents.consumeDeclarations) { WebComponents.consumeDeclarations(function(declarations) { if (declarations) { for (var i=0, l=declarations.length, d; (i<l) && (d=declarations[i]); i++) { element.apply(null, d); } } }); } })(Polymer); (function(scope) { /** * @class polymer-base */ /** * Resolve a url path to be relative to a `base` url. If unspecified, `base` * defaults to the element's ownerDocument url. Can be used to resolve * paths from element's in templates loaded in HTMLImports to be relative * to the document containing the element. Polymer automatically does this for * url attributes in element templates; however, if a url, for * example, contains a binding, then `resolvePath` can be used to ensure it is * relative to the element document. For example, in an element's template, * * <a href="{{resolvePath(path)}}">Resolved</a> * * @method resolvePath * @param {String} url Url path to resolve. * @param {String} base Optional base url against which to resolve, defaults * to the element's ownerDocument url. * returns {String} resolved url. */ var path = { resolveElementPaths: function(node) { Polymer.urlResolver.resolveDom(node); }, addResolvePathApi: function() { // let assetpath attribute modify the resolve path var assetPath = this.getAttribute('assetpath') || ''; var root = new URL(assetPath, this.ownerDocument.baseURI); this.prototype.resolvePath = function(urlPath, base) { var u = new URL(urlPath, base || root); return u.href; }; } }; // exports scope.api.declaration.path = path; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var api = scope.api.instance.styles; var STYLE_SCOPE_ATTRIBUTE = api.STYLE_SCOPE_ATTRIBUTE; var hasShadowDOMPolyfill = window.ShadowDOMPolyfill; // magic words var STYLE_SELECTOR = 'style'; var STYLE_LOADABLE_MATCH = '@import'; var SHEET_SELECTOR = 'link[rel=stylesheet]'; var STYLE_GLOBAL_SCOPE = 'global'; var SCOPE_ATTR = 'polymer-scope'; var styles = { // returns true if resources are loading loadStyles: function(callback) { var template = this.fetchTemplate(); var content = template && this.templateContent(); if (content) { this.convertSheetsToStyles(content); var styles = this.findLoadableStyles(content); if (styles.length) { var templateUrl = template.ownerDocument.baseURI; return Polymer.styleResolver.loadStyles(styles, templateUrl, callback); } } if (callback) { callback(); } }, convertSheetsToStyles: function(root) { var s$ = root.querySelectorAll(SHEET_SELECTOR); for (var i=0, l=s$.length, s, c; (i<l) && (s=s$[i]); i++) { c = createStyleElement(importRuleForSheet(s, this.ownerDocument.baseURI), this.ownerDocument); this.copySheetAttributes(c, s); s.parentNode.replaceChild(c, s); } }, copySheetAttributes: function(style, link) { for (var i=0, a$=link.attributes, l=a$.length, a; (a=a$[i]) && i<l; i++) { if (a.name !== 'rel' && a.name !== 'href') { style.setAttribute(a.name, a.value); } } }, findLoadableStyles: function(root) { var loadables = []; if (root) { var s$ = root.querySelectorAll(STYLE_SELECTOR); for (var i=0, l=s$.length, s; (i<l) && (s=s$[i]); i++) { if (s.textContent.match(STYLE_LOADABLE_MATCH)) { loadables.push(s); } } } return loadables; }, /** * Install external stylesheets loaded in <polymer-element> elements into the * element's template. * @param elementElement The <element> element to style. */ installSheets: function() { this.cacheSheets(); this.cacheStyles(); this.installLocalSheets(); this.installGlobalStyles(); }, /** * Remove all sheets from element and store for later use. */ cacheSheets: function() { this.sheets = this.findNodes(SHEET_SELECTOR); this.sheets.forEach(function(s) { if (s.parentNode) { s.parentNode.removeChild(s); } }); }, cacheStyles: function() { this.styles = this.findNodes(STYLE_SELECTOR + '[' + SCOPE_ATTR + ']'); this.styles.forEach(function(s) { if (s.parentNode) { s.parentNode.removeChild(s); } }); }, /** * Takes external stylesheets loaded in an <element> element and moves * their content into a <style> element inside the <element>'s template. * The sheet is then removed from the <element>. This is done only so * that if the element is loaded in the main document, the sheet does * not become active. * Note, ignores sheets with the attribute 'polymer-scope'. * @param elementElement The <element> element to style. */ installLocalSheets: function () { var sheets = this.sheets.filter(function(s) { return !s.hasAttribute(SCOPE_ATTR); }); var content = this.templateContent(); if (content) { var cssText = ''; sheets.forEach(function(sheet) { cssText += cssTextFromSheet(sheet) + '\n'; }); if (cssText) { var style = createStyleElement(cssText, this.ownerDocument); content.insertBefore(style, content.firstChild); } } }, findNodes: function(selector, matcher) { var nodes = this.querySelectorAll(selector).array(); var content = this.templateContent(); if (content) { var templateNodes = content.querySelectorAll(selector).array(); nodes = nodes.concat(templateNodes); } return matcher ? nodes.filter(matcher) : nodes; }, /** * Promotes external stylesheets and <style> elements with the attribute * polymer-scope='global' into global scope. * This is particularly useful for defining @keyframe rules which * currently do not function in scoped or shadow style elements. * (See wkb.ug/72462) * @param elementElement The <element> element to style. */ // TODO(sorvell): remove when wkb.ug/72462 is addressed. installGlobalStyles: function() { var style = this.styleForScope(STYLE_GLOBAL_SCOPE); applyStyleToScope(style, document.head); }, cssTextForScope: function(scopeDescriptor) { var cssText = ''; // handle stylesheets var selector = '[' + SCOPE_ATTR + '=' + scopeDescriptor + ']'; var matcher = function(s) { return matchesSelector(s, selector); }; var sheets = this.sheets.filter(matcher); sheets.forEach(function(sheet) { cssText += cssTextFromSheet(sheet) + '\n\n'; }); // handle cached style elements var styles = this.styles.filter(matcher); styles.forEach(function(style) { cssText += style.textContent + '\n\n'; }); return cssText; }, styleForScope: function(scopeDescriptor) { var cssText = this.cssTextForScope(scopeDescriptor); return this.cssTextToScopeStyle(cssText, scopeDescriptor); }, cssTextToScopeStyle: function(cssText, scopeDescriptor) { if (cssText) { var style = createStyleElement(cssText); style.setAttribute(STYLE_SCOPE_ATTRIBUTE, this.getAttribute('name') + '-' + scopeDescriptor); return style; } } }; function importRuleForSheet(sheet, baseUrl) { var href = new URL(sheet.getAttribute('href'), baseUrl).href; return '@import \'' + href + '\';'; } function applyStyleToScope(style, scope) { if (style) { if (scope === document) { scope = document.head; } if (hasShadowDOMPolyfill) { scope = document.head; } // TODO(sorvell): necessary for IE // see https://connect.microsoft.com/IE/feedback/details/790212/ // cloning-a-style-element-and-adding-to-document-produces // -unexpected-result#details // var clone = style.cloneNode(true); var clone = createStyleElement(style.textContent); var attr = style.getAttribute(STYLE_SCOPE_ATTRIBUTE); if (attr) { clone.setAttribute(STYLE_SCOPE_ATTRIBUTE, attr); } // TODO(sorvell): probably too brittle; try to figure out // where to put the element. var refNode = scope.firstElementChild; if (scope === document.head) { var selector = 'style[' + STYLE_SCOPE_ATTRIBUTE + ']'; var s$ = document.head.querySelectorAll(selector); if (s$.length) { refNode = s$[s$.length-1].nextElementSibling; } } scope.insertBefore(clone, refNode); } } function createStyleElement(cssText, scope) { scope = scope || document; scope = scope.createElement ? scope : scope.ownerDocument; var style = scope.createElement('style'); style.textContent = cssText; return style; } function cssTextFromSheet(sheet) { return (sheet && sheet.__resource) || ''; } function matchesSelector(node, inSelector) { if (matches) { return matches.call(node, inSelector); } } var p = HTMLElement.prototype; var matches = p.matches || p.matchesSelector || p.webkitMatchesSelector || p.mozMatchesSelector; // exports scope.api.declaration.styles = styles; scope.applyStyleToScope = applyStyleToScope; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var api = scope.api.instance.events; var EVENT_PREFIX = api.EVENT_PREFIX; var mixedCaseEventTypes = {}; [ 'webkitAnimationStart', 'webkitAnimationEnd', 'webkitTransitionEnd', 'DOMFocusOut', 'DOMFocusIn', 'DOMMouseScroll' ].forEach(function(e) { mixedCaseEventTypes[e.toLowerCase()] = e; }); // polymer-element declarative api: events feature var events = { parseHostEvents: function() { // our delegates map var delegates = this.prototype.eventDelegates; // extract data from attributes into delegates this.addAttributeDelegates(delegates); }, addAttributeDelegates: function(delegates) { // for each attribute for (var i=0, a; a=this.attributes[i]; i++) { // does it have magic marker identifying it as an event delegate? if (this.hasEventPrefix(a.name)) { // if so, add the info to delegates delegates[this.removeEventPrefix(a.name)] = a.value.replace('{{', '') .replace('}}', '').trim(); } } }, // starts with 'on-' hasEventPrefix: function (n) { return n && (n[0] === 'o') && (n[1] === 'n') && (n[2] === '-'); }, removeEventPrefix: function(n) { return n.slice(prefixLength); }, findController: function(node) { while (node.parentNode) { if (node.eventController) { return node.eventController; } node = node.parentNode; } return node.host; }, getEventHandler: function(controller, target, method) { var events = this; return function(e) { if (!controller || !controller.PolymerBase) { controller = events.findController(target); } var args = [e, e.detail, e.currentTarget]; controller.dispatchMethod(controller, method, args); }; }, prepareEventBinding: function(pathString, name, node) { if (!this.hasEventPrefix(name)) return; var eventType = this.removeEventPrefix(name); eventType = mixedCaseEventTypes[eventType] || eventType; var events = this; return function(model, node, oneTime) { var handler = events.getEventHandler(undefined, node, pathString); PolymerGestures.addEventListener(node, eventType, handler); if (oneTime) return; // TODO(rafaelw): This is really pointless work. Aside from the cost // of these allocations, NodeBind is going to setAttribute back to its // current value. Fixing this would mean changing the TemplateBinding // binding delegate API. function bindingValue() { return '{{ ' + pathString + ' }}'; } return { open: bindingValue, discardChanges: bindingValue, close: function() { PolymerGestures.removeEventListener(node, eventType, handler); } }; }; } }; var prefixLength = EVENT_PREFIX.length; // exports scope.api.declaration.events = events; })(Polymer); (function(scope) { // element api var observationBlacklist = ['attribute']; var properties = { inferObservers: function(prototype) { // called before prototype.observe is chained to inherited object var observe = prototype.observe, property; for (var n in prototype) { if (n.slice(-7) === 'Changed') { property = n.slice(0, -7); if (this.canObserveProperty(property)) { if (!observe) { observe = (prototype.observe = {}); } observe[property] = observe[property] || n; } } } }, canObserveProperty: function(property) { return (observationBlacklist.indexOf(property) < 0); }, explodeObservers: function(prototype) { // called before prototype.observe is chained to inherited object var o = prototype.observe; if (o) { var exploded = {}; for (var n in o) { var names = n.split(' '); for (var i=0, ni; ni=names[i]; i++) { exploded[ni] = o[n]; } } prototype.observe = exploded; } }, optimizePropertyMaps: function(prototype) { if (prototype.observe) { // construct name list var a = prototype._observeNames = []; for (var n in prototype.observe) { var names = n.split(' '); for (var i=0, ni; ni=names[i]; i++) { a.push(ni); } } } if (prototype.publish) { // construct name list var a = prototype._publishNames = []; for (var n in prototype.publish) { a.push(n); } } if (prototype.computed) { // construct name list var a = prototype._computedNames = []; for (var n in prototype.computed) { a.push(n); } } }, publishProperties: function(prototype, base) { // if we have any properties to publish var publish = prototype.publish; if (publish) { // transcribe `publish` entries onto own prototype this.requireProperties(publish, prototype, base); // warn and remove accessor names that are broken on some browsers this.filterInvalidAccessorNames(publish); // construct map of lower-cased property names prototype._publishLC = this.lowerCaseMap(publish); } var computed = prototype.computed; if (computed) { // warn and remove accessor names that are broken on some browsers this.filterInvalidAccessorNames(computed); } }, // Publishing/computing a property where the name might conflict with a // browser property is not currently supported to help users of Polymer // avoid browser bugs: // // https://code.google.com/p/chromium/issues/detail?id=43394 // https://bugs.webkit.org/show_bug.cgi?id=49739 // // We can lift this restriction when those bugs are fixed. filterInvalidAccessorNames: function(propertyNames) { for (var name in propertyNames) { // Check if the name is in our blacklist. if (this.propertyNameBlacklist[name]) { console.warn('Cannot define property "' + name + '" for element "' + this.name + '" because it has the same name as an HTMLElement ' + 'property, and not all browsers support overriding that. ' + 'Consider giving it a different name.'); // Remove the invalid accessor from the list. delete propertyNames[name]; } } }, // // `name: value` entries in the `publish` object may need to generate // matching properties on the prototype. // // Values that are objects may have a `reflect` property, which // signals that the value describes property control metadata. // In metadata objects, the prototype default value (if any) // is encoded in the `value` property. // // publish: { // foo: 5, // bar: {value: true, reflect: true}, // zot: {} // } // // `reflect` metadata property controls whether changes to the property // are reflected back to the attribute (default false). // // A value is stored on the prototype unless it's === `undefined`, // in which case the base chain is checked for a value. // If the basal value is also undefined, `null` is stored on the prototype. // // The reflection data is stored on another prototype object, `reflect` // which also can be specified directly. // // reflect: { // foo: true // } // requireProperties: function(propertyInfos, prototype, base) { // per-prototype storage for reflected properties prototype.reflect = prototype.reflect || {}; // ensure a prototype value for each property // and update the property's reflect to attribute status for (var n in propertyInfos) { var value = propertyInfos[n]; // value has metadata if it has a `reflect` property if (value && value.reflect !== undefined) { prototype.reflect[n] = Boolean(value.reflect); value = value.value; } // only set a value if one is specified if (value !== undefined) { prototype[n] = value; } } }, lowerCaseMap: function(properties) { var map = {}; for (var n in properties) { map[n.toLowerCase()] = n; } return map; }, createPropertyAccessor: function(name, ignoreWrites) { var proto = this.prototype; var privateName = name + '_'; var privateObservable = name + 'Observable_'; proto[privateName] = proto[name]; Object.defineProperty(proto, name, { get: function() { var observable = this[privateObservable]; if (observable) observable.deliver(); return this[privateName]; }, set: function(value) { if (ignoreWrites) { return this[privateName]; } var observable = this[privateObservable]; if (observable) { observable.setValue(value); return; } var oldValue = this[privateName]; this[privateName] = value; this.emitPropertyChangeRecord(name, value, oldValue); return value; }, configurable: true }); }, createPropertyAccessors: function(prototype) { var n$ = prototype._computedNames; if (n$ && n$.length) { for (var i=0, l=n$.length, n, fn; (i<l) && (n=n$[i]); i++) { this.createPropertyAccessor(n, true); } } var n$ = prototype._publishNames; if (n$ && n$.length) { for (var i=0, l=n$.length, n, fn; (i<l) && (n=n$[i]); i++) { // If the property is computed and published, the accessor is created // above. if (!prototype.computed || !prototype.computed[n]) { this.createPropertyAccessor(n); } } } }, // This list contains some property names that people commonly want to use, // but won't work because of Chrome/Safari bugs. It isn't an exhaustive // list. In particular it doesn't contain any property names found on // subtypes of HTMLElement (e.g. name, value). Rather it attempts to catch // some common cases. propertyNameBlacklist: { children: 1, 'class': 1, id: 1, hidden: 1, style: 1, title: 1, } }; // exports scope.api.declaration.properties = properties; })(Polymer); (function(scope) { // magic words var ATTRIBUTES_ATTRIBUTE = 'attributes'; var ATTRIBUTES_REGEX = /\s|,/; // attributes api var attributes = { inheritAttributesObjects: function(prototype) { // chain our lower-cased publish map to the inherited version this.inheritObject(prototype, 'publishLC'); // chain our instance attributes map to the inherited version this.inheritObject(prototype, '_instanceAttributes'); }, publishAttributes: function(prototype, base) { // merge names from 'attributes' attribute into the 'publish' object var attributes = this.getAttribute(ATTRIBUTES_ATTRIBUTE); if (attributes) { // create a `publish` object if needed. // the `publish` object is only relevant to this prototype, the // publishing logic in `declaration/properties.js` is responsible for // managing property values on the prototype chain. // TODO(sjmiles): the `publish` object is later chained to it's // ancestor object, presumably this is only for // reflection or other non-library uses. var publish = prototype.publish || (prototype.publish = {}); // names='a b c' or names='a,b,c' var names = attributes.split(ATTRIBUTES_REGEX); // record each name for publishing for (var i=0, l=names.length, n; i<l; i++) { // remove excess ws n = names[i].trim(); // looks weird, but causes n to exist on `publish` if it does not; // a more careful test would need expensive `in` operator if (n && publish[n] === undefined) { publish[n] = undefined; } } } }, // record clonable attributes from <element> accumulateInstanceAttributes: function() { // inherit instance attributes var clonable = this.prototype._instanceAttributes; // merge attributes from element var a$ = this.attributes; for (var i=0, l=a$.length, a; (i<l) && (a=a$[i]); i++) { if (this.isInstanceAttribute(a.name)) { clonable[a.name] = a.value; } } }, isInstanceAttribute: function(name) { return !this.blackList[name] && name.slice(0,3) !== 'on-'; }, // do not clone these attributes onto instances blackList: { name: 1, 'extends': 1, constructor: 1, noscript: 1, assetpath: 1, 'cache-csstext': 1 } }; // add ATTRIBUTES_ATTRIBUTE to the blacklist attributes.blackList[ATTRIBUTES_ATTRIBUTE] = 1; // exports scope.api.declaration.attributes = attributes; })(Polymer); (function(scope) { // imports var events = scope.api.declaration.events; var syntax = new PolymerExpressions(); var prepareBinding = syntax.prepareBinding; // Polymer takes a first crack at the binding to see if it's a declarative // event handler. syntax.prepareBinding = function(pathString, name, node) { return events.prepareEventBinding(pathString, name, node) || prepareBinding.call(syntax, pathString, name, node); }; // declaration api supporting mdv var mdv = { syntax: syntax, fetchTemplate: function() { return this.querySelector('template'); }, templateContent: function() { var template = this.fetchTemplate(); return template && template.content; }, installBindingDelegate: function(template) { if (template) { template.bindingDelegate = this.syntax; } } }; // exports scope.api.declaration.mdv = mdv; })(Polymer); (function(scope) { // imports var api = scope.api; var isBase = scope.isBase; var extend = scope.extend; var hasShadowDOMPolyfill = window.ShadowDOMPolyfill; // prototype api var prototype = { register: function(name, extendeeName) { // build prototype combining extendee, Polymer base, and named api this.buildPrototype(name, extendeeName); // register our custom element with the platform this.registerPrototype(name, extendeeName); // reference constructor in a global named by 'constructor' attribute this.publishConstructor(); }, buildPrototype: function(name, extendeeName) { // get our custom prototype (before chaining) var extension = scope.getRegisteredPrototype(name); // get basal prototype var base = this.generateBasePrototype(extendeeName); // implement declarative features this.desugarBeforeChaining(extension, base); // join prototypes this.prototype = this.chainPrototypes(extension, base); // more declarative features this.desugarAfterChaining(name, extendeeName); }, desugarBeforeChaining: function(prototype, base) { // back reference declaration element // TODO(sjmiles): replace `element` with `elementElement` or `declaration` prototype.element = this; // transcribe `attributes` declarations onto own prototype's `publish` this.publishAttributes(prototype, base); // `publish` properties to the prototype and to attribute watch this.publishProperties(prototype, base); // infer observers for `observe` list based on method names this.inferObservers(prototype); // desugar compound observer syntax, e.g. 'a b c' this.explodeObservers(prototype); }, chainPrototypes: function(prototype, base) { // chain various meta-data objects to inherited versions this.inheritMetaData(prototype, base); // chain custom api to inherited var chained = this.chainObject(prototype, base); // x-platform fixup ensurePrototypeTraversal(chained); return chained; }, inheritMetaData: function(prototype, base) { // chain observe object to inherited this.inheritObject('observe', prototype, base); // chain publish object to inherited this.inheritObject('publish', prototype, base); // chain reflect object to inherited this.inheritObject('reflect', prototype, base); // chain our lower-cased publish map to the inherited version this.inheritObject('_publishLC', prototype, base); // chain our instance attributes map to the inherited version this.inheritObject('_instanceAttributes', prototype, base); // chain our event delegates map to the inherited version this.inheritObject('eventDelegates', prototype, base); }, // implement various declarative features desugarAfterChaining: function(name, extendee) { // build side-chained lists to optimize iterations this.optimizePropertyMaps(this.prototype); this.createPropertyAccessors(this.prototype); // install mdv delegate on template this.installBindingDelegate(this.fetchTemplate()); // install external stylesheets as if they are inline this.installSheets(); // adjust any paths in dom from imports this.resolveElementPaths(this); // compile list of attributes to copy to instances this.accumulateInstanceAttributes(); // parse on-* delegates declared on `this` element this.parseHostEvents(); // // install a helper method this.resolvePath to aid in // setting resource urls. e.g. // this.$.image.src = this.resolvePath('images/foo.png') this.addResolvePathApi(); // under ShadowDOMPolyfill, transforms to approximate missing CSS features if (hasShadowDOMPolyfill) { WebComponents.ShadowCSS.shimStyling(this.templateContent(), name, extendee); } // allow custom element access to the declarative context if (this.prototype.registerCallback) { this.prototype.registerCallback(this); } }, // if a named constructor is requested in element, map a reference // to the constructor to the given symbol publishConstructor: function() { var symbol = this.getAttribute('constructor'); if (symbol) { window[symbol] = this.ctor; } }, // build prototype combining extendee, Polymer base, and named api generateBasePrototype: function(extnds) { var prototype = this.findBasePrototype(extnds); if (!prototype) { // create a prototype based on tag-name extension var prototype = HTMLElement.getPrototypeForTag(extnds); // insert base api in inheritance chain (if needed) prototype = this.ensureBaseApi(prototype); // memoize this base memoizedBases[extnds] = prototype; } return prototype; }, findBasePrototype: function(name) { return memoizedBases[name]; }, // install Polymer instance api into prototype chain, as needed ensureBaseApi: function(prototype) { if (prototype.PolymerBase) { return prototype; } var extended = Object.create(prototype); // we need a unique copy of base api for each base prototype // therefore we 'extend' here instead of simply chaining api.publish(api.instance, extended); // TODO(sjmiles): sharing methods across prototype chains is // not supported by 'super' implementation which optimizes // by memoizing prototype relationships. // Probably we should have a version of 'extend' that is // share-aware: it could study the text of each function, // look for usage of 'super', and wrap those functions in // closures. // As of now, there is only one problematic method, so // we just patch it manually. // To avoid re-entrancy problems, the special super method // installed is called `mixinSuper` and the mixin method // must use this method instead of the default `super`. this.mixinMethod(extended, prototype, api.instance.mdv, 'bind'); // return buffed-up prototype return extended; }, mixinMethod: function(extended, prototype, api, name) { var $super = function(args) { return prototype[name].apply(this, args); }; extended[name] = function() { this.mixinSuper = $super; return api[name].apply(this, arguments); } }, // ensure prototype[name] inherits from a prototype.prototype[name] inheritObject: function(name, prototype, base) { // require an object var source = prototype[name] || {}; // chain inherited properties onto a new object prototype[name] = this.chainObject(source, base[name]); }, // register 'prototype' to custom element 'name', store constructor registerPrototype: function(name, extendee) { var info = { prototype: this.prototype } // native element must be specified in extends var typeExtension = this.findTypeExtension(extendee); if (typeExtension) { info.extends = typeExtension; } // register the prototype with HTMLElement for name lookup HTMLElement.register(name, this.prototype); // register the custom type this.ctor = document.registerElement(name, info); }, findTypeExtension: function(name) { if (name && name.indexOf('-') < 0) { return name; } else { var p = this.findBasePrototype(name); if (p.element) { return this.findTypeExtension(p.element.extends); } } } }; // memoize base prototypes var memoizedBases = {}; // implementation of 'chainObject' depends on support for __proto__ if (Object.__proto__) { prototype.chainObject = function(object, inherited) { if (object && inherited && object !== inherited) { object.__proto__ = inherited; } return object; } } else { prototype.chainObject = function(object, inherited) { if (object && inherited && object !== inherited) { var chained = Object.create(inherited); object = extend(chained, object); } return object; } } // On platforms that do not support __proto__ (versions of IE), the prototype // chain of a custom element is simulated via installation of __proto__. // Although custom elements manages this, we install it here so it's // available during desugaring. function ensurePrototypeTraversal(prototype) { if (!Object.__proto__) { var ancestor = Object.getPrototypeOf(prototype); prototype.__proto__ = ancestor; if (isBase(ancestor)) { ancestor.__proto__ = Object.getPrototypeOf(ancestor); } } } // exports api.declaration.prototype = prototype; })(Polymer); (function(scope) { /* Elements are added to a registration queue so that they register in the proper order at the appropriate time. We do this for a few reasons: * to enable elements to load resources (like stylesheets) asynchronously. We need to do this until the platform provides an efficient alternative. One issue is that remote @import stylesheets are re-fetched whenever stamped into a shadowRoot. * to ensure elements loaded 'at the same time' (e.g. via some set of imports) are registered as a batch. This allows elements to be enured from upgrade ordering as long as they query the dom tree 1 task after upgrade (aka domReady). This is a performance tradeoff. On the one hand, elements that could register while imports are loading are prevented from doing so. On the other, grouping upgrades into a single task means less incremental work (for example style recalcs), Also, we can ensure the document is in a known state at the single quantum of time when elements upgrade. */ var queue = { // tell the queue to wait for an element to be ready wait: function(element) { if (!element.__queue) { element.__queue = {}; elements.push(element); } }, // enqueue an element to the next spot in the queue. enqueue: function(element, check, go) { var shouldAdd = element.__queue && !element.__queue.check; if (shouldAdd) { queueForElement(element).push(element); element.__queue.check = check; element.__queue.go = go; } return (this.indexOf(element) !== 0); }, indexOf: function(element) { var i = queueForElement(element).indexOf(element); if (i >= 0 && document.contains(element)) { i += (HTMLImports.useNative || HTMLImports.ready) ? importQueue.length : 1e9; } return i; }, // tell the queue an element is ready to be registered go: function(element) { var readied = this.remove(element); if (readied) { element.__queue.flushable = true; this.addToFlushQueue(readied); this.check(); } }, remove: function(element) { var i = this.indexOf(element); if (i !== 0) { //console.warn('queue order wrong', i); return; } return queueForElement(element).shift(); }, check: function() { // next var element = this.nextElement(); if (element) { element.__queue.check.call(element); } if (this.canReady()) { this.ready(); return true; } }, nextElement: function() { return nextQueued(); }, canReady: function() { return !this.waitToReady && this.isEmpty(); }, isEmpty: function() { for (var i=0, l=elements.length, e; (i<l) && (e=elements[i]); i++) { if (e.__queue && !e.__queue.flushable) { return; } } return true; }, addToFlushQueue: function(element) { flushQueue.push(element); }, flush: function() { // prevent re-entrance if (this.flushing) { return; } this.flushing = true; var element; while (flushQueue.length) { element = flushQueue.shift(); element.__queue.go.call(element); element.__queue = null; } this.flushing = false; }, ready: function() { // TODO(sorvell): As an optimization, turn off CE polyfill upgrading // while registering. This way we avoid having to upgrade each document // piecemeal per registration and can instead register all elements // and upgrade once in a batch. Without this optimization, upgrade time // degrades significantly when SD polyfill is used. This is mainly because // querying the document tree for elements is slow under the SD polyfill. var polyfillWasReady = CustomElements.ready; CustomElements.ready = false; this.flush(); if (!CustomElements.useNative) { CustomElements.upgradeDocumentTree(document); } CustomElements.ready = polyfillWasReady; Polymer.flush(); requestAnimationFrame(this.flushReadyCallbacks); }, addReadyCallback: function(callback) { if (callback) { readyCallbacks.push(callback); } }, flushReadyCallbacks: function() { if (readyCallbacks) { var fn; while (readyCallbacks.length) { fn = readyCallbacks.shift(); fn(); } } }, /** Returns a list of elements that have had polymer-elements created but are not yet ready to register. The list is an array of element definitions. */ waitingFor: function() { var e$ = []; for (var i=0, l=elements.length, e; (i<l) && (e=elements[i]); i++) { if (e.__queue && !e.__queue.flushable) { e$.push(e); } } return e$; }, waitToReady: true }; var elements = []; var flushQueue = []; var importQueue = []; var mainQueue = []; var readyCallbacks = []; function queueForElement(element) { return document.contains(element) ? mainQueue : importQueue; } function nextQueued() { return importQueue.length ? importQueue[0] : mainQueue[0]; } function whenReady(callback) { queue.waitToReady = true; Polymer.endOfMicrotask(function() { HTMLImports.whenReady(function() { queue.addReadyCallback(callback); queue.waitToReady = false; queue.check(); }); }); } /** Forces polymer to register any pending elements. Can be used to abort waiting for elements that are partially defined. @param timeout {Integer} Optional timeout in milliseconds */ function forceReady(timeout) { if (timeout === undefined) { queue.ready(); return; } var handle = setTimeout(function() { queue.ready(); }, timeout); Polymer.whenReady(function() { clearTimeout(handle); }); } // exports scope.elements = elements; scope.waitingFor = queue.waitingFor.bind(queue); scope.forceReady = forceReady; scope.queue = queue; scope.whenReady = scope.whenPolymerReady = whenReady; })(Polymer); (function(scope) { // imports var extend = scope.extend; var api = scope.api; var queue = scope.queue; var whenReady = scope.whenReady; var getRegisteredPrototype = scope.getRegisteredPrototype; var waitingForPrototype = scope.waitingForPrototype; // declarative implementation: <polymer-element> var prototype = extend(Object.create(HTMLElement.prototype), { createdCallback: function() { if (this.getAttribute('name')) { this.init(); } }, init: function() { // fetch declared values this.name = this.getAttribute('name'); this.extends = this.getAttribute('extends'); queue.wait(this); // initiate any async resource fetches this.loadResources(); // register when all constraints are met this.registerWhenReady(); }, // TODO(sorvell): we currently queue in the order the prototypes are // registered, but we should queue in the order that polymer-elements // are registered. We are currently blocked from doing this based on // crbug.com/395686. registerWhenReady: function() { if (this.registered || this.waitingForPrototype(this.name) || this.waitingForQueue() || this.waitingForResources()) { return; } queue.go(this); }, _register: function() { //console.log('registering', this.name); // warn if extending from a custom element not registered via Polymer if (isCustomTag(this.extends) && !isRegistered(this.extends)) { console.warn('%s is attempting to extend %s, an unregistered element ' + 'or one that was not registered with Polymer.', this.name, this.extends); } this.register(this.name, this.extends); this.registered = true; }, waitingForPrototype: function(name) { if (!getRegisteredPrototype(name)) { // then wait for a prototype waitingForPrototype(name, this); // emulate script if user is not supplying one this.handleNoScript(name); // prototype not ready yet return true; } }, handleNoScript: function(name) { // if explicitly marked as 'noscript' if (this.hasAttribute('noscript') && !this.noscript) { this.noscript = true; // imperative element registration Polymer(name); } }, waitingForResources: function() { return this._needsResources; }, // NOTE: Elements must be queued in proper order for inheritance/composition // dependency resolution. Previously this was enforced for inheritance, // and by rule for composition. It's now entirely by rule. waitingForQueue: function() { return queue.enqueue(this, this.registerWhenReady, this._register); }, loadResources: function() { this._needsResources = true; this.loadStyles(function() { this._needsResources = false; this.registerWhenReady(); }.bind(this)); } }); // semi-pluggable APIs // TODO(sjmiles): should be fully pluggable (aka decoupled, currently // the various plugins are allowed to depend on each other directly) api.publish(api.declaration, prototype); // utility and bookkeeping function isRegistered(name) { return Boolean(HTMLElement.getPrototypeForTag(name)); } function isCustomTag(name) { return (name && name.indexOf('-') >= 0); } // boot tasks whenReady(function() { document.body.removeAttribute('unresolved'); document.dispatchEvent( new CustomEvent('polymer-ready', {bubbles: true}) ); }); // register polymer-element with document document.registerElement('polymer-element', {prototype: prototype}); })(Polymer); (function(scope) { /** * @class Polymer */ var whenReady = scope.whenReady; /** * Loads the set of HTMLImports contained in `node`. Notifies when all * the imports have loaded by calling the `callback` function argument. * This method can be used to lazily load imports. For example, given a * template: * * <template> * <link rel="import" href="my-import1.html"> * <link rel="import" href="my-import2.html"> * </template> * * Polymer.importElements(template.content, function() { * console.log('imports lazily loaded'); * }); * * @method importElements * @param {Node} node Node containing the HTMLImports to load. * @param {Function} callback Callback called when all imports have loaded. */ function importElements(node, callback) { if (node) { document.head.appendChild(node); whenReady(callback); } else if (callback) { callback(); } } /** * Loads an HTMLImport for each url specified in the `urls` array. * Notifies when all the imports have loaded by calling the `callback` * function argument. This method can be used to lazily load imports. * For example, * * Polymer.import(['my-import1.html', 'my-import2.html'], function() { * console.log('imports lazily loaded'); * }); * * @method import * @param {Array} urls Array of urls to load as HTMLImports. * @param {Function} callback Callback called when all imports have loaded. */ function _import(urls, callback) { if (urls && urls.length) { var frag = document.createDocumentFragment(); for (var i=0, l=urls.length, url, link; (i<l) && (url=urls[i]); i++) { link = document.createElement('link'); link.rel = 'import'; link.href = url; frag.appendChild(link); } importElements(frag, callback); } else if (callback) { callback(); } } // exports scope.import = _import; scope.importElements = importElements; })(Polymer); /** * The `auto-binding` element extends the template element. It provides a quick * and easy way to do data binding without the need to setup a model. * The `auto-binding` element itself serves as the model and controller for the * elements it contains. Both data and event handlers can be bound. * * The `auto-binding` element acts just like a template that is bound to * a model. It stamps its content in the dom adjacent to itself. When the * content is stamped, the `template-bound` event is fired. * * Example: * * <template is="auto-binding"> * <div>Say something: <input value="{{value}}"></div> * <div>You said: {{value}}</div> * <button on-tap="{{buttonTap}}">Tap me!</button> * </template> * <script> * var template = document.querySelector('template'); * template.value = 'something'; * template.buttonTap = function() { * console.log('tap!'); * }; * </script> * * @module Polymer * @status stable */ (function() { var element = document.createElement('polymer-element'); element.setAttribute('name', 'auto-binding'); element.setAttribute('extends', 'template'); element.init(); Polymer('auto-binding', { createdCallback: function() { this.syntax = this.bindingDelegate = this.makeSyntax(); // delay stamping until polymer-ready so that auto-binding is not // required to load last. Polymer.whenPolymerReady(function() { this.model = this; this.setAttribute('bind', ''); // we don't bother with an explicit signal here, we could ust a MO // if necessary this.async(function() { // note: this will marshall *all* the elements in the parentNode // rather than just stamped ones. We'd need to use createInstance // to fix this or something else fancier. this.marshalNodeReferences(this.parentNode); // template stamping is asynchronous so stamping isn't complete // by polymer-ready; fire an event so users can use stamped elements this.fire('template-bound'); }); }.bind(this)); }, makeSyntax: function() { var events = Object.create(Polymer.api.declaration.events); var self = this; events.findController = function() { return self.model; }; var syntax = new PolymerExpressions(); var prepareBinding = syntax.prepareBinding; syntax.prepareBinding = function(pathString, name, node) { return events.prepareEventBinding(pathString, name, node) || prepareBinding.call(syntax, pathString, name, node); }; return syntax; } }); })();
src/app/components/BrowserSupport.js
meedan/check-web
import React, { Component } from 'react'; import { FormattedMessage, injectIntl } from 'react-intl'; import styled from 'styled-components'; import IconButton from '@material-ui/core/IconButton'; import ClearIcon from '@material-ui/icons/Clear'; import { mapGlobalMessage } from './MappedMessage'; import { ContentColumn, units, black54, white, } from '../styles/js/shared'; const Message = styled.div` padding: ${units(1)}; color: ${black54}; background-color: ${white}; > div { display: flex; align-items: center; } // Not sure why this is necessary for vertical alignment. // Is there a bug in IconButton? I think we are using it correctly. // - CGB 2017-7-12 // button > div { display: flex; align-items: center; } `; class BrowserSupport extends Component { static supported() { const ua = navigator.userAgent; if (/Chrome/i.test(ua) && !/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|mobile|CriOS/i.test(ua)) { return true; } return false; } static closed() { return window.storage.getValue('close-unsupported-browser-message') === '1'; } static shouldShowMessage() { return !BrowserSupport.supported() && !BrowserSupport.closed() && window.parent === window; } close() { window.storage.set('close-unsupported-browser-message', '1'); this.forceUpdate(); } render() { if (BrowserSupport.shouldShowMessage()) { return ( <Message> <ContentColumn> <IconButton style={{ fontSize: '20px', color: black54 }} onClick={this.close.bind(this)}> <ClearIcon /> </IconButton> <div> <FormattedMessage id="browserSupport.message" defaultMessage="{appName} is optimized for Google Chrome on desktop." values={{ appName: mapGlobalMessage(this.props.intl, 'appNameHuman') }} /> </div> </ContentColumn> </Message> ); } return null; } } export default injectIntl(BrowserSupport);
lib/yuilib/3.17.2/datatable-body/datatable-body-debug.js
valdy89/diplomaThesis
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('datatable-body', function (Y, NAME) { /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. @module datatable @submodule datatable-body @since 3.5.0 **/ var Lang = Y.Lang, isArray = Lang.isArray, isNumber = Lang.isNumber, isString = Lang.isString, fromTemplate = Lang.sub, htmlEscape = Y.Escape.html, toArray = Y.Array, bind = Y.bind, YObject = Y.Object, valueRegExp = /\{value\}/g, EV_CONTENT_UPDATE = 'contentUpdate', shiftMap = { above: [-1, 0], below: [1, 0], next: [0, 1], prev: [0, -1], previous: [0, -1] }; /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. Translates the provided `modelList` into a rendered `<tbody>` based on the data in the constituent Models, altered or amended by any special column configurations. The `columns` configuration, passed to the constructor, determines which columns will be rendered. The rendering process involves constructing an HTML template for a complete row of data, built by concatenating a customized copy of the instance's `CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is then populated with values from each Model in the `modelList`, aggregating a complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. A column `formatter` can be: * a function, as described below. * a string which can be: * the name of a pre-defined formatter function which can be located in the `Y.DataTable.BodyView.Formatters` hash using the value of the `formatter` property as the index. * A template that can use the `{value}` placeholder to include the value for the current cell or the name of any field in the underlaying model also enclosed in curly braces. Any number and type of these placeholders can be used. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @class BodyView @namespace DataTable @extends View @since 3.5.0 **/ Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], { // -- Instance properties ------------------------------------------------- /** HTML template used to create table cells. @property CELL_TEMPLATE @type {String} @default '<td {headers} class="{className}">{content}</td>' @since 3.5.0 **/ CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>', /** CSS class applied to even rows. This is assigned at instantiation. For DataTable, this will be `yui3-datatable-even`. @property CLASS_EVEN @type {String} @default 'yui3-table-even' @since 3.5.0 **/ //CLASS_EVEN: null /** CSS class applied to odd rows. This is assigned at instantiation. When used by DataTable instances, this will be `yui3-datatable-odd`. @property CLASS_ODD @type {String} @default 'yui3-table-odd' @since 3.5.0 **/ //CLASS_ODD: null /** HTML template used to create table rows. @property ROW_TEMPLATE @type {String} @default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>' @since 3.5.0 **/ ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>', /** The object that serves as the source of truth for column and row data. This property is assigned at instantiation from the `host` property of the configuration object passed to the constructor. @property host @type {Object} @default (initially unset) @since 3.5.0 **/ //TODO: should this be protected? //host: null, /** HTML templates used to create the `<tbody>` containing the table rows. @property TBODY_TEMPLATE @type {String} @default '<tbody class="{className}">{content}</tbody>' @since 3.6.0 **/ TBODY_TEMPLATE: '<tbody class="{className}"></tbody>', // -- Public methods ------------------------------------------------------ /** Returns the `<td>` Node from the given row and column index. Alternately, the `seed` can be a Node. If so, the nearest ancestor cell is returned. If the `seed` is a cell, it is returned. If there is no cell at the given coordinates, `null` is returned. Optionally, include an offset array or string to return a cell near the cell identified by the `seed`. The offset can be an array containing the number of rows to shift followed by the number of columns to shift, or one of "above", "below", "next", or "previous". <pre><code>// Previous cell in the previous row var cell = table.getCell(e.target, [-1, -1]); // Next cell var cell = table.getCell(e.target, 'next'); var cell = table.getCell(e.target, [0, 1];</pre></code> @method getCell @param {Number[]|Node} seed Array of row and column indexes, or a Node that is either the cell itself or a descendant of one. @param {Number[]|String} [shift] Offset by which to identify the returned cell Node @return {Node} @since 3.5.0 **/ getCell: function (seed, shift) { var tbody = this.tbodyNode, row, cell, index, rowIndexOffset; if (seed && tbody) { if (isArray(seed)) { row = tbody.get('children').item(seed[0]); cell = row && row.get('children').item(seed[1]); } else if (seed._node) { cell = seed.ancestor('.' + this.getClassName('cell'), true); } if (cell && shift) { rowIndexOffset = tbody.get('firstChild.rowIndex'); if (isString(shift)) { if (!shiftMap[shift]) { Y.error('Unrecognized shift: ' + shift, null, 'datatable-body'); } shift = shiftMap[shift]; } if (isArray(shift)) { index = cell.get('parentNode.rowIndex') + shift[0] - rowIndexOffset; row = tbody.get('children').item(index); index = cell.get('cellIndex') + shift[1]; cell = row && row.get('children').item(index); } } } return cell || null; }, /** Returns the generated CSS classname based on the input. If the `host` attribute is configured, it will attempt to relay to its `getClassName` or use its static `NAME` property as a string base. If `host` is absent or has neither method nor `NAME`, a CSS classname will be generated using this class's `NAME`. @method getClassName @param {String} token* Any number of token strings to assemble the classname from. @return {String} @protected @since 3.5.0 **/ getClassName: function () { var host = this.host, args; if (host && host.getClassName) { return host.getClassName.apply(host, arguments); } else { args = toArray(arguments); args.unshift(this.constructor.NAME); return Y.ClassNameManager.getClassName .apply(Y.ClassNameManager, args); } }, /** Returns the Model associated to the row Node or id provided. Passing the Node or id for a descendant of the row also works. If no Model can be found, `null` is returned. @method getRecord @param {String|Node} seed Row Node or `id`, or one for a descendant of a row @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var modelList = this.get('modelList'), tbody = this.tbodyNode, row = null, record; if (tbody) { if (isString(seed)) { seed = tbody.one('#' + seed); } if (seed && seed._node) { row = seed.ancestor(function (node) { return node.get('parentNode').compareTo(tbody); }, true); record = row && modelList.getByClientId(row.getData('yui3-record')); } } return record || null; }, /** Returns the `<tr>` Node from the given row index, Model, or Model's `clientId`. If the rows haven't been rendered yet, or if the row can't be found by the input, `null` is returned. @method getRow @param {Number|String|Model} id Row index, Model instance, or clientId @return {Node} @since 3.5.0 **/ getRow: function (id) { var tbody = this.tbodyNode, row = null; if (tbody) { if (id) { id = this._idMap[id.get ? id.get('clientId') : id] || id; } row = isNumber(id) ? tbody.get('children').item(id) : tbody.one('#' + id); } return row; }, /** Creates the table's `<tbody>` content by assembling markup generated by populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content from the `columns` and `modelList` attributes. The rendering process happens in three stages: 1. A row template is assembled from the `columns` attribute (see `_createRowTemplate`) 2. An HTML string is built up by concatenating the application of the data in each Model in the `modelList` to the row template. For cells with `formatter`s, the function is called to generate cell content. Cells with `nodeFormatter`s are ignored. For all other cells, the data value from the Model attribute for the given column key is used. The accumulated row markup is then inserted into the container. 3. If any column is configured with a `nodeFormatter`, the `modelList` is iterated again to apply the `nodeFormatter`s. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @method render @chainable @since 3.5.0 **/ render: function () { var table = this.get('container'), data = this.get('modelList'), displayCols = this.get('columns'), tbody = this.tbodyNode || (this.tbodyNode = this._createTBodyNode()); // Needed for mutation this._createRowTemplate(displayCols); if (data) { tbody.setHTML(this._createDataHTML(displayCols)); this._applyNodeFormatters(tbody, displayCols); } if (tbody.get('parentNode') !== table) { table.appendChild(tbody); } this.bindUI(); return this; }, /** Refreshes the provided row against the provided model and the Array of columns to be updated. @method refreshRow @param {Node} row @param {Model} model Y.Model representation of the row @param {String[]} colKeys Array of column keys @chainable */ refreshRow: function (row, model, colKeys) { var col, cell, len = colKeys.length, i; for (i = 0; i < len; i++) { col = this.getColumn(colKeys[i]); if (col !== null) { cell = row.one('.' + this.getClassName('col', col._id || col.key)); this.refreshCell(cell, model); } } return this; }, /** Refreshes the given cell with the provided model data and the provided column configuration. Uses the provided column formatter if aviable. @method refreshCell @param {Node} cell Y.Node pointer to the cell element to be updated @param {Model} [model] Y.Model representation of the row @param {Object} [col] Column configuration object for the cell @chainable */ refreshCell: function (cell, model, col) { var content, formatterFn, formatterData, data = model.toJSON(); cell = this.getCell(cell); /* jshint -W030 */ model || (model = this.getRecord(cell)); col || (col = this.getColumn(cell)); /* jshint +W030 */ if (col.nodeFormatter) { formatterData = { cell: cell.one('.' + this.getClassName('liner')) || cell, column: col, data: data, record: model, rowIndex: this._getRowIndex(cell.ancestor('tr')), td: cell, value: data[col.key] }; keep = col.nodeFormatter.call(host,formatterData); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. cell.destroy(true); } } else if (col.formatter) { if (!col._formatterFn) { col = this._setColumnsFormatterFn([col])[0]; } formatterFn = col._formatterFn || null; if (formatterFn) { formatterData = { value : data[col.key], data : data, column : col, record : model, className: '', rowClass : '', rowIndex : this._getRowIndex(cell.ancestor('tr')) }; // Formatters can either return a value ... content = formatterFn.call(this.get('host'), formatterData); // ... or update the value property of the data obj passed if (content === undefined) { content = formatterData.value; } } if (content === undefined || content === null || content === '') { content = col.emptyCellValue || ''; } } else { content = data[col.key] || col.emptyCellValue || ''; } cell.setHTML(col.allowHTML ? content : Y.Escape.html(content)); return this; }, /** Returns column data from this.get('columns'). If a Y.Node is provided as the key, will try to determine the key from the classname @method getColumn @param {String|Node} name @return {Object} Returns column configuration */ getColumn: function (name) { if (name && name._node) { // get column name from node name = name.get('className').match( new RegExp( this.getClassName('col') +'-([^ ]*)' ) )[1]; } if (this.host) { return this.host._columnMap[name] || null; } var displayCols = this.get('columns'), col = null; Y.Array.some(displayCols, function (_col) { if ((_col._id || _col.key) === name) { col = _col; return true; } }); return col; }, // -- Protected and private methods --------------------------------------- /** Handles changes in the source's columns attribute. Redraws the table data. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ // TODO: Preserve existing DOM // This will involve parsing and comparing the old and new column configs // and reacting to four types of changes: // 1. formatter, nodeFormatter, emptyCellValue changes // 2. column deletions // 3. column additions // 4. column moves (preserve cells) _afterColumnsChange: function () { this.render(); }, /** Handles modelList changes, including additions, deletions, and updates. Modifies the existing table DOM accordingly. @method _afterDataChange @param {EventFacade} e The `change` event from the ModelList @protected @since 3.5.0 **/ _afterDataChange: function (e) { var type = (e.type.match(/:(add|change|remove)$/) || [])[1], index = e.index, displayCols = this.get('columns'), col, changed = e.changed && Y.Object.keys(e.changed), key, row, i, len; for (i = 0, len = displayCols.length; i < len; i++ ) { col = displayCols[i]; // since nodeFormatters typcially make changes outside of it's // cell, we need to see if there are any columns that have a // nodeFormatter and if so, we need to do a full render() of the // tbody if (col.hasOwnProperty('nodeFormatter')) { this.render(); this.fire(EV_CONTENT_UPDATE); return; } } // TODO: if multiple rows are being added/remove/swapped, can we avoid the restriping? switch (type) { case 'change': for (i = 0, len = displayCols.length; i < len; i++) { col = displayCols[i]; key = col.key; if (col.formatter && !e.changed[key]) { changed.push(key); } } this.refreshRow(this.getRow(e.target), e.target, changed); break; case 'add': // we need to make sure we don't have an index larger than the data we have index = Math.min(index, this.get('modelList').size() - 1); // updates the columns with formatter functions this._setColumnsFormatterFn(displayCols); row = Y.Node.create(this._createRowHTML(e.model, index, displayCols)); this.tbodyNode.insert(row, index); this._restripe(index); break; case 'remove': this.getRow(index).remove(true); // we removed a row, so we need to back up our index to stripe this._restripe(index - 1); break; default: this.render(); } // Event fired to tell users when we are done updating after the data // was changed this.fire(EV_CONTENT_UPDATE); }, /** Toggles the odd/even classname of the row after the given index. This method is used to update rows after a row is inserted into or removed from the table. Note this event is delayed so the table is only restriped once when multiple rows are updated at one time. @protected @method _restripe @param {Number} [index] Index of row to start restriping after @since 3.11.0 */ _restripe: function (index) { var task = this._restripeTask, self; // index|0 to force int, avoid NaN. Math.max() to avoid neg indexes. index = Math.max((index|0), 0); if (!task) { self = this; this._restripeTask = { timer: setTimeout(function () { // Check for self existence before continuing if (!self || self.get('destroy') || !self.tbodyNode || !self.tbodyNode.inDoc()) { self._restripeTask = null; return; } var odd = [self.CLASS_ODD, self.CLASS_EVEN], even = [self.CLASS_EVEN, self.CLASS_ODD], index = self._restripeTask.index; self.tbodyNode.get('childNodes') .slice(index) .each(function (row, i) { // TODO: each vs batch row.replaceClass.apply(row, (index + i) % 2 ? even : odd); }); self._restripeTask = null; }, 0), index: index }; } else { task.index = Math.min(task.index, index); } }, /** Handles replacement of the modelList. Rerenders the `<tbody>` contents. @method _afterModelListChange @param {EventFacade} e The `modelListChange` event @protected @since 3.6.0 **/ _afterModelListChange: function () { var handles = this._eventHandles; if (handles.dataChange) { handles.dataChange.detach(); delete handles.dataChange; this.bindUI(); } if (this.tbodyNode) { this.render(); } }, /** Iterates the `modelList`, and calls any `nodeFormatter`s found in the `columns` param on the appropriate cell Nodes in the `tbody`. @method _applyNodeFormatters @param {Node} tbody The `<tbody>` Node whose columns to update @param {Object[]} displayCols The column configurations @protected @since 3.5.0 **/ _applyNodeFormatters: function (tbody, displayCols) { var host = this.host || this, data = this.get('modelList'), formatters = [], linerQuery = '.' + this.getClassName('liner'), rows, i, len; // Only iterate the ModelList again if there are nodeFormatters for (i = 0, len = displayCols.length; i < len; ++i) { if (displayCols[i].nodeFormatter) { formatters.push(i); } } if (data && formatters.length) { rows = tbody.get('childNodes'); data.each(function (record, index) { var formatterData = { data : record.toJSON(), record : record, rowIndex : index }, row = rows.item(index), i, len, col, key, cells, cell, keep; if (row) { cells = row.get('childNodes'); for (i = 0, len = formatters.length; i < len; ++i) { cell = cells.item(formatters[i]); if (cell) { col = formatterData.column = displayCols[formatters[i]]; key = col.key || col.id; formatterData.value = record.get(key); formatterData.td = cell; formatterData.cell = cell.one(linerQuery) || cell; keep = col.nodeFormatter.call(host,formatterData); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. cell.destroy(true); } } } } }); } }, /** Binds event subscriptions from the UI and the host (if assigned). @method bindUI @protected @since 3.5.0 **/ bindUI: function () { var handles = this._eventHandles, modelList = this.get('modelList'), changeEvent = modelList.model.NAME + ':change'; if (!handles.columnsChange) { handles.columnsChange = this.after('columnsChange', bind('_afterColumnsChange', this)); } if (modelList && !handles.dataChange) { handles.dataChange = modelList.after( ['add', 'remove', 'reset', changeEvent], bind('_afterDataChange', this)); } }, /** Iterates the `modelList` and applies each Model to the `_rowTemplate`, allowing any column `formatter` or `emptyCellValue` to override cell content for the appropriate column. The aggregated HTML string is returned. @method _createDataHTML @param {Object[]} displayCols The column configurations to customize the generated cell content or class names @return {String} The markup for all Models in the `modelList`, each applied to the `_rowTemplate` @protected @since 3.5.0 **/ _createDataHTML: function (displayCols) { var data = this.get('modelList'), html = ''; if (data) { data.each(function (model, index) { html += this._createRowHTML(model, index, displayCols); }, this); } return html; }, /** Applies the data of a given Model, modified by any column formatters and supplemented by other template values to the instance's `_rowTemplate` (see `_createRowTemplate`). The generated string is then returned. The data from Model's attributes is fetched by `toJSON` and this data object is appended with other properties to supply values to {placeholders} in the template. For a template generated from a Model with 'foo' and 'bar' attributes, the data object would end up with the following properties before being used to populate the `_rowTemplate`: * `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute. * `foo` - The value to populate the 'foo' column cell content. This value will be the value stored in the Model's `foo` attribute, or the result of the column's `formatter` if assigned. If the value is '', `null`, or `undefined`, and the column's `emptyCellValue` is assigned, that value will be used. * `bar` - Same for the 'bar' column cell content. * `foo-className` - String of CSS classes to apply to the `<td>`. * `bar-className` - Same. * `rowClass` - String of CSS classes to apply to the `<tr>`. This will be the odd/even class per the specified index plus any additional classes assigned by column formatters (via `o.rowClass`). Because this object is available to formatters, any additional properties can be added to fill in custom {placeholders} in the `_rowTemplate`. @method _createRowHTML @param {Model} model The Model instance to apply to the row template @param {Number} index The index the row will be appearing @param {Object[]} displayCols The column configurations @return {String} The markup for the provided Model, less any `nodeFormatter`s @protected @since 3.5.0 **/ _createRowHTML: function (model, index, displayCols) { var data = model.toJSON(), clientId = model.get('clientId'), values = { rowId : this._getRowId(clientId), clientId: clientId, rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN }, host = this.host || this, i, len, col, token, value, formatterData; for (i = 0, len = displayCols.length; i < len; ++i) { col = displayCols[i]; value = data[col.key]; token = col._id || col.key; values[token + '-className'] = ''; if (col._formatterFn) { formatterData = { value : value, data : data, column : col, record : model, className: '', rowClass : '', rowIndex : index }; // Formatters can either return a value value = col._formatterFn.call(host, formatterData); // or update the value property of the data obj passed if (value === undefined) { value = formatterData.value; } values[token + '-className'] = formatterData.className; values.rowClass += ' ' + formatterData.rowClass; } // if the token missing OR is the value a legit value if (!values.hasOwnProperty(token) || data.hasOwnProperty(col.key)) { if (value === undefined || value === null || value === '') { value = col.emptyCellValue || ''; } values[token] = col.allowHTML ? value : htmlEscape(value); } } // replace consecutive whitespace with a single space values.rowClass = values.rowClass.replace(/\s+/g, ' '); return fromTemplate(this._rowTemplate, values); }, /** Locates the row within the tbodyNode and returns the found index, or Null if it is not found in the tbodyNode @param {Node} row @return {Number} Index of row in tbodyNode */ _getRowIndex: function (row) { var tbody = this.tbodyNode, index = 1; if (tbody && row) { //if row is not in the tbody, return if (row.ancestor('tbody') !== tbody) { return null; } // increment until we no longer have a previous node /*jshint boss: true*/ while (row = row.previous()) { // NOTE: assignment /*jshint boss: false*/ index++; } } return index; }, /** Creates a custom HTML template string for use in generating the markup for individual table rows with {placeholder}s to capture data from the Models in the `modelList` attribute or from column `formatter`s. Assigns the `_rowTemplate` property. @method _createRowTemplate @param {Object[]} displayCols Array of column configuration objects @protected @since 3.5.0 **/ _createRowTemplate: function (displayCols) { var html = '', cellTemplate = this.CELL_TEMPLATE, i, len, col, key, token, headers, tokenValues, formatter; this._setColumnsFormatterFn(displayCols); for (i = 0, len = displayCols.length; i < len; ++i) { col = displayCols[i]; key = col.key; token = col._id || key; formatter = col._formatterFn; // Only include headers if there are more than one headers = (col._headers || []).length > 1 ? 'headers="' + col._headers.join(' ') + '"' : ''; tokenValues = { content : '{' + token + '}', headers : headers, className: this.getClassName('col', token) + ' ' + (col.className || '') + ' ' + this.getClassName('cell') + ' {' + token + '-className}' }; if (!formatter && col.formatter) { tokenValues.content = col.formatter.replace(valueRegExp, tokenValues.content); } if (col.nodeFormatter) { // Defer all node decoration to the formatter tokenValues.content = ''; } html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues); } this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, { content: html }); }, /** Parses the columns array and defines the column's _formatterFn if there is a formatter available on the column @protected @method _setColumnsFormatterFn @param {Object[]} displayCols Array of column configuration objects @return {Object[]} Returns modified displayCols configuration Array */ _setColumnsFormatterFn: function (displayCols) { var Formatters = Y.DataTable.BodyView.Formatters, formatter, col, i, len; for (i = 0, len = displayCols.length; i < len; i++) { col = displayCols[i]; formatter = col.formatter; if (!col._formatterFn && formatter) { if (Lang.isFunction(formatter)) { col._formatterFn = formatter; } else if (formatter in Formatters) { col._formatterFn = Formatters[formatter].call(this.host || this, col); } } } return displayCols; }, /** Creates the `<tbody>` node that will store the data rows. @method _createTBodyNode @return {Node} @protected @since 3.6.0 **/ _createTBodyNode: function () { return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, { className: this.getClassName('data') })); }, /** Destroys the instance. @method destructor @protected @since 3.5.0 **/ destructor: function () { (new Y.EventHandle(YObject.values(this._eventHandles))).detach(); }, /** Holds the event subscriptions needing to be detached when the instance is `destroy()`ed. @property _eventHandles @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_eventHandles: null, /** Returns the row ID associated with a Model's clientId. @method _getRowId @param {String} clientId The Model clientId @return {String} @protected **/ _getRowId: function (clientId) { return this._idMap[clientId] || (this._idMap[clientId] = Y.guid()); }, /** Map of Model clientIds to row ids. @property _idMap @type {Object} @protected **/ //_idMap, /** Initializes the instance. Reads the following configuration properties in addition to the instance attributes: * `columns` - (REQUIRED) The initial column information * `host` - The object to serve as source of truth for column info and for generating class names @method initializer @param {Object} config Configuration data @protected @since 3.5.0 **/ initializer: function (config) { this.host = config.host; this._eventHandles = { modelListChange: this.after('modelListChange', bind('_afterModelListChange', this)) }; this._idMap = {}; this.CLASS_ODD = this.getClassName('odd'); this.CLASS_EVEN = this.getClassName('even'); } /** The HTML template used to create a full row of markup for a single Model in the `modelList` plus any customizations defined in the column configurations. @property _rowTemplate @type {String} @default (initially unset) @protected @since 3.5.0 **/ //_rowTemplate: null },{ /** Hash of formatting functions for cell contents. This property can be populated with a hash of formatting functions by the developer or a set of pre-defined functions can be loaded via the `datatable-formatters` module. See: [DataTable.BodyView.Formatters](./DataTable.BodyView.Formatters.html) @property Formatters @type Object @since 3.8.0 @static **/ Formatters: {} }); }, '3.17.2', {"requires": ["datatable-core", "view", "classnamemanager"]});
screens/ProductsScreen/Products.js
nattatorn-dev/expo-with-realworld
import React from 'react' import { ScrollView, StyleSheet, TouchableOpacity, View } from 'react-native' import PropTypes from 'prop-types' import { object, url } from 'utilities' import ProductDetail from './ProductDetail' const styles = StyleSheet.create( { container: { // marginTop: 10, }, } ) const Products = ( { onPressSelectProduct, products } ) => { const renderProducts = () => Object.keys( products ).map( ( e, k ) => ( <TouchableOpacity key={`product-touch-${ products[ e ].name }-${ k }`} onPress={() => onPressSelectProduct( e, products[ e ].name )} > <ProductDetail key={`product-${ products[ e ].name }-${ k }`} productImage={url.image100x100( 'products', object.getFirstByKey( { item: products[ e ].urls, key: 'imgsName', } ) )} productHeading={products[ e ].name} /> </TouchableOpacity> ) ) return ( <ScrollView> <View style={styles.container}>{renderProducts()}</View> </ScrollView> ) } Products.propTypes = { navigation: PropTypes.object.isRequired, onPressSelectProduct: PropTypes.func.isRequired, products: PropTypes.object.isRequired, } export default Products
barebones_bbb/src/components/PageHeader/PageHeader.js
wasong/cmpt433
import React from 'react' import PropTypes from 'prop-types' import Radium from 'radium' const styles = { root: { width: '100%', fontSize: 36, }, } const PageHeader = ({ title }) => ( <div style={styles.root}>{title}</div> ) PageHeader.propTypes = { title: PropTypes.string, } PageHeader.defaultProps = { title: 'Node JS Application', } export default Radium(PageHeader)
jenkins-design-language/src/js/components/material-ui/svg-icons/image/looks.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageLooks = (props) => ( <SvgIcon {...props}> <path d="M12 10c-3.86 0-7 3.14-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.86-3.14-7-7-7zm0-4C5.93 6 1 10.93 1 17h2c0-4.96 4.04-9 9-9s9 4.04 9 9h2c0-6.07-4.93-11-11-11z"/> </SvgIcon> ); ImageLooks.displayName = 'ImageLooks'; ImageLooks.muiName = 'SvgIcon'; export default ImageLooks;
src/Table.js
moimikey/react-data-components
import React, { Component } from 'react'; import PropTypes from 'prop-types'; const simpleGet = key => data => data[key]; const keyGetter = keys => data => keys.map(key => data[key]); const isEmpty = value => value == null || value === ''; const getCellValue = ({ prop, defaultContent, render }, row) => // Return `defaultContent` if the value is empty. !isEmpty(prop) && isEmpty(row[prop]) ? defaultContent : // Use the render function for the value. render ? render(row[prop], row) : // Otherwise just return the value. row[prop]; const getCellClass = ({ prop, className }, row) => !isEmpty(prop) && isEmpty(row[prop]) ? 'empty-cell' : typeof className == 'function' ? className(row[prop], row) : className; function buildSortProps(col, sortBy, onSort) { const order = sortBy && sortBy.prop === col.prop ? sortBy.order : 'none'; const nextOrder = order === 'ascending' ? 'descending' : 'ascending'; const sortEvent = onSort.bind(null, { prop: col.prop, order: nextOrder }); return { onClick: sortEvent, // Fire the sort event on enter. onKeyDown: e => { if (e.keyCode === 13) sortEvent(); }, // Prevents selection with mouse. onMouseDown: e => e.preventDefault(), tabIndex: 0, 'aria-sort': order, 'aria-label': `${col.title}: activate to sort column ${nextOrder}`, }; } export default class Table extends Component { _headers = []; static propTypes = { keys: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.string), PropTypes.string, ]).isRequired, columns: PropTypes.arrayOf( PropTypes.shape({ title: PropTypes.string.isRequired, prop: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), render: PropTypes.func, sortable: PropTypes.bool, defaultContent: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), className: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), }), ).isRequired, dataArray: PropTypes.arrayOf( PropTypes.oneOfType([PropTypes.array, PropTypes.object]), ).isRequired, buildRowOptions: PropTypes.func, sortBy: PropTypes.shape({ prop: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), order: PropTypes.oneOf(['ascending', 'descending']), }), onSort: PropTypes.func, }; componentDidMount() { // If no width was specified, then set the width that the browser applied // initially to avoid recalculating width between pages. this._headers.forEach(header => { if (!header.style.width) { header.style.width = `${header.offsetWidth}px`; } }); } render() { const { columns, keys, buildRowOptions, sortBy, onSort, dataArray, ...otherProps } = this.props; const headers = columns.map((col, idx) => { let sortProps, order; // Only add sorting events if the column has a property and is sortable. if (onSort && col.sortable !== false && 'prop' in col) { sortProps = buildSortProps(col, sortBy, onSort); order = sortProps['aria-sort']; } return ( <th ref={c => (this._headers[idx] = c)} key={idx} style={{ width: col.width }} role="columnheader" scope="col" {...sortProps} > <span> {col.title} </span> {!order ? null : <span className={`sort-icon sort-${order}`} aria-hidden="true" />} </th> ); }); const getKeys = Array.isArray(keys) ? keyGetter(keys) : simpleGet(keys); const rows = dataArray.map(row => { const trProps = buildRowOptions ? buildRowOptions(row) : {}; return ( <tr key={getKeys(row)} {...trProps}> {columns.map((col, i) => <td key={i} className={getCellClass(col, row)}> {getCellValue(col, row)} </td>, )} </tr> ); }); return ( <table {...otherProps}> {!sortBy ? null : <caption className="sr-only" role="alert" aria-live="polite"> {`Sorted by ${sortBy.prop}: ${sortBy.order} order`} </caption>} <thead> <tr> {headers} </tr> </thead> <tbody> {rows.length ? rows : <tr> <td colSpan={columns.length} className="text-center"> No data </td> </tr>} </tbody> </table> ); } }
packages/material-ui/src/Stepper/Step.js
cherniavskii/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; export const styles = theme => ({ root: {}, horizontal: { paddingLeft: theme.spacing.unit, paddingRight: theme.spacing.unit, '&:first-child': { paddingLeft: 0, }, '&:last-child': { paddingRight: 0, }, }, vertical: {}, alternativeLabel: { flex: 1, position: 'relative', }, }); function Step(props) { const { active, alternativeLabel, children, classes, className: classNameProp, completed, connector, disabled, index, last, orientation, ...other } = props; const className = classNames( classes.root, classes[orientation], { [classes.alternativeLabel]: alternativeLabel, }, classNameProp, ); return ( <div className={className} {...other}> {React.Children.map(children, child => React.cloneElement(child, { active, alternativeLabel, completed, disabled, icon: index + 1, last, orientation, ...child.props, }), )} {connector && alternativeLabel && !last && React.cloneElement(connector, { orientation, alternativeLabel })} </div> ); } Step.propTypes = { /** * Sets the step as active. Is passed to child components. */ active: PropTypes.bool, /** * @ignore * Set internally by Stepper when it's supplied with the alternativeLabel property. */ alternativeLabel: PropTypes.bool, /** * Should be `Step` sub-components such as `StepLabel`, `StepContent`. */ children: PropTypes.node, /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * Mark the step as completed. Is passed to child components. */ completed: PropTypes.bool, /** * @ignore * Passed down from Stepper if alternativeLabel is also set. */ connector: PropTypes.element, /** * Mark the step as disabled, will also disable the button if * `StepButton` is a child of `Step`. Is passed to child components. */ disabled: PropTypes.bool, /** * @ignore * Used internally for numbering. */ index: PropTypes.number, /** * @ignore */ last: PropTypes.bool, /** * @ignore */ orientation: PropTypes.oneOf(['horizontal', 'vertical']), }; Step.defaultProps = { active: false, completed: false, disabled: false, }; export default withStyles(styles, { name: 'MuiStep' })(Step);
ceephax/components/head/index.js
mrceephax/ceephax.com.frontend
import React from 'react'; import { connect } from 'react-redux'; import { Helmet } from 'react-helmet'; class Head extends React.Component { render() { const { title } = this.props.pageTitle; return ( <Helmet> <meta charSet="utf-8" /> <title>{title}</title> </Helmet> ); } } export default connect(({ pageTitle }) => ({ pageTitle }))(Head);
react-flux-mui/js/material-ui/src/svg-icons/action/assignment-late.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAssignmentLate = (props) => ( <SvgIcon {...props}> <path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-6 15h-2v-2h2v2zm0-4h-2V8h2v6zm-1-9c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/> </SvgIcon> ); ActionAssignmentLate = pure(ActionAssignmentLate); ActionAssignmentLate.displayName = 'ActionAssignmentLate'; ActionAssignmentLate.muiName = 'SvgIcon'; export default ActionAssignmentLate;
src/routes/content/index.js
dreambo8563/RSK
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import ExcelTable from './../../components/ExcelTable/ExcelTable' // import SimpleChartComponent from './../../components/Chart/Chart' // import Content from './Content'; // import fetch from '../../core/fetch'; export default { path: '/content', async action(context) { // eslint-disable-line react/prop-types // const resp = await fetch('/graphql', { // method: 'post', // headers: { // Accept: 'application/json', // 'Content-Type': 'application/json', // }, // body: JSON.stringify({ // query: `{content(path:"${path}"){path,title,content,component}}`, // }), // credentials: 'include', // }); // if (resp.status !== 200) throw new Error(resp.statusText); // const { data } = await resp.json(); // if (!data || !data.content) return undefined; console.log('before require'); // var SimpleChartComponent = await new Promise((resolve) => { // require.ensure([], (require) => // resolve(require('./../../components/Chart/Chart').default)); // }); // the config structure for the excel const config = { type: 'horizontal', // horizontal data: [ { header: 'aaa', value: [1, 2, 3, 4, 5, 6, 6, 6, 6] }, { header: 'aaa', value: [1, 2, 3, 4, 5, 6, 6, 6, 6] }, ], } // <SimpleChartComponent /> return (<div > <ExcelTable data={config} /> </div >); // const ExcelTable = await new Promise((resolve) => { // require.ensure([], (require) => // resolve(require('./../../components/ExcelTable/ExcelTable').default)); // }); }, };
frontend/react-slingshot/src/components/NotFoundPage.js
ggchan0/git_diffed
import React from 'react'; import { Link } from 'react-router'; const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
src/components/Profile/AddService.js
RegOpz/RegOpzWebApp
import React, { Component } from 'react'; import { FormControl, FormGroup, ControlLabel, Button } from 'react-bootstrap'; import { connect } from 'react-redux'; import { bindActionCreators, dispatch } from 'redux'; import { actionFetchALLServices } from './../../actions/CustomizeDashAction'; class AddService extends Component { constructor(props) { super(props); let apis = []; for (let i = 0; i < this.props.apis.length; i++) { apis.push({ value: this.props.apis[i], data: this.props.apis[i] + ' Data' }); } this.state = { APIs: apis, currentAPI: this.props.apis[0], currentChart: '1', currentTile: '1' }; this.handleSubmit = this.handleSubmit.bind(this); this.handleAPIChange = this.handleAPIChange.bind(this); this.handleChartChange = this.handleChartChange.bind(this); this.handleTileChange = this.handleTileChange.bind(this); } componentWillMount() { this.props.fetchAllServices(); } componentWillReceiveProps(nextProps) { console.log(nextProps); let apis = []; for (let i = 0; i < nextProps.apis.length; i++) { apis.push({ value: nextProps.apis[i], data: nextProps.apis[i] + ' Data' }); } this.setState({ APIs: apis, currentAPI: nextProps.apis[0] }); } handleAPIChange(event) { this.setState({ currentAPI: event.target.value }); } handleChartChange(event) { this.setState({ currentChart: event.target.value }); } handleTileChange(event) { this.setState({ currentTile: event.target.value }); } handleSubmit(event) { event.preventDefault(); let API = this.state.currentAPI; let chart = this.state.currentChart; let tile = this.state.currentTile; this.props.addService(API, chart, tile); } render() { return ( <div style={{ padding: '7px' }}> <form onSubmit={this.handleSubmit}> <FormGroup controlId="formAPISelect"> <ControlLabel>Select API:</ControlLabel> <FormControl componentClass="select" placeholder="Select API:" onChange={this.handleAPIChange}> { this.state.APIs.map(element => { return ( <option value={element.value} key={element.value}>{element.data}</option> ); }) } </FormControl> </FormGroup> <FormGroup controlId="chartTypeSelect"> <ControlLabel>Select Type of Chart:</ControlLabel> <FormControl componentClass="select" placeholder="Select Chart:" onChange={this.handleChartChange}> <option value="1">Bar</option> <option value="2">Line</option> <option value="3">Pie</option> </FormControl> </FormGroup> <FormGroup controlId="tileSizeSelect"> <ControlLabel>Select Tile Size:</ControlLabel> <FormControl componentClass="select" placeholder="Select Tile:" onChange={this.handleTileChange}> <option value="1">One Third</option> <option value="2">Half</option> <option value="3">Full Width</option> </FormControl> </FormGroup> <Button type="submit"> Submit </Button> </form> </div> ); } } function mapStateToProps(state) { return { apis: state.api_details }; } const matchDispatchToProps = (dispatch) => { return { fetchAllServices: () => { dispatch(actionFetchALLServices()); } } } export default connect(mapStateToProps, matchDispatchToProps)(AddService);
src/Interpolate.js
pieter-lazzaro/react-bootstrap
// https://www.npmjs.org/package/react-interpolate-component // TODO: Drop this in favor of es6 string interpolation import React from 'react'; import ValidComponentChildren from './utils/ValidComponentChildren'; const REGEXP = /\%\((.+?)\)s/; const Interpolate = React.createClass({ displayName: 'Interpolate', propTypes: { component: React.PropTypes.node, format: React.PropTypes.string, unsafe: React.PropTypes.bool }, getDefaultProps() { return { component: 'span', unsafe: false }; }, render() { let format = (ValidComponentChildren.hasValidComponent(this.props.children) || (typeof this.props.children === 'string')) ? this.props.children : this.props.format; let parent = this.props.component; let unsafe = this.props.unsafe === true; let props = {...this.props}; delete props.children; delete props.format; delete props.component; delete props.unsafe; if (unsafe) { let content = format.split(REGEXP).reduce(function(memo, match, index) { let html; if (index % 2 === 0) { html = match; } else { html = props[match]; delete props[match]; } if (React.isValidElement(html)) { throw new Error('cannot interpolate a React component into unsafe text'); } memo += html; return memo; }, ''); props.dangerouslySetInnerHTML = { __html: content }; return React.createElement(parent, props); } else { let kids = format.split(REGEXP).reduce(function(memo, match, index) { let child; 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 React.createElement(parent, props, kids); } } }); export default Interpolate;
ajax/libs/forerunnerdb/1.3.9/fdb-all.min.js
wil93/cdnjs
/* MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors MIT License (c) copyright 2010-2014 original author or authors */ (function(H){"object"===typeof exports&&"undefined"!==typeof module?module.exports=H():"function"===typeof define&&define.amd?define([],H):("undefined"!==typeof window?window:"undefined"!==typeof global?global:"undefined"!==typeof self?self:this).ForerunnerDB=H()})(function(){return function g(k,h,f){function b(a,m){if(!h[a]){if(!k[a]){var e="function"==typeof require&&require;if(!m&&e)return e(a,!0);if(d)return d(a,!0);e=Error("Cannot find module '"+a+"'");throw e.code="MODULE_NOT_FOUND",e;}e=h[a]= {exports:{}};k[a][0].call(e.exports,function(n){var e=k[a][1][n];return b(e?e:n)},e,e.exports,g,k,h,f)}return h[a].exports}for(var d="function"==typeof require&&require,a=0;a<f.length;a++)b(f[a]);return b}({1:[function(g,k,h){h=g("./core");g("../lib/CollectionGroup");g("../lib/View");g("../lib/Highchart");g("../lib/Persist");g("../lib/Document");g("../lib/Overview");g("../lib/Grid");g("../lib/Rest");k.exports=h},{"../lib/CollectionGroup":5,"../lib/Document":8,"../lib/Grid":9,"../lib/Highchart":10, "../lib/Overview":25,"../lib/Persist":27,"../lib/Rest":29,"../lib/View":32,"./core":2}],2:[function(g,k,h){h=g("../lib/Core");g("../lib/Shim.IE8");k.exports=h},{"../lib/Core":6,"../lib/Shim.IE8":31}],3:[function(g,k,h){h=g("./Shared");g("./Path");g=function(f){var b;this._primaryKey="_id";this._keyArr=[];this._data=[];this._objLookup={};this._count=0;for(b in f)f.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:f[b]})};h.addModule("ActiveBucket",g);h.synthesize(g.prototype,"primaryKey");h.mixin(g.prototype, "Mixin.Sorting");g.prototype.qs=function(f,b,d,a){if(!b.length)return 0;for(var c=-1,m,e,n=0,y=b.length-1;y>=n;){m=Math.floor((n+y)/2);if(c===m)break;c=b[m];void 0!==c&&(e=a(this,f,d,c),0<e&&(n=m+1),0>e&&(y=m-1));c=m}return 0<e?m+1:m};g.prototype._sortFunc=function(f,b,d,a){d=d.split(".:.");a=a.split(".:.");var c=f._keyArr,m=c.length,e,n,y;for(e=0;e<m;e++)if(n=c[e],y=typeof b[n.key],"number"===y&&(d[e]=Number(d[e]),a[e]=Number(a[e])),d[e]!==a[e]){if(1===n.dir)return f.sortAsc(d[e],a[e]);if(-1===n.dir)return f.sortDesc(d[e], a[e])}};g.prototype.insert=function(f){var b,d;b=this.documentKey(f);d=this._data.indexOf(b);-1===d&&(d=this.qs(f,this._data,b,this._sortFunc));this._data.splice(d,0,b);this._objLookup[f[this._primaryKey]]=b;this._count++;return d};g.prototype.remove=function(f){var b;if(b=this._objLookup[f[this._primaryKey]])if(b=this._data.indexOf(b),-1<b)return this._data.splice(b,1),delete this._objLookup[f[this._primaryKey]],this._count--,!0;return!1};g.prototype.index=function(f){var b,d;b=this.documentKey(f); d=this._data.indexOf(b);-1===d&&(d=this.qs(f,this._data,b,this._sortFunc));return d};g.prototype.documentKey=function(f){var b="",d=this._keyArr,a=d.length,c,m;for(c=0;c<a;c++)m=d[c],b&&(b+=".:."),b+=f[m.key];return b+=".:."+f[this._primaryKey]};g.prototype.count=function(){return this._count};h.finishModule("ActiveBucket");k.exports=g},{"./Path":26,"./Shared":30}],4:[function(g,k,h){var f,b,d,a,c,m;h=g("./Shared");var e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._primaryKey= "_id";this._primaryIndex=new b("primary");this._primaryCrc=new b("primaryCrc");this._crcLookup=new b("crcLookup");this._name=a;this._data=[];this._groups=[];this._metrics=new f;this._deferQueue={insert:[],update:[],remove:[],upsert:[]};this._deferThreshold={insert:100,update:100,remove:100,upsert:100};this._deferTime={insert:1,update:1,remove:1,upsert:1};this._subsetOf(this)};h.addModule("Collection",e);h.mixin(e.prototype,"Mixin.Common");h.mixin(e.prototype,"Mixin.Events");h.mixin(e.prototype,"Mixin.ChainReactor"); h.mixin(e.prototype,"Mixin.CRUD");h.mixin(e.prototype,"Mixin.Constants");h.mixin(e.prototype,"Mixin.Triggers");h.mixin(e.prototype,"Mixin.Sorting");h.mixin(e.prototype,"Mixin.Matching");f=g("./Metrics");b=g("./KeyValueStore");d=g("./Path");a=g("./IndexHashMap");c=g("./IndexBinaryTree");m=g("./Crc");g=h.modules.Core;e.prototype.crc=m;h.synthesize(e.prototype,"state");h.synthesize(e.prototype,"name");e.prototype.data=function(){return this._data};e.prototype.drop=function(){if("dropped"!==this._state){if(this._db&& this._db._collection&&this._name){this.debug()&&console.log("Dropping collection "+this._name);this._state="dropped";this.emit("drop",this);delete this._db._collection[this._name];if(this._groups&&this._groups.length){var a=[],c;for(c=0;c<this._groups.length;c++)a.push(this._groups[c]);for(c=0;c<a.length;c++)this._groups[c].removeCollection(this)}delete this._primaryKey;delete this._primaryIndex;delete this._primaryCrc;delete this._crcLookup;delete this._name;delete this._data;delete this._groups; delete this._metrics;return!0}}else return!0;return!1};e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey};e.prototype._onInsert=function(a,c){this.emit("insert",a,c)};e.prototype._onUpdate=function(a){this.emit("update",a)};e.prototype._onRemove=function(a){this.emit("remove",a)};h.synthesize(e.prototype,"db",function(a){a&&"_id"===this.primaryKey()&&this.primaryKey(a.primaryKey()); return this.$super.apply(this,arguments)});e.prototype.setData=function(a,c,b){if(a){var e=this._metrics.create("setData");e.start();c=this.options(c);this.preSetData(a,c,b);c.$decouple&&(a=this.decouple(a));a instanceof Array||(a=[a]);e.time("transformIn");a=this.transformIn(a);e.time("transformIn");var d=[].concat(this._data);this._dataReplace(a);e.time("Rebuild Primary Key Index");this.rebuildPrimaryKeyIndex(c);e.time("Rebuild Primary Key Index");e.time("Rebuild All Other Indexes");this._rebuildIndexes(); e.time("Rebuild All Other Indexes");e.time("Resolve chains");this.chainSend("setData",a,{oldData:d});e.time("Resolve chains");e.stop();this.emit("setData",this._data,d)}b&&b(!1);return this};e.prototype.rebuildPrimaryKeyIndex=function(a){var c=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0;a=a&&void 0!==a.$violationCheck?a.$violationCheck:!0;var b,e,d,f=this._primaryIndex,m=this._primaryCrc,g=this._crcLookup,h=this._primaryKey,k;f.truncate();m.truncate();g.truncate();b=this._data;for(e=b.length;e--;){d= b[e];c&&this.ensurePrimaryKey(d);if(a){if(!f.uniqueSet(d[h],d))throw'ForerunnerDB.Collection "'+this.name()+'": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: '+d[this._primaryKey];}else f.set(d[h],d);k=JSON.stringify(d);m.set(d[h],k);g.set(k,d)}};e.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())};e.prototype.truncate=function(){this.emit("truncate", this._data);this._data.length=0;this._primaryIndex=new b("primary");this._primaryCrc=new b("primaryCrc");this._crcLookup=new b("crcLookup");this.deferEmit("change",{type:"truncate"});return this};e.prototype.upsert=function(a,c){if(a){var b=this._deferQueue.upsert,e=this._deferThreshold.upsert,d={},f;if(a instanceof Array){if(a.length>e)return this._deferQueue.upsert=b.concat(a),this.processQueue("upsert",c),{};d=[];for(b=0;b<a.length;b++)d.push(this.upsert(a[b]));c&&c();return d}a[this._primaryKey]? (f={},f[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(f)[0]?d.op="update":d.op="insert"):d.op="insert";switch(d.op){case "insert":d.result=this.insert(a);break;case "update":d.result=this.update(f,a)}return d}c&&c();return{}};e.prototype.update=function(a,c,b){c=this.decouple(c);c=this.transformIn(c);this.debug()&&console.log('Updating some collection data for collection "'+this.name()+'"');var e=this,d=this._metrics.create("update"),f,m,g=function(f){var m=e.decouple(f),g,l;if(e.willTrigger(e.TYPE_UPDATE, e.PHASE_BEFORE)||e.willTrigger(e.TYPE_UPDATE,e.PHASE_AFTER)){g={type:"update",query:e.decouple(a),update:e.decouple(c),options:e.decouple(b),op:d};if(!1===e.processTrigger(g,e.TYPE_UPDATE,e.PHASE_BEFORE,m)||e.willTrigger(e.TYPE_UPDATE,e.PHASE_BEFORE)&&(l=e.updateObject(m,g.update,g.query,g.options,""))&&!1===e.processTrigger(g,e.TYPE_UPDATE,e.PHASE_AFTER,f,m))return!1;l=e.updateObject(f,g.update,g.query,g.options,"")}else l=e.updateObject(f,c,a,b,"");return l};d.start();d.time("Retrieve documents to update"); f=this.find(a,{$decouple:!1});d.time("Retrieve documents to update");f.length&&(d.time("Update documents"),m=f.filter(g),d.time("Update documents"),m.length&&(d.time("Resolve chains"),this.chainSend("update",{query:a,update:c,dataSet:f},b),d.time("Resolve chains"),this._onUpdate(m),this.deferEmit("change",{type:"update",data:m})));d.stop();return m||[]};e.prototype._replaceObj=function(a,c){var e;this._removeFromIndexes(a);for(e in a)a.hasOwnProperty(e)&&delete a[e];for(e in c)c.hasOwnProperty(e)&& (a[e]=c[e]);if(!this._insertIntoIndexes(a))throw'ForerunnerDB.Collection "'+this.name()+'": Primary key violation in update! Key violated: '+a[this._primaryKey];return!0};e.prototype.updateById=function(a,c){var e={};e[this._primaryKey]=a;return this.update(e,c)};e.prototype.updateObject=function(a,c,e,b,f,m){c=this.decouple(c);f=f||"";"."===f.substr(0,1)&&(f=f.substr(1,f.length-1));this.decouple(a);var g=!1,s=!1,h,k,r,l;for(l in c)if(c.hasOwnProperty(l)){h=!1;if("$"===l.substr(0,1))switch(l){case "$key":case "$index":h= !0;break;default:h=!0,s=this.updateObject(a,c[l],e,b,f,l),g=g||s}if(this._isPositionalKey(l)&&(h=!0,l=l.substr(0,l.length-2),s=new d(f+"."+l),a[l]&&a[l]instanceof Array&&a[l].length)){k=[];for(r=0;r<a[l].length;r++)this._match(a[l][r],s.value(e)[0])&&k.push(r);for(r=0;r<k.length;r++)s=this.updateObject(a[l][k[r]],c[l+".$"],e,b,f+"."+l,m),g=g||s}if(!h)if(m||"object"!==typeof c[l])switch(m){case "$inc":this._updateIncrement(a,l,c[l]);g=!0;break;case "$push":void 0===a[l]&&this._updateProperty(a,l,[]); if(a[l]instanceof Array){if(void 0!==c[l].$position&&c[l].$each instanceof Array)for(s=c[l].$position,h=c[l].$each.length,r=0;r<h;r++)this._updateSplicePush(a[l],s+r,c[l].$each[r]);else if(c[l].$each instanceof Array)for(h=c[l].$each.length,r=0;r<h;r++)this._updatePush(a[l],c[l].$each[r]);else this._updatePush(a[l],c[l]);g=!0}else throw'ForerunnerDB.Collection "'+this.name()+'": Cannot push to a key that is not an array! ('+l+")";break;case "$pull":if(a[l]instanceof Array){k=[];for(r=0;r<a[l].length;r++)this._match(a[l][r], c[l])&&k.push(r);for(h=k.length;h--;)this._updatePull(a[l],k[h]),g=!0}break;case "$pullAll":if(a[l]instanceof Array)if(c[l]instanceof Array){if(k=a[l],h=k.length,0<h)for(;h--;){for(s=0;s<c[l].length;s++)k[h]===c[l][s]&&(this._updatePull(a[l],h),h--,g=!0);if(0>h)break}}else throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pullAll without being given an array of values to pull! ('+l+")";break;case "$addToSet":void 0===a[l]&&this._updateProperty(a,l,[]);if(a[l]instanceof Array){r=a[l];var x;k= r.length;var B;h=!0;x=b&&b.$addToSet;var A;c[l].$key?(s=!1,A=new d(c[l].$key),B=A.value(c[l])[0],delete c[l].$key):x&&x.key?(s=!1,A=new d(x.key),B=A.value(c[l])[0]):(B=JSON.stringify(c[l]),s=!0);for(x=0;x<k;x++)if(s){if(JSON.stringify(r[x])===B){h=!1;break}}else if(B===A.value(r[x])[0]){h=!1;break}h&&(this._updatePush(a[l],c[l]),g=!0)}else throw'ForerunnerDB.Collection "'+this.name()+'": Cannot addToSet on a key that is not an array! (undefined)';break;case "$splicePush":void 0===a[l]&&this._updateProperty(a, l,[]);if(a[l]instanceof Array)if(s=c.$index,void 0!==s)delete c.$index,s>a[l].length&&(s=a[l].length),this._updateSplicePush(a[l],s,c[l]),g=!0;else throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush without a $index integer value!';else throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush with a key that is not an array! ('+l+")";break;case "$move":if(a[l]instanceof Array)for(r=0;r<a[l].length;r++){if(this._match(a[l][r],c[l])){g=c.$index;if(void 0!==g)delete c.$index, this._updateSpliceMove(a[l],r,g),g=!0;else throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move without a $index integer value!';break}}else throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move on a key that is not an array! ('+l+")";break;case "$mul":this._updateMultiply(a,l,c[l]);g=!0;break;case "$rename":this._updateRename(a,l,c[l]);g=!0;break;case "$unset":this._updateUnset(a,l);g=!0;break;case "$pop":if(a[l]instanceof Array)this._updatePop(a[l],c[l])&&(g=!0);else throw'ForerunnerDB.Collection "'+ this.name()+'": Cannot pop from a key that is not an array! ('+l+")";break;default:a[l]!==c[l]&&(this._updateProperty(a,l,c[l]),g=!0)}else if(null!==a[l]&&"object"===typeof a[l])if(r=a[l]instanceof Array,k=c[l]instanceof Array,r||k)if(!k&&r)for(r=0;r<a[l].length;r++)s=this.updateObject(a[l][r],c[l],e,b,f+"."+l,m),g=g||s;else a[l]!==c[l]&&(this._updateProperty(a,l,c[l]),g=!0);else s=this.updateObject(a[l],c[l],e,b,f+"."+l,m),g=g||s;else a[l]!==c[l]&&(this._updateProperty(a,l,c[l]),g=!0)}return g}; e.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)};e.prototype._updateProperty=function(a,c,e){a[c]=e;this.debug()&&console.log('ForerunnerDB.Collection: Setting non-data-bound document property "'+c+'" for collection "'+this.name()+'"')};e.prototype._updateIncrement=function(a,c,e){a[c]+=e};e.prototype._updateSpliceMove=function(a,c,e){a.splice(e,0,a.splice(c,1)[0]);this.debug()&&console.log('ForerunnerDB.Collection: Moving non-data-bound document array index from "'+c+ '" to "'+e+'" for collection "'+this.name()+'"')};e.prototype._updateSplicePush=function(a,c,e){a.length>c?a.splice(c,0,e):a.push(e)};e.prototype._updatePush=function(a,c){a.push(c)};e.prototype._updatePull=function(a,c){a.splice(c,1)};e.prototype._updateMultiply=function(a,c,e){a[c]*=e};e.prototype._updateRename=function(a,c,e){a[e]=a[c];delete a[c]};e.prototype._updateUnset=function(a,c){delete a[c]};e.prototype._updatePop=function(a,c){var e=!1;0<a.length&&(1===c?(a.pop(),e=!0):-1===c&&(a.shift(), e=!0));return e};e.prototype.remove=function(a,c,e){var b,d;if(a instanceof Array){b=[];for(e=0;e<a.length;e++)b.push(this.remove(a[e],{noEmit:!0}));(!c||c&&!c.noEmit)&&this._onRemove(b);return b}e=this.find(a,{$decouple:!1});if(e.length){for(var f=0;f<e.length;f++)d=e[f],this._removeFromIndexes(d),b=this._data.indexOf(d),this._dataRemoveAtIndex(b),this.processTrigger(this.TYPE_REMOVE,this.PHASE_AFTER,d,{});this.chainSend("remove",{query:a,dataSet:e},c);(!c||c&&!c.noEmit)&&this._onRemove(e);this.deferEmit("change", {type:"remove",data:e})}return e};e.prototype.removeById=function(a){var c={};c[this._primaryKey]=a;return this.remove(c)};e.prototype.deferEmit=function(){var a=this,c;this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._changeTimeout&&clearTimeout(this._changeTimeout),this._changeTimeout=setTimeout(function(){a.debug()&&console.log("ForerunnerDB.Collection: Emitting "+c[0]);a.emit.apply(a,c)},100))};e.prototype.processQueue=function(a, c){var e=this._deferQueue[a],b=this._deferThreshold[a],d=this._deferTime[a];if(e.length){var f=this;e.length&&(e=e.length>b?e.splice(0,b):e.splice(0,e.length),this[a](e));setTimeout(function(){f.processQueue(a,c)},d)}else c&&c()};e.prototype.insert=function(a,c,e){"function"===typeof c?(e=c,c=this._data.length):void 0===c&&(c=this._data.length);a=this.transformIn(a);return this._insertHandle(a,c,e)};e.prototype._insertHandle=function(a,c,e){var b=this._deferQueue.insert,d=this._deferThreshold.insert, f=[],m=[];if(a instanceof Array){if(a.length>d){this._deferQueue.insert=b.concat(a);this.processQueue("insert",e);return}for(d=0;d<a.length;d++)b=this._insert(a[d],c+d),!0===b?f.push(a[d]):m.push({doc:a[d],reason:b})}else b=this._insert(a,c),!0===b?f.push(a):m.push({doc:a,reason:b});this.chainSend("insert",a,{index:c});this._onInsert(f,m);e&&e();this.deferEmit("change",{type:"insert",data:f});return{inserted:f,failed:m}};e.prototype._insert=function(a,c){if(a){var e;this.ensurePrimaryKey(a);if(e= this.insertIndexViolation(a))return"Index violation in index: "+e;this._insertIntoIndexes(a);c>this._data.length&&(c=this._data.length);this._dataInsertAtIndex(c,a);this.processTrigger(this.TYPE_INSERT,this.PHASE_AFTER,{},a);return!0}return"No document passed to insert"};e.prototype._dataInsertAtIndex=function(a,c){this._data.splice(a,0,c)};e.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)};e.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)}; e.prototype._insertIntoIndexes=function(a){var c=this._indexByName,e,b,d=JSON.stringify(a);b=this._primaryIndex.uniqueSet(a[this._primaryKey],a);this._primaryCrc.uniqueSet(a[this._primaryKey],d);this._crcLookup.uniqueSet(d,a);for(e in c)c.hasOwnProperty(e)&&c[e].insert(a);return b};e.prototype._removeFromIndexes=function(a){var c=this._indexByName,e,b=JSON.stringify(a);this._primaryIndex.unSet(a[this._primaryKey]);this._primaryCrc.unSet(a[this._primaryKey]);this._crcLookup.unSet(b);for(e in c)c.hasOwnProperty(e)&& c[e].remove(a)};e.prototype._rebuildIndexes=function(){var a=this._indexByName,c;for(c in a)a.hasOwnProperty(c)&&a[c].rebuild()};e.prototype.indexOfDocById=function(a){return this._data.indexOf(this._primaryIndex.get(a[this._primaryKey]))};e.prototype.subset=function(a,c){var b=this.find(a,c);return(new e)._subsetOf(this).primaryKey(this._primaryKey).setData(b)};e.prototype.subsetOf=function(){return this.__subsetOf};e.prototype._subsetOf=function(a){this.__subsetOf=a;return this};e.prototype.distinct= function(a,c,e){c=this.find(c,e);a=new d(a);e={};var b=[],f,m;for(m=0;m<c.length;m++)(f=a.value(c[m])[0])&&!e[f]&&(e[f]=!0,b.push(f));return b};e.prototype.findById=function(a,c){var e={};e[this._primaryKey]=a;return this.find(e,c)[0]};e.prototype.peek=function(a,c){var b=this._data,d=b.length,f,m,g=new e;if("string"===typeof a){for(f=0;f<d;f++)m=JSON.stringify(b[f]),-1<m.indexOf(a)&&g.insert(b[f]);return g.find({},c)}return this.find(a,c)};e.prototype.explain=function(a,c){return this.find(a,c).__fdbOp._data}; e.prototype.options=function(a){a=a||{};a.$decouple=void 0!==a.$decouple?a.$decouple:!0;a.$explain=void 0!==a.$explain?a.$explain:!1;return a};e.prototype.find=function(a,c){a=a||{};c=this.options(c);var e=this._metrics.create("find"),b=this,f,m=!0,g,h,k,u,r,l,x,B,A,C=[];h=function(c){return b._match(c,a,"and")};e.start();if(a){e.time("analyseQuery");f=this._analyseQuery(a,c,e);e.time("analyseQuery");e.data("analysis",f);if(f.hasJoin&&f.queriesJoin){e.time("joinReferences");for(k=0;k<f.joinsOn.length;k++)r= f.joinsOn[k],u=new d(f.joinQueries[r]),u=u.value(a)[0],this._db.collection(f.joinsOn[k]).subset(u);e.time("joinReferences")}f.indexMatch.length&&(!c||c&&!c.$skipIndex)?(e.data("index.potential",f.indexMatch),e.data("index.used",f.indexMatch[0].index),e.time("indexLookup"),g=f.indexMatch[0].lookup,e.time("indexLookup"),f.indexMatch[0].keyData.totalKeyCount===f.indexMatch[0].keyData.score&&(m=!1)):e.flag("usedIndex",!1);m&&(g&&g.length?(f=g.length,e.time("tableScan: "+f),g=g.filter(h)):(f=this._data.length, e.time("tableScan: "+f),g=this._data.filter(h)),c.$orderBy&&(e.time("sort"),g=this.sort(c.$orderBy,g),e.time("sort")),e.time("tableScan: "+f));c.limit&&g&&g.length>c.limit&&(g.length=c.limit,e.data("limit",c.limit));c.$decouple&&(e.time("decouple"),g=this.decouple(g),e.time("decouple"),e.data("flag.decouple",!0));if(c.join){for(h=0;h<c.join.length;h++)for(r in c.join[h])if(c.join[h].hasOwnProperty(r))for(B=r,f=this._db.collection(r),m=c.join[h][r],A=0;A<g.length;A++){x={};u=k=!1;for(l in m)if(m.hasOwnProperty(l))if("$"=== l.substr(0,1))switch(l){case "$as":B=m[l];break;case "$multi":k=m[l];break;case "$require":u=m[l];break;default:l.substr(0,3)}else x[l]=(new d(m[l])).value(g[A])[0];x=f.find(x);!u||u&&x[0]?g[A][B]=!1===k?x[0]:x:C.push(g[A])}e.data("flag.join",!0)}if(C.length){e.time("removalQueue");for(l=0;l<C.length;l++)r=g.indexOf(C[l]),-1<r&&g.splice(r,1);e.time("removalQueue")}if(c.transform){e.time("transform");for(l=0;l<g.length;l++)g.splice(l,1,c.transform(g[l]));e.time("transform");e.data("flag.transform", !0)}this._transformEnabled&&this._transformOut&&(e.time("transformOut"),g=this.transformOut(g),e.time("transformOut"));e.data("results",g.length);e.stop()}else e.stop(),g=[];g.__fdbOp=e;return g};e.prototype.indexOf=function(a){if(a=this.find(a,{$decouple:!1})[0])return this._data.indexOf(a)};e.prototype.transform=function(a){return void 0!==a?("object"===typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut= a.dataOut)):this._transformEnabled=!1!==a,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}};e.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var c=[],e;for(e=0;e<a.length;e++)c[e]=this._transformIn(a[e]);return c}return this._transformIn(a)}return a};e.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var c=[],e;for(e=0;e<a.length;e++)c[e]=this._transformOut(a[e]); return c}return this._transformOut(a)}return a};e.prototype.sort=function(a,c){c=c||[];var e=[],b,d;for(b in a)a.hasOwnProperty(b)&&(d={},d[b]=a[b],d.___fdbKey=b,e.push(d));return 2>e.length?this._sort(a,c):this._bucketSort(e,c)};e.prototype._bucketSort=function(a,c){var e=a.shift(),b,d,f=[];if(0<a.length){c=this._sort(e,c);b=this.bucket(e.___fdbKey,c);for(d in b)b.hasOwnProperty(d)&&(e=[].concat(a),f=f.concat(this._bucketSort(e,b[d])));return f}return this._sort(e,c)};e.prototype._sort=function(a, c){var e=this,b,f=new d;b=f.parse(a,!0)[0];f.path(b.path);if(1===b.value)b=function(a,c){var b=f.value(a)[0],d=f.value(c)[0];return e.sortAsc(b,d)};else if(-1===b.value)b=function(a,c){var b=f.value(a)[0],d=f.value(c)[0];return e.sortDesc(b,d)};else throw'ForerunnerDB.Collection "'+this.name()+'": $orderBy clause has invalid direction: '+b.value+", accepted values are 1 or -1 for ascending or descending!";return c.sort(b)};e.prototype.bucket=function(a,c){var e,b={};for(e=0;e<c.length;e++)b[c[e][a]]= b[c[e][a]]||[],b[c[e][a]].push(c[e]);return b};e.prototype._analyseQuery=function(a,c,e){var b={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:c},f,m=[],g=[],h,k,u,r,l,x;e.time("checkIndexes");if(l=(new d).countKeys(a)){void 0!==a[this._primaryKey]&&(e.time("checkIndexMatch: Primary Key"),b.indexMatch.push({lookup:this._primaryIndex.lookup(a,c),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:l,score:1},index:this._primaryIndex}),e.time("checkIndexMatch: Primary Key")); for(x in this._indexById)if(this._indexById.hasOwnProperty(x)&&(k=this._indexById[x],u=k.name(),e.time("checkIndexMatch: "+u),h=k.match(a,c),0<h.score&&(r=k.lookup(a,c),b.indexMatch.push({lookup:r,keyData:h,index:k})),e.time("checkIndexMatch: "+u),h.score===l))break;e.time("checkIndexes");1<b.indexMatch.length&&(e.time("findOptimalIndex"),b.indexMatch.sort(function(a,c){if(a.keyData.score>c.keyData.score)return-1;if(a.keyData.score<c.keyData.score)return 1;if(a.keyData.score===c.keyData.score)return a.lookup.length- c.lookup.length}),e.time("findOptimalIndex"))}if(c.join){b.hasJoin=!0;for(e=0;e<c.join.length;e++)for(f in c.join[e])c.join[e].hasOwnProperty(f)&&(m.push(f),"$as"in c.join[e][f]?g.push(c.join[e][f].$as):g.push(f));for(f=0;f<g.length;f++)if(c=this._queryReferencesCollection(a,g[f],""))b.joinQueries[m[f]]=c,b.queriesJoin=!0;b.joinsOn=m;b.queriesOn=b.queriesOn.concat(m)}return b};e.prototype._queryReferencesCollection=function(a,c,e){for(var b in a)if(a.hasOwnProperty(b)){if(b===c)return e&&(e+="."), e+b;if("object"===typeof a[b])return e&&(e+="."),e+=b,this._queryReferencesCollection(a[b],c,e)}return!1};e.prototype.count=function(a,c){return a?this.find(a,c).length:this._data.length};e.prototype.findSub=function(a,c,e,b){var f=new d(c);a=this.find(a);var m=a.length,g,h,k=this._db.collection("__FDB_temp_"+this.objectId()),u={parents:m,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(g=0;g<m;g++)if(h=f.value(a[g])[0]){k.setData(h);h=k.find(e,b);if(b.returnFirst&&h.length)return h[0];u.subDocs.push(h); u.subDocTotal+=h.length;u.pathFound=!0}k.drop();if(b.noStats)return u.subDocs;u.pathFound||(u.err="No objects found in the parent documents with a matching path of: "+c);return u};e.prototype.insertIndexViolation=function(a){var c,e=this._indexByName,b,d;if(this._primaryIndex.get(a[this._primaryKey]))c=this._primaryIndex;else for(b in e)if(e.hasOwnProperty(b)&&(d=e[b],d.unique()&&d.violation(a))){c=d;break}return c?c.name():!1};e.prototype.ensureIndex=function(e,b){this._indexByName=this._indexByName|| {};this._indexById=this._indexById||{};var d,f={start:(new Date).getTime()};if(b)switch(b.type){case "hashed":d=new a(e,b,this);break;case "btree":d=new c(e,b,this);break;default:d=new a(e,b,this)}else d=new a(e,b,this);if(this._indexByName[d.name()])return{err:"Index with that name already exists"};if(this._indexById[d.id()])return{err:"Index with those keys already exists"};d.rebuild();this._indexByName[d.name()]=d;this._indexById[d.id()]=d;f.end=(new Date).getTime();f.total=f.end-f.start;this._lastOp= {type:"ensureIndex",stats:{time:f}};return{index:d,id:d.id(),name:d.name(),state:d.state()}};e.prototype.index=function(a){if(this._indexByName)return this._indexByName[a]};e.prototype.lastOp=function(){return this._metrics.list()};e.prototype.diff=function(a){var c={insert:[],update:[],remove:[]},e=this.primaryKey(),b,d,f,m;if(e===a.primaryKey()){for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;m=b.length;for(d=0;d<m;d++)f=b[d],this._primaryIndex.get(f[e])?this._primaryCrc.get(f[e])!==a._primaryCrc.get(f[e])&& c.update.push(f):c.insert.push(f);b=this._data;m=b.length;for(d=0;d<m;d++)f=b[d],a._primaryIndex.get(f[e])||c.remove.push(f)}else throw'ForerunnerDB.Collection "'+this.name()+'": Collection diffing requires that both collections have the same primary key!';return c};g.prototype.collection=function(a,c){if(a)return this._collection[a]||this.debug()&&console.log("Creating collection "+a),this._collection[a]=this._collection[a]||(new e(a)).db(this),void 0!==c&&this._collection[a].primaryKey(c),this._collection[a]; throw'ForerunnerDB.Core "'+this.name()+'": Cannot get collection with undefined name!';};g.prototype.collectionExists=function(a){return Boolean(this._collection[a])};g.prototype.collections=function(a){var c=[],e;a&&(a instanceof RegExp||(a=RegExp(a)));for(e in this._collection)this._collection.hasOwnProperty(e)&&(a?a.exec(e)&&c.push({name:e,count:this._collection[e].count()}):c.push({name:e,count:this._collection[e].count()}));return c};h.finishModule("Collection");k.exports=e},{"./Crc":7,"./IndexBinaryTree":11, "./IndexHashMap":12,"./KeyValueStore":13,"./Metrics":14,"./Path":26,"./Shared":30}],5:[function(g,k,h){var f,b;h=g("./Shared");var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(a){this._name=a;this._data=new b("__FDB__cg_data_"+this._name);this._collections=[];this._view=[]};h.addModule("CollectionGroup",d);h.mixin(d.prototype,"Mixin.Common");h.mixin(d.prototype,"Mixin.ChainReactor");h.mixin(d.prototype,"Mixin.Constants");h.mixin(d.prototype,"Mixin.Triggers");b=g("./Collection"); g=h.modules.Core;f=h.modules.Core.prototype.init;d.prototype.on=function(){this._data.on.apply(this._data,arguments)};d.prototype.off=function(){this._data.off.apply(this._data,arguments)};d.prototype.emit=function(){this._data.emit.apply(this._data,arguments)};d.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey};h.synthesize(d.prototype,"state");h.synthesize(d.prototype,"db");d.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!== a.primaryKey())throw'ForerunnerDB.CollectionGroup "'+this.name()+'": All collections in a collection group must have the same primary key!';}else this.primaryKey(a.primaryKey());this._collections.push(a);a._groups.push(this);a.chain(this);this._data.insert(a.find())}return this};d.prototype.removeCollection=function(a){if(a){var c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),c=a._groups.indexOf(this),-1!==c&&a._groups.splice(c,1));0===this._collections.length&& delete this._primaryKey}return this};d.prototype._chainHandler=function(a){switch(a.type){case "setData":a.data=this.decouple(a.data);this._data.remove(a.options.oldData);this._data.insert(a.data);break;case "insert":a.data=this.decouple(a.data);this._data.insert(a.data);break;case "update":this._data.update(a.data.query,a.data.update,a.options);break;case "remove":this._data.remove(a.data.query,a.options)}};d.prototype.insert=function(){this._collectionsRun("insert",arguments)};d.prototype.update= function(){this._collectionsRun("update",arguments)};d.prototype.updateById=function(){this._collectionsRun("updateById",arguments)};d.prototype.remove=function(){this._collectionsRun("remove",arguments)};d.prototype._collectionsRun=function(a,c){for(var b=0;b<this._collections.length;b++)this._collections[b][a].apply(this._collections[b],c)};d.prototype.find=function(a,c){return this._data.find(a,c)};d.prototype.removeById=function(a){for(var c=0;c<this._collections.length;c++)this._collections[c].removeById(a)}; d.prototype.subset=function(a,c){var d=this.find(a,c);return(new b)._subsetOf(this).primaryKey(this._primaryKey).setData(d)};d.prototype.drop=function(){if("dropped"!==this._state){var a,c;this._debug&&console.log("Dropping collection group "+this._name);this._state="dropped";if(this._collections&&this._collections.length)for(c=[].concat(this._collections),a=0;a<c.length;a++)this.removeCollection(c[a]);if(this._view&&this._view.length)for(c=[].concat(this._view),a=0;a<c.length;a++)this._removeView(c[a]); this.emit("drop",this)}return!0};g.prototype.init=function(){this._collectionGroup={};f.apply(this,arguments)};g.prototype.collectionGroup=function(a){return a?(this._collectionGroup[a]=this._collectionGroup[a]||(new d(a)).db(this),this._collectionGroup[a]):this._collectionGroup};g.prototype.collectionGroups=function(){var a=[],c;for(c in this._collectionGroup)this._collectionGroup.hasOwnProperty(c)&&a.push({name:c});return a};k.exports=d},{"./Collection":4,"./Shared":30}],6:[function(g,k,h){var f, b,d;f=g("./Shared");d=g("./Overload");h=function(a){this.init.apply(this,arguments)};h.prototype.init=function(a){this._primaryKey="_id";this._name=a;this._collection={};this._debug={}};h.prototype.moduleLoaded=d({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");a=a.split(",");var c;for(c=0;c<a.length;c++)if(!f.modules[a[c]])return!1;return!0}return!1},"string, function":function(a,c){if(void 0!==a){a=a.replace(/ /g,"");var b=a.split(","),e;for(e=0;e<b.length;e++)if(!f.modules[b[e]])return!1; c()}},"string, function, function":function(a,c,b){if(void 0!==a){a=a.replace(/ /g,"");a=a.split(",");var e;for(e=0;e<a.length;e++)if(!f.modules[a[e]])return b(),!1;c()}}});h.prototype.version=function(a,c){return void 0!==a?0===f.version.indexOf(a)?(c&&c(),!0):!1:f.version};h.moduleLoaded=h.prototype.moduleLoaded;h.version=h.prototype.version;h.shared=f;h.prototype.shared=f;f.addModule("Core",h);f.mixin(h.prototype,"Mixin.Common");f.mixin(h.prototype,"Mixin.ChainReactor");f.mixin(h.prototype,"Mixin.Constants"); b=g("./Collection.js");g("./Metrics.js");g=g("./Crc.js");h.prototype._isServer=!1;f.synthesize(h.prototype,"primaryKey");f.synthesize(h.prototype,"state");f.synthesize(h.prototype,"name");h.prototype.isClient=function(){return!this._isServer};h.prototype.isServer=function(){return this._isServer};h.prototype.crc=g;h.prototype.isClient=function(){return!this._isServer};h.prototype.isServer=function(){return this._isServer};h.prototype.arrayToCollection=function(a){return(new b).setData(a)};h.prototype.on= function(a,c){this._listeners=this._listeners||{};this._listeners[a]=this._listeners[a]||[];this._listeners[a].push(c);return this};h.prototype.off=function(a,c){if(a in this._listeners){var b=this._listeners[a],e=b.indexOf(c);-1<e&&b.splice(e,1)}return this};h.prototype.emit=function(a,c){this._listeners=this._listeners||{};if(a in this._listeners){var b=this._listeners[a],e=b.length,d;for(d=0;d<e;d++)b[d].apply(this,Array.prototype.slice.call(arguments,1))}return this};h.prototype.peek=function(a){var c, b,e=[],d=typeof a;for(c in this._collection)this._collection.hasOwnProperty(c)&&(b=this._collection[c],e="string"===d?e.concat(b.peek(a)):e.concat(b.find(a)));return e};h.prototype.peekCat=function(a){var c,b,e={},d,f=typeof a;for(c in this._collection)this._collection.hasOwnProperty(c)&&(b=this._collection[c],(d="string"===f?b.peek(a):b.find(a))&&d.length&&(e[b.name()]=d));return e};h.prototype.drop=function(a){if("dropped"!==this._state){var c=this.collections(),b=c.length,e,d=0,f=function(){d++; d===b&&a&&a()};this._state="dropped";for(e=0;e<b;e++)this.collection(c[e].name).drop(f),delete this._collection[c[e].name];this.emit("drop",this)}return!0};k.exports=h},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":14,"./Overload":24,"./Shared":30}],7:[function(g,k,h){var f=function(){var b=[],d,a,c;for(a=0;256>a;a++){d=a;for(c=0;8>c;c++)d=d&1?3988292384^d>>>1:d>>>1;b[a]=d}return b}();k.exports=function(b){var d=-1,a;for(a=0;a<b.length;a++)d=d>>>8^f[(d^b.charCodeAt(a))&255];return(d^-1)>>>0}}, {}],8:[function(g,k,h){var f,b;h=g("./Shared");var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(a){this._name=a;this._data={}};h.addModule("Document",d);h.mixin(d.prototype,"Mixin.Common");h.mixin(d.prototype,"Mixin.Events");h.mixin(d.prototype,"Mixin.ChainReactor");h.mixin(d.prototype,"Mixin.Constants");h.mixin(d.prototype,"Mixin.Triggers");g=g("./Collection");f=h.modules.Core;b=h.modules.Core.prototype.init;h.synthesize(d.prototype,"state");h.synthesize(d.prototype,"db"); h.synthesize(d.prototype,"name");d.prototype.setData=function(a){var c,b;if(a)if(a=this.decouple(a),this._linked){b={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(b[c]=1);a.$unset=b;this.updateObject(this._data,a,{})}else this._data=a;return this};d.prototype.update=function(a,c,b){this.updateObject(this._data,c,a,b)};d.prototype.updateObject=g.prototype.updateObject;d.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)};d.prototype._updateProperty= function(a,c,b){this._linked?(jQuery.observable(a).setProperty(c,b),this.debug()&&console.log('ForerunnerDB.Document: Setting data-bound document property "'+c+'" for collection "'+this.name()+'"')):(a[c]=b,this.debug()&&console.log('ForerunnerDB.Document: Setting non-data-bound document property "'+c+'" for collection "'+this.name()+'"'))};d.prototype._updateIncrement=function(a,c,b){this._linked?jQuery.observable(a).setProperty(c,a[c]+b):a[c]+=b};d.prototype._updateSpliceMove=function(a,c,b){this._linked? (jQuery.observable(a).move(c,b),this.debug()&&console.log('ForerunnerDB.Document: Moving data-bound document array index from "'+c+'" to "'+b+'" for collection "'+this.name()+'"')):(a.splice(b,0,a.splice(c,1)[0]),this.debug()&&console.log('ForerunnerDB.Document: Moving non-data-bound document array index from "'+c+'" to "'+b+'" for collection "'+this.name()+'"'))};d.prototype._updateSplicePush=function(a,c,b){a.length>c?this._linked?jQuery.observable(a).insert(c,b):a.splice(c,0,b):this._linked?jQuery.observable(a).insert(b): a.push(b)};d.prototype._updatePush=function(a,c){this._linked?jQuery.observable(a).insert(c):a.push(c)};d.prototype._updatePull=function(a,c){this._linked?jQuery.observable(a).remove(c):a.splice(c,1)};d.prototype._updateMultiply=function(a,c,b){this._linked?jQuery.observable(a).setProperty(c,a[c]*b):a[c]*=b};d.prototype._updateRename=function(a,c,b){var e=a[c];this._linked?(jQuery.observable(a).setProperty(b,e),jQuery.observable(a).removeProperty(c)):(a[b]=e,delete a[c])};d.prototype._updateUnset= function(a,c){this._linked?jQuery.observable(a).removeProperty(c):delete a[c]};d.prototype._updatePop=function(a,c){var b,e=!1;0<a.length&&(this._linked?(1===c?b=a.length-1:-1===c&&(b=0),-1<b&&(jQuery.observable(arr).remove(b),e=!0)):1===c?(a.pop(),e=!0):-1===c&&(a.shift(),e=!0));return e};d.prototype.drop=function(){if("dropped"!==this._state){if(this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name])return this._state="dropped",delete this._db._document[this._name],delete this._data, this.emit("drop",this),!0}else return!0;return!1};f.prototype.init=function(){b.apply(this,arguments)};f.prototype.document=function(a){return a?(this._document=this._document||{},this._document[a]=this._document[a]||(new d(a)).db(this),this._document[a]):this._document};f.prototype.documents=function(){var a=[],c;for(c in this._document)this._document.hasOwnProperty(c)&&a.push({name:c});return a};h.finishModule("Document");k.exports=d},{"./Collection":4,"./Shared":30}],9:[function(g,k,h){var f,b, d,a;h=g("./Shared");var c=function(a,c){this.init.apply(this,arguments)};c.prototype.init=function(a,c,b){var d=this;this._selector=a;this._template=c;this._options=b;this._debug={};this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}};h.addModule("Grid",c);h.mixin(c.prototype,"Mixin.Common");h.mixin(c.prototype,"Mixin.ChainReactor");h.mixin(c.prototype,"Mixin.Constants");h.mixin(c.prototype,"Mixin.Triggers");h.mixin(c.prototype,"Mixin.Events");f=g("./Collection");b=g("./CollectionGroup"); d=g("./View");g("./ReactorIO");g=h.modules.Core;a=g.prototype.init;h.synthesize(c.prototype,"state");h.synthesize(c.prototype,"name");c.prototype.insert=function(){this._from.insert.apply(this._from,arguments)};c.prototype.update=function(){this._from.update.apply(this._from,arguments)};c.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)};c.prototype.remove=function(){this._from.remove.apply(this._from,arguments)};c.prototype.from=function(a){void 0!==a&&(this._from&& (this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"===typeof a&&(a=this._db.collection(a)),this._from=a,this.refresh());return this};c.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db};c.prototype._collectionDropped=function(a){a&&delete this._from};c.prototype.drop=function(){if("dropped"!==this._state){if(this._from)return this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this), (this.debug()||this._db&&this._db.debug())&&console.log("ForerunnerDB.Grid: Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),delete this._selector,delete this._template,delete this._from,delete this._db,!0}else return!0;return!1};c.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template};c.prototype._sortGridClick=function(a){a=($(a.currentTarget).attr("data-grid-sort")||"").split(","); var c={},b;for(b=0;b<a.length;b++)c[a]=1;this._from.orderBy(c)};c.prototype.refresh=function(){if(this._from)if(this._from.link){var a=this,c=$(this._selector),b=function(){a._sortGridClick.apply(a,arguments)};c.html("");this._from.orderBy&&c.off("click","[data-grid-sort]",b);this._from.link(this._selector,this.template(),{wrap:"gridRow"});if(this._from.orderBy)c.on("click","[data-grid-sort]",b)}else throw"Grid requires the AutoBind module in order to operate!";return this};f.prototype.grid=d.prototype.grid= function(a,e,b){if(this._db&&this._db._grid){if(this._db._grid[a])throw'ForerunnerDB.Collection/View "'+this.name()+'": Cannot create a grid using this collection/view because a grid with this name already exists: '+name;a=(new c(a,e,b)).db(this._db).from(this);this._grid=this._grid||[];this._grid.push(a);return a}};f.prototype._addGrid=b.prototype._addGrid=d.prototype._addGrid=function(a){void 0!==a&&(this._grid=this._grid||[],this._grid.push(a));return this};f.prototype._removeGrid=b.prototype._removeGrid= d.prototype._removeGrid=function(a){void 0!==a&&this._grid&&(a=this._grid.indexOf(a),-1<a&&this._grid.splice(a,1));return this};g.prototype.init=function(){this._grid={};a.apply(this,arguments)};g.prototype.grid=function(a,e,b){this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Core.Grid: Creating grid "+a);this._grid[a]=this._grid[a]||(new c(a,e,b)).db(this);return this._grid[a]};g.prototype.gridExists=function(a){return Boolean(this._grid[a])};g.prototype.grids=function(){var a= [],c;for(c in this._grid)this._grid.hasOwnProperty(c)&&a.push({name:c,count:this._grid[c].count()});return a};h.finishModule("Grid");k.exports=c},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":28,"./Shared":30,"./View":32}],10:[function(g,k,h){var f,b;h=g("./Shared");b=g("./Overload");var d=function(a,c){this.init.apply(this,arguments)};d.prototype.init=function(a,c){this._options=c;this._selector=jQuery(this._options.selector);if(!this._selector[0])throw'ForerunnerDB.Highchart "'+a.name()+ '": Chart target element does not exist via selector: '+this._options.selector;this._listeners={};this._collection=a;this._options.series=[];c.chartOptions=c.chartOptions||{};c.chartOptions.credits=!1;var b,e;switch(this._options.type){case "pie":this._selector.highcharts(this._options.chartOptions);this._chart=this._selector.highcharts();b=this._collection.find();e={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:Highcharts.theme&& Highcharts.theme.contrastTextColor||"black"}}};b=this.pieDataFromCollectionData(b,this._options.keyField,this._options.valField);jQuery.extend(e,this._options.seriesOptions);jQuery.extend(e,{name:this._options.seriesName,data:b});this._chart.addSeries(e,!0,!0);break;case "line":case "area":case "column":case "bar":b=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy);this._options.chartOptions.xAxis=b.xAxis;this._options.chartOptions.series= b.series;this._selector.highcharts(this._options.chartOptions);this._chart=this._selector.highcharts();break;default:throw'ForerunnerDB.Highchart "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type;}this._hookEvents()};h.addModule("Highchart",d);g=h.modules.Collection;f=g.prototype.init;h.mixin(d.prototype,"Mixin.Events");h.synthesize(d.prototype,"state");d.prototype.pieDataFromCollectionData=function(a,c,b){var e=[],d;for(d=0;d<a.length;d++)e.push([a[d][c], a[d][b]]);return e};d.prototype.seriesDataFromCollectionData=function(a,c,b,e){var d=this._collection.distinct(a),f=[],g={categories:[]},h,v,k,w,s;for(w=0;w<d.length;w++){h=d[w];v={};v[a]=h;k=[];v=this._collection.find(v,{orderBy:e});for(s=0;s<v.length;s++)g.categories.push(v[s][c]),k.push(v[s][b]);f.push({name:h,data:k})}return{xAxis:g,series:f}};d.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)});a._collection.on("drop",function(){a.drop.apply(a, arguments)})};d.prototype._changeListener=function(){if("undefined"!==typeof this._collection&&this._chart){var a=this._collection.find();switch(this._options.type){case "pie":this._chart.series[0].setData(this.pieDataFromCollectionData(a,this._options.keyField,this._options.valField),!0,!0);break;case "bar":case "line":case "area":case "column":var c=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy);this._chart.xAxis[0].setCategories(c.xAxis.categories); for(a=0;a<c.series.length;a++)this._chart.series[a]?this._chart.series[a].setData(c.series[a].data,!0,!0):this._chart.addSeries(c.series[a],!0,!0)}}};d.prototype.drop=function(){"dropped"!==this._state&&(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options, delete this._collection,this.emit("drop",this));return!0};g.prototype.init=function(){this._highcharts={};f.apply(this,arguments)};g.prototype.pieChart=new b({object:function(a){a.type="pie";a.chartOptions=a.chartOptions||{};a.chartOptions.chart=a.chartOptions.chart||{};a.chartOptions.chart.type="pie";this._highcharts[a.selector]||(this._highcharts[a.selector]=new d(this,a));return this._highcharts[a.selector]},"*, string, string, string, ...":function(a,c,b,e,d){d=d||{};d.selector=a;d.keyField=c; d.valField=b;d.seriesName=e;this.pieChart(d)}});g.prototype.lineChart=new b({object:function(a){a.type="line";a.chartOptions=a.chartOptions||{};a.chartOptions.chart=a.chartOptions.chart||{};a.chartOptions.chart.type="line";this._highcharts[a.selector]||(this._highcharts[a.selector]=new d(this,a));return this._highcharts[a.selector]},"*, string, string, string, ...":function(a,c,b,e,d){d=d||{};d.seriesField=c;d.selector=a;d.keyField=b;d.valField=e;this.lineChart(d)}});g.prototype.areaChart=new b({object:function(a){a.type= "area";a.chartOptions=a.chartOptions||{};a.chartOptions.chart=a.chartOptions.chart||{};a.chartOptions.chart.type="area";this._highcharts[a.selector]||(this._highcharts[a.selector]=new d(this,a));return this._highcharts[a.selector]},"*, string, string, string, ...":function(a,c,b,e,d){d=d||{};d.seriesField=c;d.selector=a;d.keyField=b;d.valField=e;this.areaChart(d)}});g.prototype.columnChart=new b({object:function(a){a.type="column";a.chartOptions=a.chartOptions||{};a.chartOptions.chart=a.chartOptions.chart|| {};a.chartOptions.chart.type="column";this._highcharts[a.selector]||(this._highcharts[a.selector]=new d(this,a));return this._highcharts[a.selector]},"*, string, string, string, ...":function(a,c,b,e,d){d=d||{};d.seriesField=c;d.selector=a;d.keyField=b;d.valField=e;this.columnChart(d)}});g.prototype.barChart=new b({object:function(a){a.type="bar";a.chartOptions=a.chartOptions||{};a.chartOptions.chart=a.chartOptions.chart||{};a.chartOptions.chart.type="bar";this._highcharts[a.selector]||(this._highcharts[a.selector]= new d(this,a));return this._highcharts[a.selector]},"*, string, string, string, ...":function(a,c,b,e,d){d=d||{};d.seriesField=c;d.selector=a;d.keyField=b;d.valField=e;this.barChart(d)}});g.prototype.stackedBarChart=new b({object:function(a){a.type="bar";a.chartOptions=a.chartOptions||{};a.chartOptions.chart=a.chartOptions.chart||{};a.chartOptions.chart.type="bar";a.plotOptions=a.plotOptions||{};a.plotOptions.series=a.plotOptions.series||{};a.plotOptions.series.stacking=a.plotOptions.series.stacking|| "normal";this._highcharts[a.selector]||(this._highcharts[a.selector]=new d(this,a));return this._highcharts[a.selector]},"*, string, string, string, ...":function(a,c,b,e,d){d=d||{};d.seriesField=c;d.selector=a;d.keyField=b;d.valField=e;this.stackedBarChart(d)}});g.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()};h.finishModule("Highchart");k.exports=d},{"./Overload":24,"./Shared":30}],11:[function(g,k,h){h=g("./Shared");var f=g("./Path"),b=function(){}; g=function(){this.init.apply(this,arguments)};g.prototype.init=function(d,a,c){this._btree=new (b.create(2,this.sortAsc));this._size=0;this._id=this._itemKeyHash(d,d);this.unique(a&&a.unique?a.unique:!1);void 0!==d&&this.keys(d);void 0!==c&&this.collection(c);this.name(a&&a.name?a.name:this._id)};h.addModule("IndexBinaryTree",g);h.mixin(g.prototype,"Mixin.ChainReactor");h.mixin(g.prototype,"Mixin.Sorting");g.prototype.id=function(){return this._id};g.prototype.state=function(){return this._state}; g.prototype.size=function(){return this._size};h.synthesize(g.prototype,"data");h.synthesize(g.prototype,"name");h.synthesize(g.prototype,"collection");h.synthesize(g.prototype,"type");h.synthesize(g.prototype,"unique");g.prototype.keys=function(b){return void 0!==b?(this._keys=b,this._keyCount=(new f).parse(this._keys).length,this):this._keys};g.prototype.rebuild=function(){if(this._collection){var d=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}).find(),a,c=d.length;this._btree=new (b.create(2, this.sortAsc));this._unique&&(this._uniqueLookup={});for(a=0;a<c;a++)this.insert(d[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}};g.prototype.insert=function(b,a){var c=this._unique,f=this._itemKeyHash(b,this._keys);c&&(c=this._itemHash(b,this._keys),this._uniqueLookup[c]=b);c=this._btree.get(f);void 0===c&&(c=[],this._btree.put(f,c));c.push(b);this._size++};g.prototype.remove=function(b,a){var c=this._unique,f=this._itemKeyHash(b,this._keys), e;c&&(c=this._itemHash(b,this._keys),delete this._uniqueLookup[c]);c=this._btree.get(f);void 0!==c&&(e=c.indexOf(b),-1<e&&(1===c.length?this._btree.del(f):c.splice(e,1),this._size--))};g.prototype.violation=function(b){b=this._itemHash(b,this._keys);return Boolean(this._uniqueLookup[b])};g.prototype.hashViolation=function(b){return Boolean(this._uniqueLookup[b])};g.prototype.lookup=function(b){return this._data[this._itemHash(b,this._keys)]||[]};g.prototype.match=function(b,a){var c=new f,g=c.parseArr(this._keys), c=c.parseArr(b),e=[],n=0,h;for(h=0;h<g.length;h++)if(c[h]===g[h])n++,e.push(c[h]);else return{matchedKeys:[],totalKeyCount:c.length,score:0};return{matchedKeys:e,totalKeyCount:c.length,score:n}};g.prototype._itemHash=function(b,a){var c=new f,g,e="",n;g=c.parse(a);for(n=0;n<g.length;n++)e&&(e+="_"),e+=c.value(b,g[n].path).join(":");return e};g.prototype._itemKeyHash=function(b,a){var c=new f,g,e="",n;g=c.parse(a);for(n=0;n<g.length;n++)e&&(e+="_"),e+=c.keyValue(b,g[n].path);return e};g.prototype._itemHashArr= function(b,a){var c=new f,g,e=[],n,h,t,q;g=c.parse(a);for(t=0;t<g.length;t++)for(n=c.value(b,g[t].path),h=0;h<n.length;h++)if(0===t)e.push(n[h]);else for(q=0;q<e.length;q++)e[q]=e[q]+"_"+n[h];return e};h.finishModule("IndexBinaryTree");k.exports=g},{"./Path":26,"./Shared":30}],12:[function(g,k,h){h=g("./Shared");var f=g("./Path");g=function(){this.init.apply(this,arguments)};g.prototype.init=function(b,d,a){this._crossRef={};this._size=0;this._id=this._itemKeyHash(b,b);this.data({});this.unique(d&& d.unique?d.unique:!1);void 0!==b&&this.keys(b);void 0!==a&&this.collection(a);this.name(d&&d.name?d.name:this._id)};h.addModule("IndexHashMap",g);h.mixin(g.prototype,"Mixin.ChainReactor");g.prototype.id=function(){return this._id};g.prototype.state=function(){return this._state};g.prototype.size=function(){return this._size};h.synthesize(g.prototype,"data");h.synthesize(g.prototype,"name");h.synthesize(g.prototype,"collection");h.synthesize(g.prototype,"type");h.synthesize(g.prototype,"unique");g.prototype.keys= function(b){return void 0!==b?(this._keys=b,this._keyCount=(new f).parse(this._keys).length,this):this._keys};g.prototype.rebuild=function(){if(this._collection){var b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}).find(),d,a=b.length;this._data={};this._unique&&(this._uniqueLookup={});for(d=0;d<a;d++)this.insert(b[d])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}};g.prototype.insert=function(b,d){var a,c;this._unique&&(a= this._itemHash(b,this._keys),this._uniqueLookup[a]=b);a=this._itemHashArr(b,this._keys);for(c=0;c<a.length;c++)this.pushToPathValue(a[c],b)};g.prototype.remove=function(b,d){var a,c;this._unique&&(a=this._itemHash(b,this._keys),delete this._uniqueLookup[a]);a=this._itemHashArr(b,this._keys);for(c=0;c<a.length;c++)this.pullFromPathValue(a[c],b)};g.prototype.violation=function(b){b=this._itemHash(b,this._keys);return Boolean(this._uniqueLookup[b])};g.prototype.hashViolation=function(b){return Boolean(this._uniqueLookup[b])}; g.prototype.pushToPathValue=function(b,d){var a=this._data[b]=this._data[b]||[];-1===a.indexOf(d)&&(a.push(d),this._size++,this.pushToCrossRef(d,a))};g.prototype.pullFromPathValue=function(b,d){var a=this._data[b],c;c=a.indexOf(d);-1<c&&(a.splice(c,1),this._size--,this.pullFromCrossRef(d,a));a.length||delete this._data[b]};g.prototype.pull=function(b){var d=b[this._collection.primaryKey()],a=this._crossRef[d],c,f=a.length,e;for(c=0;c<f;c++)e=a[c],this._pullFromArray(e,b);this._size--;delete this._crossRef[d]}; g.prototype._pullFromArray=function(b,d){for(var a=b.length;a--;)b[a]===d&&b.splice(a,1)};g.prototype.pushToCrossRef=function(b,d){var a=b[this._collection.primaryKey()];this._crossRef[a]=this._crossRef[a]||[];a=this._crossRef[a];-1===a.indexOf(d)&&a.push(d)};g.prototype.pullFromCrossRef=function(b,d){var a=b[this._collection.primaryKey()];delete this._crossRef[a]};g.prototype.lookup=function(b){return this._data[this._itemHash(b,this._keys)]||[]};g.prototype.match=function(b,d){var a=new f,c=a.parseArr(this._keys), a=a.parseArr(b),g=[],e=0,n;for(n=0;n<c.length;n++)if(a[n]===c[n])e++,g.push(a[n]);else return{matchedKeys:[],totalKeyCount:a.length,score:0};return{matchedKeys:g,totalKeyCount:a.length,score:e}};g.prototype._itemHash=function(b,d){var a=new f,c,g="",e;c=a.parse(d);for(e=0;e<c.length;e++)g&&(g+="_"),g+=a.value(b,c[e].path).join(":");return g};g.prototype._itemKeyHash=function(b,d){var a=new f,c,g="",e;c=a.parse(d);for(e=0;e<c.length;e++)g&&(g+="_"),g+=a.keyValue(b,c[e].path);return g};g.prototype._itemHashArr= function(b,d){var a=new f,c,g=[],e,n,h,t;c=a.parse(d);for(h=0;h<c.length;h++)for(e=a.value(b,c[h].path),n=0;n<e.length;n++)if(0===h)g.push(e[n]);else for(t=0;t<g.length;t++)g[t]=g[t]+"_"+e[n];return g};h.finishModule("IndexHashMap");k.exports=g},{"./Path":26,"./Shared":30}],13:[function(g,k,h){g=g("./Shared");h=function(f){this.init.apply(this,arguments)};h.prototype.init=function(f){this._name=f;this._data={};this._primaryKey="_id"};g.addModule("KeyValueStore",h);g.mixin(h.prototype,"Mixin.ChainReactor"); g.synthesize(h.prototype,"name");h.prototype.primaryKey=function(f){return void 0!==f?(this._primaryKey=f,this):this._primaryKey};h.prototype.truncate=function(){this._data={};return this};h.prototype.set=function(f,b){this._data[f]=b?b:!0;return this};h.prototype.get=function(f){return this._data[f]};h.prototype.lookup=function(f){f=f[this._primaryKey];var b,d,a,c;if(f instanceof Array){d=f.length;c=[];for(b=0;b<d;b++)(a=this._data[f[b]])&&c.push(a);return c}if(f instanceof RegExp){c=[];for(b in this._data)this._data.hasOwnProperty(b)&& f.test(b)&&c.push(this._data[b]);return c}if("object"===typeof f){if(f.$ne){c=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&c.push(this._data[b]);return c}if(f.$in&&f.$in instanceof Array){c=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1<f.$in.indexOf(b)&&c.push(this._data[b]);return c}if(f.$nin&&f.$nin instanceof Array){c=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&c.push(this._data[b]);return c}if(f.$or&&f.$or instanceof Array){c=[];for(b= 0;b<f.$or.length;b++)c=c.concat(this.lookup(f.$or[b]));return c}}else return a=this._data[f],void 0!==a?[a]:[]};h.prototype.unSet=function(f){delete this._data[f];return this};h.prototype.uniqueSet=function(f,b){return void 0===this._data[f]?(this._data[f]=b,!0):!1};g.finishModule("KeyValueStore");k.exports=h},{"./Shared":30}],14:[function(g,k,h){h=g("./Shared");var f=g("./Operation");g=function(){this.init.apply(this,arguments)};g.prototype.init=function(){this._data=[]};h.addModule("Metrics",g); h.mixin(g.prototype,"Mixin.ChainReactor");g.prototype.create=function(b){b=new f(b);this._enabled&&this._data.push(b);return b};g.prototype.start=function(){this._enabled=!0;return this};g.prototype.stop=function(){this._enabled=!1;return this};g.prototype.clear=function(){this._data=[];return this};g.prototype.list=function(){return this._data};h.finishModule("Metrics");k.exports=g},{"./Operation":23,"./Shared":30}],15:[function(g,k,h){k.exports={preSetData:function(){},postSetData:function(){}}}, {}],16:[function(g,k,h){k.exports={chain:function(f){this._chain=this._chain||[];-1===this._chain.indexOf(f)&&this._chain.push(f)},unChain:function(f){this._chain&&(f=this._chain.indexOf(f),-1<f&&this._chain.splice(f,1))},chainSend:function(f,b,d){if(this._chain){var a=this._chain,c=a.length,g;for(g=0;g<c;g++)a[g].chainReceive(this,f,b,d)}},chainReceive:function(f,b,d,a){f={sender:f,type:b,data:d,options:a};(!this._chainHandler||this._chainHandler&&!this._chainHandler(f))&&this.chainSend(f.type,f.data, f.options)}}},{}],17:[function(g,k,h){var f=0;g={decouple:function(b,d){if(void 0!==b){if(d){var a,c=JSON.stringify(b),f=[];for(a=0;a<d;a++)f.push(JSON.parse(c));return f}return JSON.parse(JSON.stringify(b))}},objectId:function(b){var d=Math.pow(10,17);if(b){var a=0,c=b.length,g;for(g=0;g<c;g++)a+=b.charCodeAt(g)*d;b=a.toString(16)}else f++,b=(f+(Math.random()*d+Math.random()*d+Math.random()*d+Math.random()*d)).toString(16);return b},debug:g("./Overload")([function(){return this._debug&&this._debug.all}, function(b){return void 0!==b?"boolean"===typeof b?(this._debug=this._debug||{},this._debug.all=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[b]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(b,d){return void 0!==b?void 0!==d?(this._debug=this._debug||{},this._debug[b]=d,this.chainSend("debug",this._debug),this):this._debug&&this._debug[d]||this._db&&this._db._debug&&this._db._debug[b]:this._debug&&this._debug.all}])}; k.exports=g},{"./Overload":24}],18:[function(g,k,h){k.exports={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1}},{}],19:[function(g,k,h){g=g("./Overload");g={on:new g({"string, function":function(f,b){this._listeners=this._listeners||{};this._listeners[f]=this._listeners[f]||{};this._listeners[f]["*"]=this._listeners[f]["*"]||[];this._listeners[f]["*"].push(b);return this},"string, *, function":function(f,b,d){this._listeners=this._listeners||{};this._listeners[f]=this._listeners[f]|| {};this._listeners[f][b]=this._listeners[f][b]||[];this._listeners[f][b].push(d);return this}}),off:new g({string:function(f){this._listeners&&this._listeners[f]&&f in this._listeners&&delete this._listeners[f];return this},"string, function":function(f,b){var d,a;"string"===typeof b?this._listeners&&this._listeners[f]&&this._listeners[f][b]&&delete this._listeners[f][b]:f in this._listeners&&(d=this._listeners[f]["*"],a=d.indexOf(b),-1<a&&d.splice(a,1));return this},"string, *, function":function(f, b,d){this._listeners&&f in this._listeners&&b in this.listeners[f]&&(f=this._listeners[f][b],d=f.indexOf(d),-1<d&&f.splice(d,1))},"string, *":function(f,b){this._listeners&&f in this._listeners&&b in this._listeners[f]&&delete this._listeners[f][b]}}),emit:function(f,b){this._listeners=this._listeners||{};if(f in this._listeners){var d,a;if(this._listeners[f]["*"]){var c=this._listeners[f]["*"];a=c.length;for(d=0;d<a;d++)c[d].apply(this,Array.prototype.slice.call(arguments,1))}if(b instanceof Array&& b[0]&&b[0][this._primaryKey]){var c=this._listeners[f],g,e;a=b.length;for(d=0;d<a;d++)if(c[b[d][this._primaryKey]])for(g=c[b[d][this._primaryKey]].length,e=0;e<g;e++)c[b[d][this._primaryKey]][e].apply(this,Array.prototype.slice.call(arguments,1))}}return this}};k.exports=g},{"./Overload":24}],20:[function(g,k,h){k.exports={_match:function(f,b,d){var a,c;a=typeof f;c=typeof b;var g=!0,e;if(!("string"!==a&&"number"!==a||"string"!==c&&"number"!==c))"number"===a?f!==b&&(g=!1):f.localeCompare(b)&&(g=!1); else for(e in b)if(b.hasOwnProperty(e)){a=!1;if("$"===e.substr(0,1)&&(c=this._matchOp(e,f,b[e]),-1<c)){if(c){if("or"===d)return!0}else g=c;a=!0}if(!a&&b[e]instanceof RegExp)if(a=!0,"object"===typeof f&&void 0!==f[e]&&b[e].test(f[e])){if("or"===d)return!0}else g=!1;if(!a)if("object"===typeof b[e])if(void 0!==f[e]){if(f[e]instanceof Array&&!(b[e]instanceof Array))for(a=!1,c=0;c<f[e].length&&!(a=this._match(f[e][c],b[e],void 0));c++);else if(!(f[e]instanceof Array)&&b[e]instanceof Array)for(a=!1,c=0;c< b[e].length&&!(a=this._match(f[e],b[e][c],void 0));c++);else a="object"===typeof f?this._match(f[e],b[e],void 0):this._match(void 0,b[e],void 0);if(a){if("or"===d)return!0}else g=!1}else if(b[e]&&void 0!==b[e].$exists)if(a=this._match(void 0,b[e],void 0)){if("or"===d)return!0}else g=!1;else g=!1;else if(f&&f[e]===b[e]){if("or"===d)return!0}else if(f&&f[e]&&f[e]instanceof Array&&b[e]&&"object"!==typeof b[e]){a=!1;for(c=0;c<f[e].length&&!(a=this._match(f[e][c],b[e],void 0));c++);if(a){if("or"===d)return!0}else g= !1}else g=!1;if("and"===d&&!g)return!1}return g},_matchOp:function(f,b,d){switch(f){case "$gt":return b>d;case "$gte":return b>=d;case "$lt":return b<d;case "$lte":return b<=d;case "$exists":return void 0===b!==d;case "$ne":return b!=d;case "$or":for(f=0;f<d.length;f++)if(this._match(b,d[f],"and"))return!0;return!1;case "$and":for(f=0;f<d.length;f++)if(!this._match(b,d[f],"and"))return!1;return!0;case "$in":if(d instanceof Array){f=d.length;var a;for(a=0;a<f;a++)if(d[a]===b)return!0;return!1}throw'ForerunnerDB.Mixin.Matching "'+ this.name()+'": Cannot use an $in operator on a non-array key: '+f;case "$nin":if(d instanceof Array){f=d.length;for(a=0;a<f;a++)if(d[a]===b)return!1;return!0}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use a $nin operator on a non-array key: '+f;}return-1}}},{}],21:[function(g,k,h){k.exports={sortAsc:function(f,b){return"string"===typeof f&&"string"===typeof b?f.localeCompare(b):f>b?1:f<b?-1:0},sortDesc:function(f,b){return"string"===typeof f&&"string"===typeof b?b.localeCompare(f): f>b?-1:f<b?1:0}}},{}],22:[function(g,k,h){k.exports={addTrigger:function(f,b,d,a){return-1===this._triggerIndex(f,b,d)?(this._trigger=this._trigger||{},this._trigger[b]=this._trigger[b]||{},this._trigger[b][d]=this._trigger[b][d]||[],this._trigger[b][d].push({id:f,method:a}),!0):!1},removeTrigger:function(f,b,d){f=this._triggerIndex(f,b,d);-1<f&&this._trigger[b][d].splice(f,1);return!1},willTrigger:function(f,b){return this._trigger&&this._trigger[f]&&this._trigger[f][b]&&this._trigger[f][b].length}, processTrigger:function(f,b,d,a,c){var g,e;if(this._trigger&&this._trigger[b]&&this._trigger[b][d]){b=this._trigger[b][d];g=b.length;for(d=0;d<g;d++){e=b[d];this.debug();e=e.method.call(this,f,a,c);if(!1===e)return!1;if(void 0!==e&&!0!==e&&!1!==e)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+e;}return!0}},_triggerIndex:function(f,b,d){var a;if(this._trigger&&this._trigger[b]&&this._trigger[b][d])for(b=this._trigger[b][d],d=b.length,a=0;a<d;a++)if(b[a].id===f)return a;return-1}}},{}],23:[function(g, k,h){h=g("./Shared");var f=g("./Path");g=function(b){this.pathSolver=new f;this.counter=0;this.init.apply(this,arguments)};g.prototype.init=function(b){this._data={operation:b,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}};h.addModule("Operation",g);h.mixin(g.prototype,"Mixin.ChainReactor");g.prototype.start=function(){this._data.time.startMs=(new Date).getTime()};g.prototype.log=function(b){if(b){var d=0<this._log.length?this._data.log[this._data.log.length- 1].time:0;b={event:b,time:(new Date).getTime(),delta:0};this._data.log.push(b);d&&(b.delta=b.time-d);return this}return this._data.log};g.prototype.time=function(b){if(void 0!==b){var d=this._data.time.process,d=d[b]=d[b]||{};d.startMs?(d.stopMs=(new Date).getTime(),d.totalMs=d.stopMs-d.startMs,d.stepObj.totalMs=d.totalMs,delete d.stepObj):(d.startMs=(new Date).getTime(),d.stepObj={name:b},this._data.steps.push(d.stepObj));return this}return this._data.time};g.prototype.flag=function(b,d){if(void 0!== b&&void 0!==d)this._data.flag[b]=d;else return void 0!==b?this._data.flag[b]:this._data.flag};g.prototype.data=function(b,d,a){return void 0!==d?(this.pathSolver.set(this._data,b,d),this):this.pathSolver.get(this._data,b)};g.prototype.pushData=function(b,d,a){this.pathSolver.push(this._data,b,d)};g.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime();this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs};h.finishModule("Operation");k.exports=g},{"./Path":26,"./Shared":30}], 24:[function(g,k,h){Overload=function(f){if(f){var b,d,a,c,g;if(!(f instanceof Array)){a={};for(b in f)if(f.hasOwnProperty(b))if(c=b.replace(/ /g,""),-1===c.indexOf("*"))a[c]=f[b];else for(g=generateSignaturePermutations(c),c=0;c<g.length;c++)a[g[c]]||(a[g[c]]=f[b]);f=a}return function(){var a=[],c;if(f instanceof Array)for(d=f.length,b=0;b<d;b++){if(f[b].length===arguments.length)return f[b].apply(this,arguments)}else{for(b=0;b<arguments.length;b++)c=typeof arguments[b],"object"===c&&arguments[b]instanceof Array&&(c="array"),a.push(c);c=a.join(",");if(f[c])return f[c].apply(this,arguments);for(b=a.length;0<=b;b--)if(c=a.slice(0,b).join(","),f[c+",..."])return f[c+",..."].apply(this,arguments)}throw'ForerunnerDB.Overload "'+this.name()+'": Overloaded method does not have a matching signature for the passed arguments: '+JSON.stringify(a);}}return function(){}};generateSignaturePermutations=function(f){var b=[],d,a=["string","object","number","function","undefined"],c;if(-1<f.indexOf("*"))for(c=0;c<a.length;c++)d= f.replace("*",a[c]),b=b.concat(generateSignaturePermutations(d));else b.push(f);return b};k.exports=Overload},{}],25:[function(g,k,h){var f,b,d;h=g("./Shared");var a=function(){this.init.apply(this,arguments)};a.prototype.init=function(a){var f=this;this._name=a;this._data=new d("__FDB__dc_data_"+this._name);this._collData=new b;this._collections=[];this._collectionDroppedWrap=function(){f._collectionDropped.apply(f,arguments)}};h.addModule("Overview",a);h.mixin(a.prototype,"Mixin.Common");h.mixin(a.prototype, "Mixin.ChainReactor");h.mixin(a.prototype,"Mixin.Constants");h.mixin(a.prototype,"Mixin.Triggers");h.mixin(a.prototype,"Mixin.Events");b=g("./Collection");d=g("./Document");g=h.modules.Core;f=h.modules.Core.prototype.init;h.synthesize(a.prototype,"state");h.synthesize(a.prototype,"db");h.synthesize(a.prototype,"name");h.synthesize(a.prototype,"query",function(a){var b=this.$super(a);void 0!==a&&this._refresh();return b});h.synthesize(a.prototype,"queryOptions",function(a){var b=this.$super(a);void 0!== a&&this._refresh();return b});h.synthesize(a.prototype,"reduce",function(a){var b=this.$super(a);void 0!==a&&this._refresh();return b});a.prototype.from=function(a){return void 0!==a?("string"===typeof a&&(a=this._db.collection(a)),this._addCollection(a),this):this._collections};a.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)};a.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)};a.prototype._addCollection=function(a){-1=== this._collections.indexOf(a)&&(this._collections.push(a),a.chain(this),a.on("drop",this._collectionDroppedWrap),this._refresh());return this};a.prototype._removeCollection=function(a){-1<this._collections.indexOf(a)&&(this._collections.splice(a,1),a.unChain(this),a.off("drop",this._collectionDroppedWrap),this._refresh());return this};a.prototype._collectionDropped=function(a){a&&this._removeCollection(a)};a.prototype._refresh=function(){if("dropped"!==this._state){if(this._collections&&this._collections[0]){this._collData.primaryKey(this._collections[0].primaryKey()); var a=[],b;for(b=0;b<this._collections.length;b++)a=a.concat(this._collections[b].find(this._query,this._queryOptions));this._collData.setData(a)}this._reduce&&(a=this._reduce(),this._data.setData(a))}};a.prototype._chainHandler=function(a){switch(a.type){case "setData":case "insert":case "update":case "remove":this._refresh()}};a.prototype.data=function(){return this._data};a.prototype.drop=function(){if("dropped"!==this._state){this._state="dropped";delete this._data;for(delete this._collData;this._collections.length;)this._removeCollection(this._collections[0]); delete this._collections;this._db&&this._name&&delete this._db._overview[this._name];delete this._name;this.emit("drop",this)}return!0};g.prototype.init=function(){this._overview={};f.apply(this,arguments)};g.prototype.overview=function(c){return c?(this._overview[c]=this._overview[c]||(new a(c)).db(this),this._overview[c]):this._overview};h.finishModule("Overview");k.exports=a},{"./Collection":4,"./Document":8,"./Shared":30}],26:[function(g,k,h){g=g("./Shared");h=function(f){this.init.apply(this, arguments)};h.prototype.init=function(f){f&&this.path(f)};g.addModule("Path",h);g.mixin(h.prototype,"Mixin.ChainReactor");h.prototype.path=function(f){return void 0!==f?(this._path=this.clean(f),this._pathParts=this._path.split("."),this):this._path};h.prototype.hasObjectPaths=function(f,b){var d=!0,a;for(a in f)if(f.hasOwnProperty(a)&&(void 0===b[a]||"object"===typeof f[a]&&(d=this.hasObjectPaths(f[a],b[a]),!d)))return!1;return d};h.prototype.countKeys=function(f){var b=0,d;for(d in f)f.hasOwnProperty(d)&& void 0!==f[d]&&("object"!==typeof f[d]?b++:b+=this.countKeys(f[d]));return b};h.prototype.countObjectPaths=function(f,b){var d,a={},c=0,g=0,e;for(e in b)b.hasOwnProperty(e)&&("object"===typeof b[e]?(d=this.countObjectPaths(f[e],b[e]),a[e]=d.matchedKeys,g+=d.totalKeyCount,c+=d.matchedKeyCount):(g++,f&&f[e]&&"object"!==typeof f[e]?(a[e]=!0,c++):a[e]=!1));return{matchedKeys:a,matchedKeyCount:c,totalKeyCount:g}};h.prototype.parse=function(f,b){var d=[],a="",c,g,e;for(g in f)if(f.hasOwnProperty(g))if(a= g,"object"===typeof f[g])if(b)for(c=this.parse(f[g],b),e=0;e<c.length;e++)d.push({path:a+"."+c[e].path,value:c[e].value});else for(c=this.parse(f[g]),e=0;e<c.length;e++)d.push({path:a+"."+c[e].path});else b?d.push({path:a,value:f[g]}):d.push({path:a});return d};h.prototype.parseArr=function(f,b){b=b||{};return this._parseArr(f,"",[],b)};h.prototype._parseArr=function(f,b,d,a){var c,g="";b=b||"";d=d||[];for(c in f)f.hasOwnProperty(c)&&(!a.ignore||a.ignore&&!a.ignore.test(c))&&(g=b?b+"."+c:c,"object"=== typeof f[c]?this._parseArr(f[c],g,d,a):d.push(g));return d};h.prototype.value=function(f,b){if(void 0!==f&&"object"===typeof f){var d,a,c,g,e=[],n;void 0!==b&&(b=this.clean(b),d=b.split("."));d=d||this._pathParts;a=d.length;c=f;for(n=0;n<a;n++){c=c[d[n]];if(g instanceof Array){for(a=0;a<g.length;a++)e=e.concat(this.value(g,a+"."+d[n]));return e}if(!c||"object"!==typeof c)break;g=c}return[c]}return[]};h.prototype.set=function(f,b,d){if(void 0!==f&&void 0!==b){var a;b=this.clean(b);b=b.split(".");a= b.shift();b.length?(f[a]=f[a]||{},this.set(f[a],b.join("."),d)):f[a]=d}return f};h.prototype.get=function(f,b){return this.value(f,b)[0]};h.prototype.push=function(f,b,d){if(void 0!==f&&void 0!==b){var a;b=this.clean(b);b=b.split(".");a=b.shift();if(b.length)f[a]=f[a]||{},this.set(f[a],b.join("."),d);else if(f[a]=f[a]||[],f[a]instanceof Array)f[a].push(d);else throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";}return f};h.prototype.keyValue=function(f,b){var d,a,c,g, e;void 0!==b&&(b=this.clean(b),d=b.split("."));d=d||this._pathParts;a=d.length;c=f;for(e=0;e<a;e++)if(c=c[d[e]],!c||"object"!==typeof c){g=d[e]+":"+c;break}return g};h.prototype.clean=function(f){"."===f.substr(0,1)&&(f=f.substr(1,f.length-1));return f};g.finishModule("Path");k.exports=h},{"./Shared":30}],27:[function(g,k,h){h=g("./Shared");var f=g("localforage"),b,d,a,c,m;m=function(){this.init.apply(this,arguments)};m.prototype.init=function(a){a.isClient()&&void 0!==Storage&&(this.mode("localforage"), f.config({driver:[f.INDEXEDDB,f.WEBSQL,f.LOCALSTORAGE],name:"ForerunnerDB",storeName:"FDB"}))};h.addModule("Persist",m);h.mixin(m.prototype,"Mixin.ChainReactor");b=h.modules.Core;d=g("./Collection");a=d.prototype.drop;g("./CollectionGroup");c=b.prototype.init;g=h.overload;m.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode};m.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case "LOCALSTORAGE":f.setDriver(f.LOCALSTORAGE);break;case "WEBSQL":f.setDriver(f.WEBSQL); break;case "INDEXEDDB":f.setDriver(f.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!";}return this}return f.driver()};m.prototype.save=function(a,c,b){var d;d=function(a,c){a="object"===typeof a?"json::fdb::"+JSON.stringify(a):"raw::fdb::"+a;c&&c(!1,a)};switch(this.mode()){case "localforage":d(c,function(c,d){f.setItem(a,d).then(function(a){b(!1,a)},function(a){b(a)})});break;default:b&& b("No data handler.")}};m.prototype.load=function(a,c){var b,d,g;g=function(a,c){if(a){b=a.split("::fdb::");switch(b[0]){case "json":d=JSON.parse(b[1]);break;case "raw":d=b[1]}c&&c(!1,d)}else c(!1,a)};switch(this.mode()){case "localforage":f.getItem(a).then(function(a){g(a,c)},function(a){c(a)});break;default:c&&c("No data handler or unrecognised data type.")}};m.prototype.drop=function(a,c){switch(this.mode()){case "localforage":f.removeItem(a).then(function(){c(!1)},function(a){c(a)});break;default:c&& c("No data handler or unrecognised data type.")}};d.prototype.drop=new g({"":function(){"dropped"!==this._state&&this.drop(!0)},"function":function(a){"dropped"!==this._state&&this.drop(!0,a)},"boolean":function(c){if("dropped"!==this._state){if(c)if(this._name)if(this._db)this._db.persist.drop(this._name);else throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when the collection is not attached to a database!";else throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!"; a.apply(this,arguments)}},"boolean, function":function(c,b){"dropped"!==this._state&&(c&&(this._name?this._db?this._db.persist.drop(this._name,b):b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!"):b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")),a.apply(this,arguments))}});d.prototype.save=function(a){this._name?this._db?this._db.persist.save(this._name,this._data,a):a&&a("Cannot save a collection that is not attached to a database!"): a&&a("Cannot save a collection with no assigned name!")};d.prototype.load=function(a){var c=this;this._name?this._db?this._db.persist.load(this._name,function(b,d){b?a&&a(b):(d&&c.setData(d),a&&a(!1))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")};b.prototype.init=function(){this.persist=new m(this);c.apply(this,arguments)};b.prototype.load=function(a){var c=this._collection,b=c.keys().length,d,f;d=function(c){c?a(c): (b--,0===b&&a(!1))};for(f in c)c.hasOwnProperty(f)&&c[f].load(d)};b.prototype.save=function(a){var c=this._collection,b=c.keys().length,d,f;d=function(c){c?a(c):(b--,0===b&&a(!1))};for(f in c)c.hasOwnProperty(f)&&c[f].save(d)};h.finishModule("Persist");k.exports=m},{"./Collection":4,"./CollectionGroup":5,"./Shared":30,localforage:39}],28:[function(g,k,h){g=g("./Shared");h=function(f,b,d){if(f&&b&&d){this._reactorIn=f;this._reactorOut=b;this._chainHandler=d;if(!f.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!"; f.chain(this);this.chain(b)}else throw"ForerunnerDB.ReactorIO: ReactorIO requires an in, out and process argument to instantiate!";};g.addModule("ReactorIO",h);h.prototype.drop=function(){"dropped"!==this._state&&(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this));return!0};g.synthesize(h.prototype,"state");g.mixin(h.prototype,"Mixin.ChainReactor"); g.mixin(h.prototype,"Mixin.Events");g.finishModule("ReactorIO");k.exports=h},{"./Shared":30}],29:[function(g,k,h){h=g("./Shared");var f=g("rest"),b=g("rest/interceptor/mime"),d=function(){this.init.apply(this,arguments)};d.prototype.init=function(a){this._endPoint="";this._client=f.wrap(b)};d.prototype._params=function(a){var c=[],b;for(b in a)a.hasOwnProperty(b)&&c.push(encodeURIComponent(b)+"="+encodeURIComponent(a[b]));return c.join("&")};d.prototype.get=function(a,c,b){var e=this,d;a=void 0!== a?a:"";console.log("Getting: ",this.endPoint()+a+"?"+this._params(c));this._client({method:"get",path:this.endPoint()+a,params:c}).then(function(a){a.entity&&a.entity.error?b(a.entity.error,a.entity,a):((d=e.collection())&&d.upsert(a.entity),b(!1,a.entity,a))},function(a){b(!0,a.entity,a)})};d.prototype.post=function(a,c,b){this._client({method:"post",path:this.endPoint()+a,entity:c,headers:{"Content-Type":"application/json"}}).then(function(a){a.entity&&a.entity.error?b(a.entity.error,a.entity,a): b(!1,a.entity,a)},function(a){b(!0,a)})};h.synthesize(d.prototype,"sessionData");h.synthesize(d.prototype,"endPoint");h.synthesize(d.prototype,"collection");h.addModule("Rest",d);h.mixin(d.prototype,"Mixin.ChainReactor");Core=h.modules.Core;Collection=g("./Collection");CollectionDrop=Collection.prototype.drop;CollectionGroup=g("./CollectionGroup");CollectionInit=Collection.prototype.init;CoreInit=Core.prototype.init;Overload=h.overload;Collection.prototype.init=function(){this.rest=new d;this.rest.collection(this); CollectionInit.apply(this,arguments)};Core.prototype.init=function(){this.rest=new d;CoreInit.apply(this,arguments)};h.finishModule("Rest");k.exports=d},{"./Collection":4,"./CollectionGroup":5,"./Shared":30,rest:42,"rest/interceptor/mime":47}],30:[function(g,k,h){g={version:"1.3.8",modules:{},_synth:{},addModule:function(f,b){this.modules[f]=b;this.emit("moduleLoad",[f,b])},finishModule:function(f){if(this.modules[f])this.modules[f]._fdbFinished=!0,this.emit("moduleFinished",[f,this.modules[f]]); else throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+f;},moduleFinished:function(f,b){if(this.modules[f]&&this.modules[f]._fdbFinished)b(f,this.modules[f]);else this.on("moduleFinished",b)},moduleExists:function(f){return Boolean(this.modules[f])},mixin:function(f,b){var d=this.mixins[b];if(d)for(var a in d)d.hasOwnProperty(a)&&(f[a]=d[a]);else throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;},synthesize:function(f,b,d){this._synth[b]= this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]};if(d){var a=this;f[b]=function(){var c=this.$super,f;this.$super=a._synth[b];f=d.apply(this,arguments);this.$super=c;return f}}else f[b]=this._synth[b]},overload:g("./Overload"),mixins:{"Mixin.Common":g("./Mixin.Common"),"Mixin.Events":g("./Mixin.Events"),"Mixin.ChainReactor":g("./Mixin.ChainReactor"),"Mixin.CRUD":g("./Mixin.CRUD"),"Mixin.Constants":g("./Mixin.Constants"),"Mixin.Triggers":g("./Mixin.Triggers"),"Mixin.Sorting":g("./Mixin.Sorting"), "Mixin.Matching":g("./Mixin.Matching")}};g.mixin(g,"Mixin.Events");k.exports=g},{"./Mixin.CRUD":15,"./Mixin.ChainReactor":16,"./Mixin.Common":17,"./Mixin.Constants":18,"./Mixin.Events":19,"./Mixin.Matching":20,"./Mixin.Sorting":21,"./Mixin.Triggers":22,"./Overload":24}],31:[function(g,k,h){Array.prototype.filter||(Array.prototype.filter=function(f){if(void 0===this||null===this)throw new TypeError;var b=Object(this),d=b.length>>>0;if("function"!==typeof f)throw new TypeError;for(var a=[],c=2<=arguments.length? arguments[1]:void 0,g=0;g<d;g++)if(g in b){var e=b[g];f.call(c,e,g,b)&&a.push(e)}return a});"function"!==typeof Object.create&&(Object.create=function(){var f=function(){};return function(b){if(1<arguments.length)throw Error("Second argument not supported");if("object"!==typeof b)throw TypeError("Argument must be an object");f.prototype=b;var d=new f;f.prototype=null;return d}}());Array.prototype.indexOf||(Array.prototype.indexOf=function(f,b){var d;if(null==this)throw new TypeError('"this" is null or not defined'); var a=Object(this),c=a.length>>>0;if(0===c)return-1;d=+b||0;Infinity===Math.abs(d)&&(d=0);if(d>=c)return-1;for(d=Math.max(0<=d?d:c-Math.abs(d),0);d<c;){if(d in a&&a[d]===f)return d;d++}return-1});k.exports={}},{}],32:[function(g,k,h){var f,b,d,a,c,m;h=g("./Shared");var e=function(a,c,b){this.init.apply(this,arguments)};e.prototype.init=function(a,c,b){var e=this;this._name=a;this._groups=[];this._listeners={};this._querySettings={};this._debug={};this.query(c,!1);this.queryOptions(b,!1);this._collectionDroppedWrap= function(){e._collectionDropped.apply(e,arguments)};this._privateData=new f("__FDB__view_privateData_"+this._name)};h.addModule("View",e);h.mixin(e.prototype,"Mixin.Common");h.mixin(e.prototype,"Mixin.ChainReactor");h.mixin(e.prototype,"Mixin.Constants");h.mixin(e.prototype,"Mixin.Triggers");f=g("./Collection");b=g("./CollectionGroup");m=g("./ActiveBucket");c=g("./ReactorIO");d=f.prototype.init;g=h.modules.Core;a=g.prototype.init;h.synthesize(e.prototype,"state");h.synthesize(e.prototype,"name"); e.prototype.insert=function(){this._from.insert.apply(this._from,arguments)};e.prototype.update=function(){this._from.update.apply(this._from,arguments)};e.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)};e.prototype.remove=function(){this._from.remove.apply(this._from,arguments)};e.prototype.find=function(a,c){return this.publicData().find(a,c)};e.prototype.data=function(){return this._privateData};e.prototype.from=function(a){var b=this;if(void 0!==a){this._from&& (this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this));"string"===typeof a&&(a=this._db.collection(a));this._from=a;this._io=new c(a,this,function(a){var c,e,d;if(b._querySettings.query){if("insert"===a.type){c=a.data;if(c instanceof Array)for(e=[],a=0;a<c.length;a++)b._privateData._match(c[a],b._querySettings.query,"and")&&(e.push(c[a]),d=!0);else b._privateData._match(c,b._querySettings.query,"and")&&(e=c,d=!0);d&&this.chainSend("insert",e);return!0}if("update"===a.type&& (e=b._privateData.diff(b._from.subset(b._querySettings.query,b._querySettings.options)),e.insert.length||e.remove.length)){e.insert.length&&this.chainSend("insert",e.insert);if(e.update.length)for(d=b._privateData.primaryKey(),a=0;a<e.update.length;a++)c={},c[d]=e.update[a][d],this.chainSend("update",{query:c,update:e.update[a]});if(e.remove.length){d=b._privateData.primaryKey();c=[];var f={query:{$or:c}};for(a=0;a<e.remove.length;a++)c.push({_id:e.remove[a][d]});this.chainSend("remove",f)}return!0}}return!1}); var e=a.find(this._querySettings.query,this._querySettings.options);this._transformPrimaryKey(a.primaryKey());this._transformSetData(e);this._privateData.primaryKey(a.primaryKey());this._privateData.setData(e);this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket()}return this};e.prototype._collectionDropped=function(a){a&&delete this._from};e.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData, arguments)};e.prototype._chainHandler=function(a){var c,b,e,d;switch(a.type){case "setData":this.debug()&&console.log('ForerunnerDB.View: Setting data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"');a=this._from.find(this._querySettings.query,this._querySettings.options);this._transformSetData(a);this._privateData.setData(a);break;case "insert":this.debug()&&console.log('ForerunnerDB.View: Inserting some data on view "'+this.name()+'" in underlying (internal) view collection "'+ this._privateData.name()+'"');a.data=this.decouple(a.data);a.data instanceof Array||(a.data=[a.data]);if(this._querySettings.options&&this._querySettings.options.$orderBy)for(c=a.data,b=c.length,e=0;e<b;e++)d=this._activeBucket.insert(c[e]),this._transformInsert(a.data,d),this._privateData._insertHandle(a.data,d);else d=this._privateData._data.length,this._transformInsert(a.data,d),this._privateData._insertHandle(a.data,d);break;case "update":this.debug()&&console.log('ForerunnerDB.View: Updating some data on view "'+ this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"');this._privateData.primaryKey();a=this._privateData.update(a.data.query,a.data.update,a.data.options);if(this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.length,e=0;e<b;e++)d=a[e],this._activeBucket.remove(d),c=this._privateData._data.indexOf(d),d=this._activeBucket.insert(d),c!==d&&this._privateData._updateSpliceMove(this._privateData._data,c,d);if(this._transformEnabled&&this._transformIn)for(b= this._publicData.primaryKey(),c=0;c<a.length;c++)e={},d=a[c],e[b]=d[b],this._transformUpdate(e,d);break;case "remove":this.debug()&&console.log('ForerunnerDB.View: Removing some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),this._transformRemove(a.data.query,a.options),this._privateData.remove(a.data.query,a.options)}};e.prototype.on=function(){this._privateData.on.apply(this._privateData,arguments)};e.prototype.off=function(){this._privateData.off.apply(this._privateData, arguments)};e.prototype.emit=function(){this._privateData.emit.apply(this._privateData,arguments)};e.prototype.drop=function(){if("dropped"!==this._state){if(this._from)return this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this),(this.debug()||this._db&&this._db.debug())&&console.log("ForerunnerDB.View: Dropping view "+this._name),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._db&&this._name&&delete this._db._view[this._name], this.emit("drop",this),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._groups,delete this._listeners,delete this._querySettings,delete this._db,!0}else return!0;return!1};e.prototype.db=function(a){return void 0!==a?(this._db=a,this.privateData().db(a),this.publicData().db(a),this):this._db};e.prototype.primaryKey=function(){return this._privateData.primaryKey()};e.prototype.queryData=function(a,c,b){void 0!==a&&(this._querySettings.query=a);void 0!==c&& (this._querySettings.options=c);return void 0!==a||void 0!==c?(void 0!==b&&!0!==b||this.refresh(),this):this._querySettings};e.prototype.queryAdd=function(a,c,b){var e=this._querySettings.query,d;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&c)&&(e[d]=a[d]);void 0!==b&&!0!==b||this.refresh()};e.prototype.queryRemove=function(a,c){var b=this._querySettings.query,e;if(void 0!==a)for(e in a)a.hasOwnProperty(e)&&delete b[e];void 0!==c&&!0!==c||this.refresh()};e.prototype.query= function(a,c){return void 0!==a?(this._querySettings.query=a,void 0!==c&&!0!==c||this.refresh(),this):this._querySettings.query};e.prototype.orderBy=function(a){if(void 0!==a){var c=this.queryOptions()||{};c.$orderBy=a;this.queryOptions(c);return this}return(this.queryOptions()||{}).$orderBy};e.prototype.queryOptions=function(a,c){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===c||!0===c?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options}; e.prototype.rebuildActiveBucket=function(a){if(a){var c=this._privateData._data,b=c.length;this._activeBucket=new m(a);this._activeBucket.primaryKey(this._privateData.primaryKey());for(a=0;a<b;a++)this._activeBucket.insert(c[a])}else delete this._activeBucket};e.prototype.refresh=function(){if(this._from){var a=this.publicData();this._privateData.remove();a.remove();this._privateData.insert(this._from.find(this._querySettings.query,this._querySettings.options))}this._querySettings.options&&this._querySettings.options.$orderBy? this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket();return this};e.prototype.count=function(){return this._privateData&&this._privateData._data?this._privateData._data.length:0};e.prototype.transform=function(a){return void 0!==a?("object"===typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=!1!==a,this._transformPrimaryKey(this.privateData().primaryKey()), this._transformSetData(this.privateData().find()),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}};e.prototype.privateData=function(){return this._privateData};e.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData};e.prototype._transformSetData=function(a){this._transformEnabled&&(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0, dataIn:this._transformIn,dataOut:this._transformOut}),this._publicData.setData(a))};e.prototype._transformInsert=function(a,c){this._transformEnabled&&this._publicData&&this._publicData.insert(a,c)};e.prototype._transformUpdate=function(a,c,b){this._transformEnabled&&this._publicData&&this._publicData.update(a,c,b)};e.prototype._transformRemove=function(a,c){this._transformEnabled&&this._publicData&&this._publicData.remove(a,c)};e.prototype._transformPrimaryKey=function(a){this._transformEnabled&& this._publicData&&this._publicData.primaryKey(a)};f.prototype.init=function(){this._view=[];d.apply(this,arguments)};f.prototype.view=function(a,c,b){if(this._db&&this._db._view){if(this._db._view[a])throw'ForerunnerDB.Collection "'+this.name()+'": Cannot create a view using this collection because a view with this name already exists: '+a;a=(new e(a,c,b)).db(this._db).from(this);this._view=this._view||[];this._view.push(a);return a}};f.prototype._addView=b.prototype._addView=function(a){void 0!== a&&this._view.push(a);return this};f.prototype._removeView=b.prototype._removeView=function(a){void 0!==a&&(a=this._view.indexOf(a),-1<a&&this._view.splice(a,1));return this};g.prototype.init=function(){this._view={};a.apply(this,arguments)};g.prototype.view=function(a){this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Core.View: Creating view "+a);this._view[a]=this._view[a]||(new e(a)).db(this);return this._view[a]};g.prototype.viewExists=function(a){return Boolean(this._view[a])}; g.prototype.views=function(){var a=[],c;for(c in this._view)this._view.hasOwnProperty(c)&&a.push({name:c,count:this._view[c].count()});return a};h.finishModule("View");k.exports=e},{"./ActiveBucket":3,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":28,"./Shared":30}],33:[function(g,k,h){function f(c){function g(c){null===t?v.push(c):a(function(){var a=t?c.onFulfilled:c.onRejected;if(null===a)(t?c.resolve:c.reject)(q);else{var b;try{b=a(q)}catch(e){c.reject(e);return}c.resolve(b)}})}function e(a){try{if(a=== p)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"===typeof a||"function"===typeof a)){var c=a.then;if("function"===typeof c){d(c.bind(a),e,h);return}}t=!0;q=a;k()}catch(b){h(b)}}function h(a){t=!1;q=a;k()}function k(){for(var a=0,c=v.length;a<c;a++)g(v[a]);v=null}if("object"!==typeof this)throw new TypeError("Promises must be constructed via new");if("function"!==typeof c)throw new TypeError("not a function");var t=null,q=null,v=[],p=this;this.then=function(a,c){return new f(function(e, d){g(new b(a,c,e,d))})};d(c,e,h)}function b(a,b,e,d){this.onFulfilled="function"===typeof a?a:null;this.onRejected="function"===typeof b?b:null;this.resolve=e;this.reject=d}function d(a,b,e){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,e(a))})}catch(f){d||(d=!0,e(f))}}var a=g("asap");k.exports=f},{asap:35}],34:[function(g,k,h){function f(a){this.then=function(c){return"function"!==typeof c?this:new b(function(b,e){d(function(){try{b(c(a))}catch(d){e(d)}})})}}var b=g("./core.js"), d=g("asap");k.exports=b;f.prototype=Object.create(b.prototype);var a=new f(!0),c=new f(!1),m=new f(null),e=new f(void 0),n=new f(0),y=new f("");b.resolve=function(d){if(d instanceof b)return d;if(null===d)return m;if(void 0===d)return e;if(!0===d)return a;if(!1===d)return c;if(0===d)return n;if(""===d)return y;if("object"===typeof d||"function"===typeof d)try{var g=d.then;if("function"===typeof g)return new b(g.bind(d))}catch(h){return new b(function(a,c){c(h)})}return new f(d)};b.from=b.cast=function(a){var c= Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");c.name="Warning";console.warn(c.stack);return b.resolve(a)};b.denodeify=function(a,c){c=c||Infinity;return function(){var e=this,d=Array.prototype.slice.call(arguments);return new b(function(b,f){for(;d.length&&d.length>c;)d.pop();d.push(function(a,c){a?f(a):b(c)});a.apply(e,d)})}};b.nodeify=function(a){return function(){var c=Array.prototype.slice.call(arguments),e="function"===typeof c[c.length-1]?c.pop():null;try{return a.apply(this, arguments).nodeify(e)}catch(f){if(null===e||"undefined"==typeof e)return new b(function(a,c){c(f)});d(function(){e(f)})}}};b.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),c=Array.prototype.slice.call(a?arguments[0]:arguments);a||(a=Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated"),a.name="Warning",console.warn(a.stack));return new b(function(a,b){function e(f,g){try{if(g&&("object"===typeof g||"function"===typeof g)){var h= g.then;if("function"===typeof h){h.call(g,function(a){e(f,a)},b);return}}c[f]=g;0===--d&&a(c)}catch(m){b(m)}}if(0===c.length)return a([]);for(var d=c.length,f=0;f<c.length;f++)e(f,c[f])})};b.reject=function(a){return new b(function(c,b){b(a)})};b.race=function(a){return new b(function(c,e){a.forEach(function(a){b.resolve(a).then(c,e)})})};b.prototype.done=function(a,c){(arguments.length?this.then.apply(this,arguments):this).then(null,function(a){d(function(){throw a;})})};b.prototype.nodeify=function(a){if("function"!= typeof a)return this;this.then(function(c){d(function(){a(null,c)})},function(c){d(function(){a(c)})})};b.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":33,asap:35}],35:[function(g,k,h){(function(f){function b(){for(;d.next;){d=d.next;var a=d.task;d.task=void 0;var f=d.domain;f&&(d.domain=void 0,f.enter());try{a()}catch(g){if(e)throw f&&f.exit(),setTimeout(b,0),f&&f.enter(),g;setTimeout(function(){throw g;},0)}f&&f.exit()}c=!1}var d={task:void 0,next:null},a=d,c=!1,g=void 0, e=!1;if("undefined"!==typeof f&&f.nextTick)e=!0,g=function(){f.nextTick(b)};else if("function"===typeof setImmediate)g="undefined"!==typeof window?setImmediate.bind(window,b):function(){setImmediate(b)};else if("undefined"!==typeof MessageChannel){var h=new MessageChannel;h.port1.onmessage=b;g=function(){h.port2.postMessage(0)}}else g=function(){setTimeout(b,0)};k.exports=function(b){a=a.next={task:b,domain:e&&f.domain,next:null};c||(c=!0,g())}}).call(this,g("_process"))},{_process:82}],36:[function(g, k,h){(function(){function f(a){var c=this,b={db:null};if(a)for(var e in a)b[e]=a[e];return new p(function(a,e){var d=w.open(b.name,b.version);d.onerror=function(){e(d.error)};d.onupgradeneeded=function(){d.result.createObjectStore(b.storeName)};d.onsuccess=function(){b.db=d.result;c._dbInfo=b;a()}})}function b(a,c){var b=this;"string"!==typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new p(function(c,e){b.ready().then(function(){var d=b._dbInfo,f=d.db.transaction(d.storeName, "readonly").objectStore(d.storeName).get(a);f.onsuccess=function(){var a=f.result;void 0===a&&(a=null);c(a)};f.onerror=function(){e(f.error)}})["catch"](e)});q(e,c);return e}function d(a,c){var b=this,e=new p(function(c,e){b.ready().then(function(){var d=b._dbInfo,f=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName).openCursor(),g=1;f.onsuccess=function(){var b=f.result;if(b){var e=a(b.value,b.key,g++);void 0!==e?c(e):b["continue"]()}else c()};f.onerror=function(){e(f.error)}})["catch"](e)}); q(e,c);return e}function a(a,c,b){var e=this;"string"!==typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new p(function(b,d){e.ready().then(function(){var f=e._dbInfo,g=f.db.transaction(f.storeName,"readwrite"),f=g.objectStore(f.storeName);null===c&&(c=void 0);var h=f.put(c,a);g.oncomplete=function(){void 0===c&&(c=null);b(c)};g.onabort=g.onerror=function(){d(h.error)}})["catch"](d)});q(d,b);return d}function c(a,c){var b=this;"string"!==typeof a&&(window.console.warn(a+ " used as a key, but it is not a string."),a=String(a));var e=new p(function(c,e){b.ready().then(function(){var d=b._dbInfo,f=d.db.transaction(d.storeName,"readwrite"),g=f.objectStore(d.storeName)["delete"](a);f.oncomplete=function(){c()};f.onerror=function(){e(g.error)};f.onabort=function(a){a=a.target.error;"QuotaExceededError"===a&&e(a)}})["catch"](e)});q(e,c);return e}function h(a){var c=this,b=new p(function(a,b){c.ready().then(function(){var e=c._dbInfo,d=e.db.transaction(e.storeName,"readwrite"), f=d.objectStore(e.storeName).clear();d.oncomplete=function(){a()};d.onabort=d.onerror=function(){b(f.error)}})["catch"](b)});q(b,a);return b}function e(a){var c=this,b=new p(function(a,b){c.ready().then(function(){var e=c._dbInfo,d=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName).count();d.onsuccess=function(){a(d.result)};d.onerror=function(){b(d.error)}})["catch"](b)});t(b,a);return b}function n(a,c){var b=this,e=new p(function(c,e){0>a?c(null):b.ready().then(function(){var d=b._dbInfo, f=!1,g=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName).openCursor();g.onsuccess=function(){var b=g.result;b?0===a?c(b.key):f?c(b.key):(f=!0,b.advance(a)):c(null)};g.onerror=function(){e(g.error)}})["catch"](e)});t(e,c);return e}function y(a){var c=this,b=new p(function(a,b){c.ready().then(function(){var e=c._dbInfo,d=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName).openCursor(),f=[];d.onsuccess=function(){var c=d.result;c?(f.push(c.key),c["continue"]()):a(f)};d.onerror= function(){b(d.error)}})["catch"](b)});t(b,a);return b}function t(a,c){c&&a.then(function(a){c(null,a)},function(a){c(a)})}function q(a,c){c&&a.then(function(a){v(c,a)},function(a){c(a)})}function v(a,c){if(a)return setTimeout(function(){return a(null,c)},0)}var p="undefined"!==typeof k&&k.exports?g("promise"):this.Promise,w=w||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(w){var s={_driver:"asyncStorage",_initStorage:f,iterate:d,getItem:b,setItem:a, removeItem:c,clear:h,length:e,key:n,keys:y};"undefined"!==typeof k&&k.exports?k.exports=s:this.asyncStorage=s}}).call(window)},{promise:34}],37:[function(g,k,h){(function(){function f(a,c){c&&a.then(function(a){c(null,a)},function(a){c(a)})}var b="undefined"!==typeof k&&k.exports?g("promise"):this.Promise,d=this,a=null,c=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;c=this.localStorage}catch(h){return}var e=3;"undefined"!==typeof k&&k.exports&&(e=2);var n={_driver:"localStorageWrapper", _initStorage:function(c){var f={};if(c)for(var h in c)f[h]=c[h];f.keyPrefix=f.name+"/";this._dbInfo=f;return(new b(function(a){1===e?g(["localforageSerializer"],a):2===e?a(g("./../utils/serializer")):a(d.localforageSerializer)})).then(function(c){a=c;return b.resolve()})},iterate:function(b,e){var d=this,g=d.ready().then(function(){for(var e=d._dbInfo.keyPrefix.length,f=c.length,g=0;g<f;g++){var h=c.key(g),m=c.getItem(h);m&&(m=a.deserialize(m));m=b(m,h.substring(e),g+1);if(void 0!==m)return m}}); f(g,e);return g},getItem:function(b,e){var d=this;"string"!==typeof b&&(window.console.warn(b+" used as a key, but it is not a string."),b=String(b));var g=d.ready().then(function(){var e=c.getItem(d._dbInfo.keyPrefix+b);e&&(e=a.deserialize(e));return e});f(g,e);return g},setItem:function(e,d,g){var h=this;"string"!==typeof e&&(window.console.warn(e+" used as a key, but it is not a string."),e=String(e));var m=h.ready().then(function(){void 0===d&&(d=null);var f=d;return new b(function(b,g){a.serialize(d, function(a,d){if(d)g(d);else try{c.setItem(h._dbInfo.keyPrefix+e,a),b(f)}catch(m){"QuotaExceededError"!==m.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==m.name||g(m),g(m)}})})});f(m,g);return m},removeItem:function(a,b){var e=this;"string"!==typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=e.ready().then(function(){c.removeItem(e._dbInfo.keyPrefix+a)});f(d,b);return d},clear:function(a){var b=this,e=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,e=c.length- 1;0<=e;e--){var d=c.key(e);0===d.indexOf(a)&&c.removeItem(d)}});f(e,a);return e},length:function(a){var c=this.keys().then(function(a){return a.length});f(c,a);return c},key:function(a,b){var e=this,d=e.ready().then(function(){var b=e._dbInfo,d;try{d=c.key(a)}catch(f){d=null}d&&(d=d.substring(b.keyPrefix.length));return d});f(d,b);return d},keys:function(a){var b=this,e=b.ready().then(function(){for(var a=b._dbInfo,e=c.length,d=[],f=0;f<e;f++)0===c.key(f).indexOf(a.keyPrefix)&&d.push(c.key(f).substring(a.keyPrefix.length)); return d});f(e,a);return e}};2===e?k.exports=n:1===e?(void 0)("localStorageWrapper",function(){return n}):this.localStorageWrapper=n}).call(window)},{"./../utils/serializer":40,promise:34}],38:[function(g,k,h){(function(){function f(a){var c=this,b={db:null};if(a)for(var e in a)b[e]="string"!==typeof a[e]?a[e].toString():a[e];e=new q(function(a){z===s.DEFINE?g(["localforageSerializer"],a):z===s.EXPORT?a(g("./../utils/serializer")):a(v.localforageSerializer)});var d=new q(function(e,d){try{b.db=w(b.name, String(b.version),b.description,b.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(a)}).then(e)["catch"](d)}b.db.transaction(function(a){a.executeSql("CREATE TABLE IF NOT EXISTS "+b.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=b;e()},function(a,c){d(c)})})});return e.then(function(a){p=a;return d})}function b(a,c){var b=this;"string"!==typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a)); var e=new q(function(c,e){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT * FROM "+d.storeName+" WHERE key = ? LIMIT 1",[a],function(a,b){var e=b.rows.length?b.rows.item(0).value:null;e&&(e=p.deserialize(e));c(e)},function(a,c){e(c)})})})["catch"](e)});t(e,c);return e}function d(a,c){var b=this,e=new q(function(c,e){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT * FROM "+d.storeName,[],function(b,e){for(var d= e.rows,f=d.length,g=0;g<f;g++){var h=d.item(g),m=h.value;m&&(m=p.deserialize(m));m=a(m,h.key,g+1);if(void 0!==m){c(m);return}}c()},function(a,c){e(c)})})})["catch"](e)});t(e,c);return e}function a(a,c,b){var e=this;"string"!==typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new q(function(b,d){e.ready().then(function(){void 0===c&&(c=null);var f=c;p.serialize(c,function(c,g){if(g)d(g);else{var h=e._dbInfo;h.db.transaction(function(e){e.executeSql("INSERT OR REPLACE INTO "+ h.storeName+" (key, value) VALUES (?, ?)",[a,c],function(){b(f)},function(a,c){d(c)})},function(a){a.code===a.QUOTA_ERR&&d(a)})}})})["catch"](d)});t(d,b);return d}function c(a,c){var b=this;"string"!==typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new q(function(c,e){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName+" WHERE key = ?",[a],function(){c()},function(a,c){e(c)})})})["catch"](e)}); t(e,c);return e}function h(a){var c=this,b=new q(function(a,b){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName,[],function(){a()},function(a,c){b(c)})})})["catch"](b)});t(b,a);return b}function e(a){var c=this,b=new q(function(a,b){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT COUNT(key) as c FROM "+e.storeName,[],function(c,b){var e=b.rows.item(0).c;a(e)},function(a,c){b(c)})})})["catch"](b)}); t(b,a);return b}function n(a,c){var b=this,e=new q(function(c,e){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,b){var e=b.rows.length?b.rows.item(0).key:null;c(e)},function(a,c){e(c)})})})["catch"](e)});t(e,c);return e}function y(a){var c=this,b=new q(function(a,b){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName,[],function(c, b){for(var e=[],d=0;d<b.rows.length;d++)e.push(b.rows.item(d).key);a(e)},function(a,c){b(c)})})})["catch"](b)});t(b,a);return b}function t(a,c){c&&a.then(function(a){c(null,a)},function(a){c(a)})}var q="undefined"!==typeof k&&k.exports?g("promise"):this.Promise,v=this,p=null,w=this.openDatabase;if(w){var s={DEFINE:1,EXPORT:2,WINDOW:3},z=s.WINDOW;"undefined"!==typeof k&&k.exports&&(z=s.EXPORT);var u={_driver:"webSQLStorage",_initStorage:f,iterate:d,getItem:b,setItem:a,removeItem:c,clear:h,length:e, key:n,keys:y};z===s.DEFINE?(void 0)("webSQLStorage",function(){return u}):z===s.EXPORT?k.exports=u:this.webSQLStorage=u}}).call(window)},{"./../utils/serializer":40,promise:34}],39:[function(g,k,h){(function(){function f(a,c){a[c]=function(){var b=arguments;return a.ready().then(function(){return a[c].apply(a,b)})}}function b(){for(var a=1;a<arguments.length;a++){var c=arguments[a];if(c)for(var b in c)c.hasOwnProperty(b)&&(v(c[b])?arguments[0][b]=c[b].slice():arguments[0][b]=c[b])}return arguments[0]} function d(a){for(var c in e)if(e.hasOwnProperty(c)&&e[c]===a)return!0;return!1}function a(a){this._config=b({},y,a);this._driverSet=null;this._ready=!1;this._dbInfo=null;for(a=0;a<n.length;a++)f(this,n[a]);this.setDriver(this._config.driver)}var c="undefined"!==typeof k&&k.exports?g("promise"):this.Promise,h={},e={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},n="clear getItem iterate key keys length removeItem setItem".split(" "),y={description:"",driver:[e.INDEXEDDB, e.WEBSQL,e.LOCALSTORAGE].slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},t=3;"undefined"!==typeof k&&k.exports&&(t=2);var q=function(a){var c=c||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,b={};b[e.WEBSQL]=!!a.openDatabase;b[e.INDEXEDDB]=!!function(){if("undefined"!==typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return c&&"function"===typeof c.open&& "undefined"!==typeof a.IDBKeyRange}catch(b){return!1}}();var d=e.LOCALSTORAGE,f;try{f=a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(g){f=!1}b[d]=!!f;return b}(this),v=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},p=this;a.prototype.INDEXEDDB=e.INDEXEDDB;a.prototype.LOCALSTORAGE=e.LOCALSTORAGE;a.prototype.WEBSQL=e.WEBSQL;a.prototype.config=function(a){if("object"===typeof a){if(this._ready)return Error("Can't call config() after localforage has been used."); for(var c in a)"storeName"===c&&(a[c]=a[c].replace(/\W/g,"_")),this._config[c]=a[c];"driver"in a&&a.driver&&this.setDriver(this._config.driver);return!0}return"string"===typeof a?this._config[a]:this._config};a.prototype.defineDriver=function(a,b,e){var f=new c(function(b,e){try{var f=a._driver,g=Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),k=Error("Custom driver name already in use: "+a._driver);if(a._driver)if(d(a._driver))e(k);else{for(var t=n.concat("_initStorage"), k=0;k<t.length;k++){var p=t[k];if(!p||!a[p]||"function"!==typeof a[p]){e(g);return}}var y=c.resolve(!0);"_support"in a&&(y=a._support&&"function"===typeof a._support?a._support():c.resolve(!!a._support));y.then(function(c){q[f]=c;h[f]=a;b()},e)}else e(g)}catch(w){e(w)}});f.then(b,e);return f};a.prototype.driver=function(){return this._driver||null};a.prototype.ready=function(a){var b=this,e=new c(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config));b._ready.then(a, c)})["catch"](c)});e.then(a,a);return e};a.prototype.setDriver=function(a,b,e){function f(){k._config.driver=k.driver()}var k=this;"string"===typeof a&&(a=[a]);this._driverSet=new c(function(b,e){var f=k._getFirstSupportedDriver(a),n=Error("No available storage method found.");if(f){k._dbInfo=null;k._ready=null;if(d(f)){if(1===t){g([f],function(a){k._extend(a);b()});return}if(2===t){var q;switch(f){case k.INDEXEDDB:q=g("./drivers/indexeddb");break;case k.LOCALSTORAGE:q=g("./drivers/localstorage"); break;case k.WEBSQL:q=g("./drivers/websql")}k._extend(q)}else k._extend(p[f])}else if(h[f])k._extend(h[f]);else{k._driverSet=c.reject(n);e(n);return}b()}else k._driverSet=c.reject(n),e(n)});this._driverSet.then(f,f);this._driverSet.then(b,e);return this._driverSet};a.prototype.supports=function(a){return!!q[a]};a.prototype._extend=function(a){b(this,a)};a.prototype._getFirstSupportedDriver=function(a){if(a&&v(a))for(var c=0;c<a.length;c++){var b=a[c];if(this.supports(b))return b}return null};a.prototype.createInstance= function(c){return new a(c)};var w=new a;1===t?(void 0)("localforage",function(){return w}):2===t?k.exports=w:this.localforage=w}).call(window)},{"./drivers/indexeddb":36,"./drivers/localstorage":37,"./drivers/websql":38,promise:34}],40:[function(g,k,h){(function(){function f(a){var b=0.75*a.length,e=a.length,f=0,g,h,k,v;"="===a[a.length-1]&&(b--,"="===a[a.length-2]&&b--);for(var p=new ArrayBuffer(b),w=new Uint8Array(p),b=0;b<e;b+=4)g=d.indexOf(a[b]),h=d.indexOf(a[b+1]),k=d.indexOf(a[b+2]),v=d.indexOf(a[b+ 3]),w[f++]=g<<2|h>>4,w[f++]=(h&15)<<4|k>>2,w[f++]=(k&3)<<6|v&63;return p}function b(a){a=new Uint8Array(a);var b="",e;for(e=0;e<a.length;e+=3)b+=d[a[e]>>2],b+=d[(a[e]&3)<<4|a[e+1]>>4],b+=d[(a[e+1]&15)<<2|a[e+2]>>6],b+=d[a[e+2]&63];2===a.length%3?b=b.substring(0,b.length-1)+"=":1===a.length%3&&(b=b.substring(0,b.length-2)+"==");return b}var d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a={serialize:function(a,d){var e="";a&&(e=a.toString());if(a&&("[object ArrayBuffer]"===a.toString()|| a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var f,g="__lfsc__:";a instanceof ArrayBuffer?(f=a,g+="arbf"):(f=a.buffer,"[object Int8Array]"===e?g+="si08":"[object Uint8Array]"===e?g+="ui08":"[object Uint8ClampedArray]"===e?g+="uic8":"[object Int16Array]"===e?g+="si16":"[object Uint16Array]"===e?g+="ur16":"[object Int32Array]"===e?g+="si32":"[object Uint32Array]"===e?g+="ui32":"[object Float32Array]"===e?g+="fl32":"[object Float64Array]"===e?g+="fl64":d(Error("Failed to get type for BinaryArray"))); d(g+b(f))}else if("[object Blob]"===e)e=new FileReader,e.onload=function(){var a=b(this.result);d("__lfsc__:blob"+a)},e.readAsArrayBuffer(a);else try{d(JSON.stringify(a))}catch(h){window.console.error("Couldn't convert value into a JSON string: ",a),d(null,h)}},deserialize:function(a){if("__lfsc__:"!==a.substring(0,9))return JSON.parse(a);var b=a.substring(13);a=a.substring(9,13);b=f(b);switch(a){case "arbf":return b;case "blob":return new Blob([b]);case "si08":return new Int8Array(b);case "ui08":return new Uint8Array(b); case "uic8":return new Uint8ClampedArray(b);case "si16":return new Int16Array(b);case "ur16":return new Uint16Array(b);case "si32":return new Int32Array(b);case "ui32":return new Uint32Array(b);case "fl32":return new Float32Array(b);case "fl64":return new Float64Array(b);default:throw Error("Unkown type: "+a);}},stringToBuffer:f,bufferToString:b};"undefined"!==typeof k&&k.exports?k.exports=a:this.localforageSerializer=a}).call(window)},{}],41:[function(g,k,h){(function(f,b){f(function(d){function a(b, e){if(!(this instanceof a))return new a(b,e);b instanceof a?(this._template=b.template,this._params=c({},this._params,e)):(this._template=(b||"").toString(),this._params=e||{})}var c,f,e,g,h;c=d("./util/mixin");e=/([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?(\/[^?#]*)?(\?[^#]*)?(#\S*)?/i;g=/^([a-z][a-z0-9\-\+\.]*:\/\/|\/)/i;h=/([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?\//i;a.prototype={append:function(b,e){return new a(this._template+b,c({},this._params,e))},fullyQualify:function(){if(!b|| this.isFullyQualified())return this;var c=this._template;0===c.indexOf("//")?c=f.protocol+c:0===c.indexOf("/")?c=f.origin+c:this.isAbsolute()||(c=f.origin+f.pathname.substring(0,f.pathname.lastIndexOf("/")+1));-1===c.indexOf("/",8)&&(c+="/");return new a(c,this._params)},isAbsolute:function(){return g.test(this.build())},isFullyQualified:function(){return h.test(this.build())},isCrossOrigin:function(){if(!f)return!0;var a=this.parts();return a.protocol!==f.protocol||a.hostname!==f.hostname||a.port!== f.port},parts:function(){var a;a=this.fullyQualify().build().match(e);a={href:a[0],protocol:a[1],host:a[3]||"",hostname:a[4]||"",port:a[6],pathname:a[7]||"",search:a[8]||"",hash:a[9]||""};a.origin=a.protocol+"//"+a.host;a.port=a.port||("https:"===a.protocol?"443":"http:"===a.protocol?"80":"");return a},build:function(a){a=c({},this._params,a);var b,e,d,f;b=this._template;d={};if(a){for(e in a)f=RegExp("\\{"+e+"\\}"),f.test(b)?b=b.replace(f,encodeURIComponent(a[e]),"g"):d[e]=a[e];for(e in d)b+=-1=== b.indexOf("?")?"?":"&",b+=encodeURIComponent(e),null!==d[e]&&void 0!==d[e]&&(b+="=",b+=encodeURIComponent(d[e]))}return b},toString:function(){return this.build()}};f=b?(new a(b.href)).parts():void 0;return a})})(function(f){k.exports=f(g)},"undefined"!==typeof window?window.location:void 0)},{"./util/mixin":77}],42:[function(g,k,h){(function(f){f(function(b){var d=b("./client/default");b=b("./client/xhr");d.setPlatformDefaultClient(b);return d})})(function(f){k.exports=f(g)})},{"./client/default":44, "./client/xhr":45}],43:[function(g,k,h){(function(f){f(function(){return function(b,d){d&&(b.skip=function(){return d});b.wrap=function(a,c){return a(b,c)};b.chain=function(){"undefined"!==typeof console&&console.log("rest.js: client.chain() is deprecated, use client.wrap() instead");return b.wrap.apply(this,arguments)};return b}})})(function(f){k.exports=f(g)})},{}],44:[function(g,k,h){(function(f){f(function(b){function d(){return a.apply(void 0,arguments)}var a,c;b=b("../client");d.setDefaultClient= function(b){a=b};d.getDefaultClient=function(){return a};d.resetDefaultClient=function(){a=c};d.setPlatformDefaultClient=function(b){if(c)throw Error("Unable to redefine platformDefaultClient");a=c=b};return b(d)})})(function(f){k.exports=f(g)})},{"../client":43}],45:[function(g,k,h){(function(f,b){f(function(d){function a(a){var b={};if(!a)return b;a.trim().split(h).forEach(function(a){var c,d;c=a.indexOf(":");d=e(a.substring(0,c).trim());a=a.substring(c+1).trim();b[d]?Array.isArray(b[d])?b[d].push(a): b[d]=[b[d],a]:b[d]=a});return b}function c(a,b){Object.keys(b||{}).forEach(function(c){if(b.hasOwnProperty(c)&&c in a)try{a[c]=b[c]}catch(e){}});return a}var f,e,g,h;d("when");f=d("../UrlBuilder");e=d("../util/normalizeHeaderName");g=d("../util/responsePromise");d=d("../client");h=/[\r|\n]+/;return d(function(e){return g.promise(function(d,g){var h,k,n,y,u,r,l,x;e="string"===typeof e?{path:e}:e||{};l={request:e};if(e.canceled)l.error="precanceled",g(l);else if(x=e.engine||b.XMLHttpRequest){u=e.entity; e.method=e.method||(u?"POST":"GET");k=e.method;n=(new f(e.path||"",e.params)).build();try{h=l.raw=new x;c(h,e.mixin);h.open(k,n,!0);c(h,e.mixin);y=e.headers;for(r in y)"Content-Type"===r&&"multipart/form-data"===y[r]||h.setRequestHeader(r,y[r]);e.canceled=!1;e.cancel=function(){e.canceled=!0;h.abort();g(l)};h.onreadystatechange=function(){e.canceled||h.readyState!==(x.DONE||4)||(l.status={code:h.status,text:h.statusText},l.headers=a(h.getAllResponseHeaders()),l.entity=h.responseText,0<l.status.code? d(l):setTimeout(function(){d(l)},0))};try{h.onerror=function(){l.error="loaderror";g(l)}}catch(B){}h.send(u)}catch(A){l.error="loaderror",g(l)}}else g({request:e,error:"xhr-not-available"})})})})})(function(f){k.exports=f(g)},"undefined"!==typeof window?window:void 0)},{"../UrlBuilder":41,"../client":43,"../util/normalizeHeaderName":78,"../util/responsePromise":79,when:74}],46:[function(g,k,h){(function(f){f(function(b){function d(a){return a}function a(a){return a}function c(a){return a}function f(a){return p.promise(function(b, c){a.forEach(function(a){p(a,b,c)})})}function e(a){if(!(this instanceof e))return new e(a);k(this,a)}function g(b){var k,n,t,r;b=b||{};k=b.init||d;n=b.request||a;t=b.success||b.response||c;r=b.error||function(){return p((b.response||c).apply(this,arguments),p.reject,p.reject)};return function(a,c){function d(b){var g,h;g={};h={arguments:Array.prototype.slice.call(arguments),client:d};b="string"===typeof b?{path:b}:b||{};b.originator=b.originator||d;return q(n.call(g,b,c,h),function(b){var d,k,n; n=a;b instanceof e&&(k=b.abort,n=b.client||n,d=b.response,b=b.request);d=d||p(b,function(a){return p(n(a),function(a){return t.call(g,a,c,h)},function(a){return r.call(g,a,c,h)})});return k?f([d,k]):d},function(a){return p.reject({request:b,error:a})})}"object"===typeof a&&(c=a);"function"!==typeof a&&(a=b.client||h);c=k(c||{});return v(d,a)}}var h,k,q,v,p;h=b("./client/default");k=b("./util/mixin");q=b("./util/responsePromise");v=b("./client");p=b("when");g.ComplexRequest=e;return g})})(function(f){k.exports= f(g)})},{"./client":43,"./client/default":44,"./util/mixin":77,"./util/responsePromise":79,when:74}],47:[function(g,k,h){(function(f){f(function(b){var d,a,c,f,e;d=b("../interceptor");a=b("../mime");c=b("../mime/registry");e=b("when");f={read:function(a){return a},write:function(a){return a}};return d({init:function(a){a.registry=a.registry||c;return a},request:function(b,c){var d,g;g=b.headers||(b.headers={});d=a.parse(g["Content-Type"]=g["Content-Type"]||c.mime||"text/plain");g.Accept=g.Accept|| c.accept||d.raw+", application/json;q=0.8, text/plain;q=0.5, */*;q=0.2";return"entity"in b?c.registry.lookup(d).otherwise(function(){if(c.permissive)return f;throw"mime-unknown";}).then(function(a){return e.attempt(a.write,b.entity,{client:c.client||b.originator,request:b,mime:d,registry:c.registry}).otherwise(function(){throw"mime-serialization";}).then(function(a){b.entity=a;return b})}):b},response:function(b,c){if(!(b.headers&&b.headers["Content-Type"]&&b.entity))return b;var d=a.parse(b.headers["Content-Type"]); return c.registry.lookup(d).otherwise(function(){return f}).then(function(a){return e.attempt(a.read,b.entity,{client:c.client||b.request&&b.request.originator,response:b,mime:d,registry:c.registry}).otherwise(function(a){b.error="mime-deserialization";b.cause=a;throw b;}).then(function(a){b.entity=a;return b})})}})})})(function(f){k.exports=f(g)})},{"../interceptor":46,"../mime":50,"../mime/registry":51,when:74}],48:[function(g,k,h){(function(f){f(function(b){var d,a;d=b("../interceptor");a=b("../UrlBuilder"); return d({request:function(b,d){var e;d.prefix&&!(new a(b.path)).isFullyQualified()&&(e=d.prefix,b.path&&(e.lastIndexOf("/")+1!==e.length&&0!==b.path.indexOf("/")&&(e+="/"),e+=b.path),b.path=e);return b}})})})(function(f){k.exports=f(g)})},{"../UrlBuilder":41,"../interceptor":46}],49:[function(g,k,h){(function(f){f(function(b){var d,a,c;d=b("../interceptor");a=b("../util/uriTemplate");c=b("../util/mixin");return d({init:function(a){a.params=a.params||{};a.template=a.template||"";return a},request:function(b, e){var d,f;d=b.path||e.template;f=c({},b.params,e.params);b.path=a.expand(d,f);delete b.params;return b}})})})(function(f){k.exports=f(g)})},{"../interceptor":46,"../util/mixin":77,"../util/uriTemplate":81}],50:[function(g,k,h){(function(f){f(function(){return{parse:function(b){var d,a;d=b.split(";");a=d[0].trim().split("+");return{raw:b,type:a[0],suffix:a[1]?"+"+a[1]:"",params:d.slice(1).reduce(function(a,b){b=b.split("=");a[b[0].trim()]=b[1]?b[1].trim():void 0;return a},{})}}}})})(function(f){k.exports= f(g)})},{}],51:[function(g,k,h){(function(f){f(function(b){function d(b){this.lookup=function(d){d="string"===typeof d?a.parse(d):d;return b[d.raw]?b[d.raw]:b[d.type+d.suffix]?b[d.type+d.suffix]:b[d.type]?b[d.type]:b[d.suffix]?b[d.suffix]:c.reject(Error('Unable to locate converter for mime "'+d.raw+'"'))};this.delegate=function(a){return{read:function(){var b=arguments;return this.lookup(a).then(function(a){return a.read.apply(this,b)}.bind(this))}.bind(this),write:function(){var b=arguments;return this.lookup(a).then(function(a){return a.write.apply(this, b)}.bind(this))}.bind(this)}};this.register=function(a,d){b[a]=c(d);return b[a]};this.child=function(){return new d(Object.create(b))}}var a,c,f;a=b("../mime");c=b("when");f=new d({});f.register("application/hal",b("./type/application/hal"));f.register("application/json",b("./type/application/json"));f.register("application/x-www-form-urlencoded",b("./type/application/x-www-form-urlencoded"));f.register("multipart/form-data",b("./type/multipart/form-data"));f.register("text/plain",b("./type/text/plain")); f.register("+json",f.delegate("application/json"));return f})})(function(f){k.exports=f(g)})},{"../mime":50,"./type/application/hal":52,"./type/application/json":53,"./type/application/x-www-form-urlencoded":54,"./type/multipart/form-data":55,"./type/text/plain":56,when:74}],52:[function(g,k,h){(function(f){f(function(b){function d(a,b,c){Object.defineProperty(a,b,{value:c,configurable:!0,enumerable:!1,writeable:!0})}var a,c,f,e,g,h;a=b("../../../interceptor/pathPrefix");c=b("../../../interceptor/template"); f=b("../../../util/find");e=b("../../../util/lazyPromise");g=b("../../../util/responsePromise");h=b("when");return{read:function(b,k){function v(a,b){(b&&w&&w.warn||w.log)&&(w.warn||w.log).call(w,"Relationship '"+a+"' is deprecated, see "+b)}var p,w;k=k||{};p=k.client;w=k.console||w;return k.registry.lookup(k.mime.suffix).then(function(s){return h(s.read(b,k)).then(function(b){f.findProperties(b,"_embedded",function(a,b,c){Object.keys(a).forEach(function(c){if(!(c in b)){var e=g({entity:a[c]});d(b, c,e)}});d(b,c,a)});f.findProperties(b,"_links",function(b,f,h){Object.keys(b).forEach(function(a){var h=b[a];a in f||d(f,a,g.make(e(function(){h.deprecation&&v(a,h.deprecation);return!0===h.templated?c(p)({path:h.href}):p({path:h.href})})))});d(f,h,b);d(f,"clientFor",function(e,d){var f=b[e];if(!f)throw Error("Unknown relationship: "+e);f.deprecation&&v(e,f.deprecation);return!0===f.templated?c(d||p,{template:f.href}):a(d||p,{prefix:f.href})});d(f,"requestFor",function(a,b,c){return this.clientFor(a, c)(b)})});return b})})},write:function(a,b){return b.registry.lookup(b.mime.suffix).then(function(c){return c.write(a,b)})}}})})(function(f){k.exports=f(g)})},{"../../../interceptor/pathPrefix":48,"../../../interceptor/template":49,"../../../util/find":75,"../../../util/lazyPromise":76,"../../../util/responsePromise":79,when:74}],53:[function(g,k,h){(function(f){f(function(){function b(d,a){return{read:function(a){return JSON.parse(a,d)},write:function(b){return JSON.stringify(b,a)},extend:b}}return b()})})(function(f){k.exports= f(g)})},{}],54:[function(g,k,h){(function(f){f(function(){function b(a){a=encodeURIComponent(a);return a.replace(c,"+")}function d(a){a=a.replace(f," ");return decodeURIComponent(a)}function a(c,d,f){Array.isArray(f)?f.forEach(function(b){c=a(c,d,b)}):(0<c.length&&(c+="&"),c+=b(d),void 0!==f&&null!==f&&(c+="="+b(f)));return c}var c,f;c=/%20/g;f=/\+/g;return{read:function(a){var b={};a.split("&").forEach(function(a){var c;c=a.split("=");a=d(c[0]);c=2===c.length?d(c[1]):null;a in b?(Array.isArray(b[a])|| (b[a]=[b[a]]),b[a].push(c)):b[a]=c});return b},write:function(b){var c="";Object.keys(b).forEach(function(d){c=a(c,d,b[d])});return c}}})})(function(f){k.exports=f(g)})},{}],55:[function(g,k,h){(function(f){f(function(){return{write:function(b){if("undefined"===typeof FormData)throw Error("The multipart/form-data mime serializer requires FormData support");if(b instanceof FormData)return b;if(b&&1===b.nodeType&&"FORM"===b.tagName)return new FormData(b);if("object"===typeof b&&null!==b){var d=new FormData, a,c;for(c in b)b.hasOwnProperty(c)&&(a=b[c],a instanceof File?d.append(c,a,a.name):a instanceof Blob?d.append(c,a):d.append(c,String(a)));return d}throw Error("Unable to create FormData from object "+b);}}})})(function(f){k.exports=f(g)})},{}],56:[function(g,k,h){(function(f){f(function(){return{read:function(b){return b},write:function(b){return b.toString()}}})})(function(f){k.exports=f(g)})},{}],57:[function(g,k,h){(function(f){f(function(b){var d=b("./makePromise"),a=b("./Scheduler");b=b("./env").asap; return d({scheduler:new a(b)})})})(function(f){k.exports=f(g)})},{"./Scheduler":58,"./env":70,"./makePromise":72}],58:[function(g,k,h){(function(f){f(function(){function b(b){this._async=b;this._running=!1;this._queue=this;this._queueLen=0;this._afterQueue={};this._afterQueueLen=0;var a=this;this.drain=function(){a._drain()}}b.prototype.enqueue=function(b){this._queue[this._queueLen++]=b;this.run()};b.prototype.afterQueue=function(b){this._afterQueue[this._afterQueueLen++]=b;this.run()};b.prototype.run= function(){this._running||(this._running=!0,this._async(this.drain))};b.prototype._drain=function(){for(var b=0;b<this._queueLen;++b)this._queue[b].run(),this._queue[b]=void 0;this._queueLen=0;this._running=!1;for(b=0;b<this._afterQueueLen;++b)this._afterQueue[b].run(),this._afterQueue[b]=void 0;this._afterQueueLen=0};return b})})(function(f){k.exports=f()})},{}],59:[function(g,k,h){(function(f){f(function(){function b(d){Error.call(this);this.message=d;this.name=b.name;"function"===typeof Error.captureStackTrace&& Error.captureStackTrace(this,b)}b.prototype=Object.create(Error.prototype);return b.prototype.constructor=b})})(function(f){k.exports=f()})},{}],60:[function(g,k,h){(function(f){f(function(){function b(a,b){function f(d,g){if(0>d.i)return b(d.f,d.thisArg,d.params,g);a._handler(d.args[d.i]).fold(e,d,void 0,g)}function e(a,b,c){a.params[a.i]=b;a.i-=1;f(a,c)}2>arguments.length&&(b=d);return function(e,d,g){var h=a._defer(),k=g.length;f({f:e,thisArg:d,args:g,params:Array(k),i:k-1,call:b},h._handler); return h}}function d(a,b,d,e){try{e.resolve(a.apply(b,d))}catch(f){e.reject(f)}}b.tryCatchResolve=d;return b})})(function(f){k.exports=f()})},{}],61:[function(g,k,h){(function(f){f(function(b){var d=b("../state"),a=b("../apply");return function(b){function f(a){var e=b._handler(a);if(0===e.state())return h(a).then(d.fulfilled,d.rejected);e._unreport();return d.inspect(e)}function e(a){return function(b,c,e){return g(a,void 0,[b,c,e])}}var g=a(b),h=b.resolve,k=b.all,q=Array.prototype.reduce,v=Array.prototype.reduceRight, p=Array.prototype.slice;b.any=function(a){function e(a){m=null;this.resolve(a)}function d(a){this.resolved||(m.push(a),0===--k&&this.reject(m))}for(var f=b._defer(),g=f._handler,h=a.length>>>0,k=h,m=[],q,p=0;p<h;++p)if(q=a[p],void 0!==q||p in a)if(q=b._handler(q),0<q.state()){g.become(q);b._visitRemaining(a,p,q);break}else q.visit(g,e,d);else--k;0===k&&g.reject(new RangeError("any(): array must not be empty"));return f};b.some=function(a,e){function d(a){this.resolved||(k.push(a),0===--p&&(m=null, this.resolve(k)))}function f(a){this.resolved||(m.push(a),0===--n&&(k=null,this.reject(m)))}var g=b._defer(),h=g._handler,k=[],m=[],q=a.length>>>0,p=0,n,t,v;for(v=0;v<q;++v)t=a[v],(void 0!==t||v in a)&&++p;e=Math.max(e,0);n=p-e+1;p=Math.min(e,p);e>p?h.reject(new RangeError("some(): array must contain at least "+e+" item(s), but had "+p)):0===p&&h.resolve(k);for(v=0;v<q;++v)t=a[v],(void 0!==t||v in a)&&b._handler(t).visit(h,d,f,h.notify);return g};b.settle=function(a){return k(a.map(f))};b.map=function(a, e){return b._traverse(e,a)};b.filter=function(a,e){var d=p.call(a);return b._traverse(e,d).then(function(a){for(var e=a.length,f=Array(e),g=0,h=0;g<e;++g)a[g]&&(f[h++]=b._handler(d[g]).value);f.length=h;return f})};b.reduce=function(a,b){return 2<arguments.length?q.call(a,e(b),arguments[2]):q.call(a,e(b))};b.reduceRight=function(a,b){return 2<arguments.length?v.call(a,e(b),arguments[2]):v.call(a,e(b))};b.prototype.spread=function(a){return this.then(k).then(function(b){return a.apply(this,b)})};return b}})})(function(f){k.exports= f(g)})},{"../apply":60,"../state":73}],62:[function(g,k,h){(function(f){f(function(){function b(){throw new TypeError("catch predicate must be a function");}function d(a){return a}return function(a){function c(a,b){return function(c){return(b===Error||null!=b&&b.prototype instanceof Error?c instanceof b:b(c))?a.call(this,c):h(c)}}function f(a,b,c,d){a=a.call(b);return"object"!==typeof a&&"function"!==typeof a||null===a?c(d):e(a,c,d)}function e(a,b,c){return g(a).then(function(){return b(c)})}var g= a.resolve,h=a.reject,k=a.prototype["catch"];a.prototype.done=function(a,b){this._handler.visit(this._handler.receiver,a,b)};a.prototype["catch"]=a.prototype.otherwise=function(a){return 2>arguments.length?k.call(this,a):"function"!==typeof a?this.ensure(b):k.call(this,c(arguments[1],a))};a.prototype["finally"]=a.prototype.ensure=function(a){return"function"!==typeof a?this:this.then(function(b){return f(a,this,d,b)},function(b){return f(a,this,h,b)})};a.prototype["else"]=a.prototype.orElse=function(a){return this.then(void 0, function(){return a})};a.prototype.yield=function(a){return this.then(function(){return a})};a.prototype.tap=function(a){return this.then(a).yield(this)};return a}})})(function(f){k.exports=f()})},{}],63:[function(g,k,h){(function(f){f(function(){return function(b){b.prototype.fold=function(d,a){var c=this._beget();this._handler.fold(function(a,c,f){b._handler(a).fold(function(a,b,c){c.resolve(d.call(this,b,a))},c,this,f)},a,c._handler.receiver,c._handler);return c};return b}})})(function(f){k.exports= f()})},{}],64:[function(g,k,h){(function(f){f(function(b){var d=b("../state").inspect;return function(a){a.prototype.inspect=function(){return d(a._handler(this))};return a}})})(function(f){k.exports=f(g)})},{"../state":73}],65:[function(g,k,h){(function(f){f(function(){return function(b){function d(b,f,e,g){function h(g,k){return a(e(g)).then(function(){return d(b,f,e,k)})}return a(g).then(function(e){return a(f(e)).then(function(d){return d?e:a(b(e)).spread(h)})})}var a=b.resolve;b.iterate=function(a, b,e,f){return d(function(b){return[b,a(b)]},b,e,f)};b.unfold=d;return b}})})(function(f){k.exports=f()})},{}],66:[function(g,k,h){(function(f){f(function(){return function(b){b.prototype.progress=function(b){return this.then(void 0,void 0,b)};return b}})})(function(f){k.exports=f()})},{}],67:[function(g,k,h){(function(f){f(function(b){function d(b,c,d,f){return a.setTimer(function(){b(d,f,c)},c)}var a=b("../env"),c=b("../TimeoutError");return function(b){function e(a,b,c){d(f,a,b,c)}function f(a, b){b.resolve(a)}function g(a,b,e){a="undefined"===typeof a?new c("timed out after "+e+"ms"):a;b.reject(a)}b.prototype.delay=function(a){var b=this._beget();this._handler.fold(e,a,void 0,b._handler);return b};b.prototype.timeout=function(b,c){var e=this._beget(),f=e._handler,h=d(g,b,c,e._handler);this._handler.visit(f,function(b){a.clearTimer(h);this.resolve(b)},function(b){a.clearTimer(h);this.reject(b)},f.notify);return e};return b}})})(function(f){k.exports=f(g)})},{"../TimeoutError":59,"../env":70}], 68:[function(g,k,h){(function(f){f(function(b){function d(a){throw a;}function a(){}var c=b("../env").setTimer,f=b("../format");return function(b){function g(a){a.handled||(z.push(a),v("Potentially unhandled rejection ["+a.id+"] "+f.formatError(a.value)))}function h(a){var b=z.indexOf(a);0<=b&&(z.splice(b,1),p("Handled previous rejection ["+a.id+"] "+f.formatObject(a.value)))}function k(a,b){s.push(a,b);null===u&&(u=c(q,0))}function q(){for(u=null;0<s.length;)s.shift()(s.shift())}var v=a,p=a,w;"undefined"!== typeof console&&(w=console,v="undefined"!==typeof w.error?function(a){w.error(a)}:function(a){w.log(a)},p="undefined"!==typeof w.info?function(a){w.info(a)}:function(a){w.log(a)});b.onPotentiallyUnhandledRejection=function(a){k(g,a)};b.onPotentiallyUnhandledRejectionHandled=function(a){k(h,a)};b.onFatalRejection=function(a){k(d,a.value)};var s=[],z=[],u=null;return b}})})(function(f){k.exports=f(g)})},{"../env":70,"../format":71}],69:[function(g,k,h){(function(f){f(function(){return function(b){b.prototype["with"]= b.prototype.withThis=function(b){var a=this._beget(),c=a._handler;c.receiver=b;this._handler.chain(c,b);return a};return b}})})(function(f){k.exports=f()})},{}],70:[function(g,k,h){(function(f){(function(b){b(function(b){function a(a){var b,c=document.createTextNode("");(new a(function(){var a=b;b=void 0;a()})).observe(c,{characterData:!0});var e=0;return function(a){b=a;c.data=e^=1}}var c,g="undefined"!==typeof setTimeout&&setTimeout,e=function(a,b){return setTimeout(a,b)},h=function(a){return clearTimeout(a)}, k=function(a){return g(a,0)};if("undefined"!==typeof f&&null!==f&&"function"===typeof f.nextTick)k=function(a){return f.nextTick(a)};else if(c="function"===typeof MutationObserver&&MutationObserver||"function"===typeof WebKitMutationObserver&&WebKitMutationObserver)k=a(c);else if(!g)var t=b("vertx"),e=function(a,b){return t.setTimer(b,a)},h=t.cancelTimer,k=t.runOnLoop||t.runOnContext;return{setTimer:e,clearTimer:h,asap:k}})})(function(b){k.exports=b(g)})}).call(this,g("_process"))},{_process:82}], 71:[function(g,k,h){(function(f){f(function(){function b(a){var b=String(a);"[object Object]"===b&&"undefined"!==typeof JSON&&(b=d(a,b));return b}function d(a,b){try{return JSON.stringify(a)}catch(d){return b}}return{formatError:function(a){var c="object"===typeof a&&null!==a&&a.stack?a.stack:b(a);return a instanceof Error?c:c+" (WARNING: non-Error used)"},formatObject:b,tryStringify:d}})})(function(f){k.exports=f()})},{}],72:[function(g,k,h){(function(f){(function(b){b(function(){return function(b){function a(a, b){this._handler=a===p?b:c(a)}function c(a){function b(a){d.resolve(a)}function c(a){d.reject(a)}function e(a){d.notify(a)}var d=new s;try{a(b,c,e)}catch(f){c(f)}return d}function g(b){return b instanceof a?b:new a(p,new z(q(b)))}function e(b){return new a(p,new z(new l(b)))}function h(b,c,e){function d(a,g,h){h.resolved||k(e,f,a,b(c,g,a),h)}function f(a,b,c){n[a]=b;0===--m&&c.become(new r(n))}for(var g="function"===typeof c?d:f,l=new s,m=e.length>>>0,n=Array(m),q=0,t;q<e.length&&!l.resolved;++q)t= e[q],void 0!==t||q in e?k(e,g,q,t,l):--m;0===m&&l.become(new r(n));return new a(p,l)}function k(b,c,e,d,f){if(K(d)){d=d instanceof a?d._handler.join():v(d);var g=d.state();0===g?d.fold(c,e,void 0,f):0<g?c(e,d.value,f):(f.become(d),t(b,e+1,d))}else c(e,d,f)}function t(a,b,c){for(;b<a.length;++b){var e=q(a[b]);if(e!==c){var d=e.state();0===d?e.visit(e,void 0,e._unreport):0>d&&e._unreport()}}}function q(b){return b instanceof a?b._handler.join():K(b)?v(b):new r(b)}function v(a){try{var b=a.then;return"function"=== typeof b?new u(b,a):new r(a)}catch(c){return new l(c)}}function p(){}function w(){}function s(b,c){a.createContext(this,c);this.consumers=void 0;this.receiver=b;this.handler=void 0;this.resolved=!1}function z(a){this.handler=a}function u(a,b){s.call(this);D.enqueue(new J(a,b,this))}function r(b){a.createContext(this);this.value=b}function l(b){a.createContext(this);this.id=++R;this.value=b;this.reported=this.handled=!1;this._report()}function x(a,b){this.rejection=a;this.context=b}function B(a){this.rejection= a}function A(a,b){this.continuation=a;this.handler=b}function C(a,b){this.handler=b;this.value=a}function J(a,b,c){this._then=a;this.thenable=b;this.resolver=c}function O(a,b,c,e,d){try{a.call(b,c,e,d)}catch(f){e(f)}}function F(a,b,c,e){this.f=a;this.z=b;this.c=c;this.to=e;this.resolver=M;this.receiver=this}function K(a){return("object"===typeof a||"function"===typeof a)&&null!==a}function L(b,c,e,d){if("function"!==typeof b)return d.become(c);a.enterContext(c);try{d.become(q(b.call(e,c.value)))}catch(f){d.become(new l(f))}a.exitContext()} function P(a,b,c){try{return a(b,c)}catch(d){return e(d)}}function E(a,b){b.prototype=S(a.prototype);b.prototype.constructor=b}function Q(a,b){return b}function G(){}var D=b.scheduler,I=function(){return"undefined"!==typeof f&&null!==f&&"function"===typeof f.emit?function(a,b){return"unhandledRejection"===a?f.emit(a,b.value,b):f.emit(a,b)}:"undefined"!==typeof self&&"function"===typeof CustomEvent?function(a,b,c){var e=!1;try{e=new c("unhandledRejection")instanceof c}catch(d){}return e?function(a, e){var d=new c(a,{detail:{reason:e.value,key:e},bubbles:!1,cancelable:!0});return!b.dispatchEvent(d)}:a}(G,self,CustomEvent):G}(),S=Object.create||function(a){function b(){}b.prototype=a;return new b};a.resolve=g;a.reject=e;a.never=function(){return N};a._defer=function(){return new a(p,new s)};a._handler=q;a.prototype.then=function(a,b,c){var e=this._handler,d=e.join().state();if("function"!==typeof a&&0<d||"function"!==typeof b&&0>d)return new this.constructor(p,e);d=this._beget();e.chain(d._handler, e.receiver,a,b,c);return d};a.prototype["catch"]=function(a){return this.then(void 0,a)};a.prototype._beget=function(){var a=this._handler,b=this.constructor,a=new s(a.receiver,a.join().context);return new b(p,a)};a.all=function(a){return h(Q,null,a)};a.race=function(b){if("object"!==typeof b||null===b)return e(new TypeError("non-iterable passed to race()"));if(0===b.length)b=N;else if(1===b.length)b=g(b[0]);else{var c=new s,d,f;for(d=0;d<b.length;++d)if(f=b[d],void 0!==f||d in b)if(f=q(f),0!==f.state()){c.become(f); t(b,d+1,f);break}else f.visit(c,c.resolve,c.reject);b=new a(p,c)}return b};a._traverse=function(a,b){return h(P,a,b)};a._visitRemaining=t;p.prototype.when=p.prototype.become=p.prototype.notify=p.prototype.fail=p.prototype._unreport=p.prototype._report=G;p.prototype._state=0;p.prototype.state=function(){return this._state};p.prototype.join=function(){for(var a=this;void 0!==a.handler;)a=a.handler;return a};p.prototype.chain=function(a,b,c,e,d){this.when({resolver:a,receiver:b,fulfilled:c,rejected:e, progress:d})};p.prototype.visit=function(a,b,c,e){this.chain(M,a,b,c,e)};p.prototype.fold=function(a,b,c,e){this.when(new F(a,b,c,e))};E(p,w);w.prototype.become=function(a){a.fail()};var M=new w;E(p,s);s.prototype._state=0;s.prototype.resolve=function(a){this.become(q(a))};s.prototype.reject=function(a){this.resolved||this.become(new l(a))};s.prototype.join=function(){if(!this.resolved)return this;for(var a=this;void 0!==a.handler;)if(a=a.handler,a===this)return this.handler=new l(new TypeError("Promise cycle")); return a};s.prototype.run=function(){var a=this.consumers,b=this.handler;this.handler=this.handler.join();this.consumers=void 0;for(var c=0;c<a.length;++c)b.when(a[c])};s.prototype.become=function(a){this.resolved||(this.resolved=!0,this.handler=a,void 0!==this.consumers&&D.enqueue(this),void 0!==this.context&&a._report(this.context))};s.prototype.when=function(a){this.resolved?D.enqueue(new A(a,this.handler)):void 0===this.consumers?this.consumers=[a]:this.consumers.push(a)};s.prototype.notify=function(a){this.resolved|| D.enqueue(new C(a,this))};s.prototype.fail=function(a){a="undefined"===typeof a?this.context:a;this.resolved&&this.handler.join().fail(a)};s.prototype._report=function(a){this.resolved&&this.handler.join()._report(a)};s.prototype._unreport=function(){this.resolved&&this.handler.join()._unreport()};E(p,z);z.prototype.when=function(a){D.enqueue(new A(a,this))};z.prototype._report=function(a){this.join()._report(a)};z.prototype._unreport=function(){this.join()._unreport()};E(s,u);E(p,r);r.prototype._state= 1;r.prototype.fold=function(b,c,e,d){if("function"!==typeof b)d.become(this);else{a.enterContext(this);try{b.call(e,c,this.value,d)}catch(f){d.become(new l(f))}a.exitContext()}};r.prototype.when=function(a){L(a.fulfilled,this,a.receiver,a.resolver)};var R=0;E(p,l);l.prototype._state=-1;l.prototype.fold=function(a,b,c,e){e.become(this)};l.prototype.when=function(a){"function"===typeof a.rejected&&this._unreport();L(a.rejected,this,a.receiver,a.resolver)};l.prototype._report=function(a){D.afterQueue(new x(this, a))};l.prototype._unreport=function(){this.handled||(this.handled=!0,D.afterQueue(new B(this)))};l.prototype.fail=function(b){this.reported=!0;I("unhandledRejection",this);a.onFatalRejection(this,void 0===b?this.context:b)};x.prototype.run=function(){this.rejection.handled||this.rejection.reported||(this.rejection.reported=!0,I("unhandledRejection",this.rejection)||a.onPotentiallyUnhandledRejection(this.rejection,this.context))};B.prototype.run=function(){this.rejection.reported&&(I("rejectionHandled", this.rejection)||a.onPotentiallyUnhandledRejectionHandled(this.rejection))};a.createContext=a.enterContext=a.exitContext=a.onPotentiallyUnhandledRejection=a.onPotentiallyUnhandledRejectionHandled=a.onFatalRejection=G;b=new p;var N=new a(p,b);A.prototype.run=function(){this.handler.join().when(this.continuation)};C.prototype.run=function(){var b=this.handler.consumers;if(void 0!==b)for(var c,e=0;e<b.length;++e){c=b[e];var d=c.progress,f=this.value,g=this.handler,h=c.receiver;c=c.resolver;if("function"!== typeof d)c.notify(f);else{a.enterContext(g);g=c;try{g.notify(d.call(h,f))}catch(k){g.notify(k)}a.exitContext()}}};J.prototype.run=function(){var a=this.resolver;O(this._then,this.thenable,function(b){a.resolve(b)},function(b){a.reject(b)},function(b){a.notify(b)})};F.prototype.fulfilled=function(a){this.f.call(this.c,this.z,a,this.to)};F.prototype.rejected=function(a){this.to.reject(a)};F.prototype.progress=function(a){this.to.notify(a)};return a}})})(function(b){k.exports=b()})}).call(this,g("_process"))}, {_process:82}],73:[function(g,k,h){(function(f){f(function(){function b(){return{state:"pending"}}function d(a){return{state:"rejected",reason:a}}function a(a){return{state:"fulfilled",value:a}}return{pending:b,fulfilled:a,rejected:d,inspect:function(c){var f=c.state();return 0===f?b():0<f?a(c.value):d(c.value)}}})})(function(f){k.exports=f()})},{}],74:[function(g,k,h){(function(f){f(function(b){function d(a,b,c,e){var d=u.resolve(a);return 2>arguments.length?d:d.then(b,c,e)}function a(a){return function(){for(var b= 0,c=arguments.length,e=Array(c);b<c;++b)e[b]=arguments[b];return r(a,this,e)}}function c(a){for(var b=0,c=arguments.length-1,e=Array(c);b<c;++b)e[b]=arguments[b+1];return r(a,this,e)}function f(){function a(b){e._handler.resolve(b)}function b(a){e._handler.reject(a)}function c(a){e._handler.notify(a)}var e=u._defer();this.promise=e;this.resolve=a;this.reject=b;this.notify=c;this.resolver={resolve:a,reject:b,notify:c}}var e=b("./lib/decorators/timed"),g=b("./lib/decorators/array"),h=b("./lib/decorators/flow"), k=b("./lib/decorators/fold"),q=b("./lib/decorators/inspect"),v=b("./lib/decorators/iterate"),p=b("./lib/decorators/progress"),w=b("./lib/decorators/with"),s=b("./lib/decorators/unhandledRejection"),z=b("./lib/TimeoutError"),u=[g,h,k,v,p,q,w,e,s].reduce(function(a,b){return b(a)},b("./lib/Promise")),r=b("./lib/apply")(u);d.promise=function(a){return new u(a)};d.resolve=u.resolve;d.reject=u.reject;d.lift=a;d["try"]=c;d.attempt=c;d.iterate=u.iterate;d.unfold=u.unfold;d.join=function(){return u.all(arguments)}; d.all=function(a){return d(a,u.all)};d.settle=function(a){return d(a,u.settle)};d.any=a(u.any);d.some=a(u.some);d.race=a(u.race);d.map=function(a,b){return d(a,function(a){return u.map(a,b)})};d.filter=function(a,b){return d(a,function(a){return u.filter(a,b)})};d.reduce=a(u.reduce);d.reduceRight=a(u.reduceRight);d.isPromiseLike=function(a){return a&&"function"===typeof a.then};d.Promise=u;d.defer=function(){return new f};d.TimeoutError=z;return d})})(function(f){k.exports=f(g)})},{"./lib/Promise":57, "./lib/TimeoutError":59,"./lib/apply":60,"./lib/decorators/array":61,"./lib/decorators/flow":62,"./lib/decorators/fold":63,"./lib/decorators/inspect":64,"./lib/decorators/iterate":65,"./lib/decorators/progress":66,"./lib/decorators/timed":67,"./lib/decorators/unhandledRejection":68,"./lib/decorators/with":69}],75:[function(g,k,h){(function(f){f(function(){return{findProperties:function d(a,c,f){"object"===typeof a&&null!==a&&(c in a&&f(a[c],a,c),Object.keys(a).forEach(function(e){d(a[e],c,f)}))}}})})(function(f){k.exports= f(g)})},{}],76:[function(g,k,h){(function(f){f(function(b){var d;d=b("when");return function(a){var b,f,e,g,h;b=d.defer();f=!1;e=b.resolver;g=b.promise;h=g.then;g.then=function(){f||(f=!0,d.attempt(a).then(e.resolve,e.reject));return h.apply(g,arguments)};return g}})})(function(f){k.exports=f(g)})},{when:74}],77:[function(g,k,h){(function(f){f(function(){var b={};return function(d){var a,c,f,e;d||(d={});a=1;for(c=arguments.length;a<c;a+=1)for(e in f=arguments[a],f)e in d&&(d[e]===f[e]||e in b&&b[e]=== f[e])||(d[e]=f[e]);return d}})})(function(f){k.exports=f(g)})},{}],78:[function(g,k,h){(function(f){f(function(){return function(b){return b.toLowerCase().split("-").map(function(b){return b.charAt(0).toUpperCase()+b.slice(1)}).join("-")}})})(function(f){k.exports=f(g)})},{}],79:[function(g,k,h){(function(f){f(function(b){function d(a,b){return a.then(function(a){return a&&a[b]},function(a){return q.reject(a&&a[b])})}function a(){return d(this,"entity")}function c(){return d(d(this,"status"),"code")} function f(){return d(this,"headers")}function e(a){a=v(a);return d(this.headers(),a)}function g(a){a=[].concat(a);return h(q.reduce(a,function(a,b){"string"===typeof b&&(b={rel:b});if("function"!==typeof a.entity.clientFor)throw Error("Hypermedia response expected");return a.entity.clientFor(b.rel)({params:b.params})},this))}function h(b){b.status=c;b.headers=f;b.header=e;b.entity=a;b.follow=g;return b}function k(){return h(q.apply(q,arguments))}var q=b("when"),v=b("./normalizeHeaderName");k.make= h;k.reject=function(a){return h(q.reject(a))};k.promise=function(a){return h(q.promise(a))};return k})})(function(f){k.exports=f(g)})},{"./normalizeHeaderName":78,when:74}],80:[function(g,k,h){(function(f){f(function(){function b(a,b){if("string"!==typeof a)throw Error("String required for URL encoding");return a.split("").map(function(a){if(b.hasOwnProperty(a))return a;var c=a.charCodeAt(0);return 127>=c?"%"+c.toString(16).toUpperCase():encodeURIComponent(a).toUpperCase()}).join("")}function d(c){c= c||a.unreserved;return function(a){return b(a,c)}}var a;a=function(){var a={alpha:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",digit:"0123456789",genDelims:":/?#[]@",subDelims:"!$&'()*+,;="};a.reserved=a.genDelims+a.subDelims;a.unreserved=a.alpha+a.digit+"-._~";a.url=a.reserved+a.unreserved;a.scheme=a.alpha+a.digit+"+-.";a.userinfo=a.unreserved+a.subDelims+":";a.host=a.unreserved+a.subDelims;a.port=a.digit;a.pchar=a.unreserved+a.subDelims+":@";a.segment=a.pchar;a.path=a.segment+"/";a.query= a.pchar+"/?";a.fragment=a.pchar+"/?";return Object.keys(a).reduce(function(b,e){b[e]=a[e].split("").reduce(function(a,b){a[b]=!0;return a},{});return b},{})}();return{decode:function(a){return decodeURIComponent(a)},encode:d(),encodeURL:d(a.url),encodeScheme:d(a.scheme),encodeUserInfo:d(a.userinfo),encodeHost:d(a.host),encodePort:d(a.port),encodePathSegment:d(a.segment),encodePath:d(a.path),encodeQuery:d(a.query),encodeFragment:d(a.fragment)}})})(function(f){k.exports=f(g)})},{}],81:[function(g,k, h){(function(f){f(function(b){function d(b,c,d){return c.split(",").reduce(function(c,g){var h,k,n;k=h=void 0;"*"===g.slice(-1)&&(g=g.slice(0,-1),h=!0);f.test(g)&&(k=f.exec(g),g=k[1],k=parseInt(k[2]));g=a.decode(g);n=d[g];if(void 0===n||null===n)return c;"string"===typeof n?(k&&(n=n.slice(0,k)),c+=c.length?b.separator:b.first,b.named&&(c+=b.encoder(g),c+=n.length?"=":b.empty),c+=b.encoder(n)):c=Array.isArray(n)?c+n.reduce(function(a,c){a.length?(a+=h?b.separator:",",b.named&&h&&(a+=b.encoder(g),a+= c.length?"=":b.empty)):(a+=b.first,b.named&&(a+=b.encoder(g),a+=c.length?"=":b.empty));return a+=b.encoder(c)},""):c+Object.keys(n).reduce(function(a,c){a.length?a+=h?b.separator:",":(a+=b.first,b.named&&!h&&(a+=b.encoder(g),a+=n[c].length?"=":b.empty));a+=b.encoder(c);a+=h?"=":",";return a+=b.encoder(n[c])},"");return c},"")}var a,c,f;a=b("./uriEncoder");f=/^([^:]*):([0-9]+)$/;c={"":{first:"",separator:",",named:!1,empty:"",encoder:a.encode},"+":{first:"",separator:",",named:!1,empty:"",encoder:a.encodeURL}, "#":{first:"#",separator:",",named:!1,empty:"",encoder:a.encodeURL},".":{first:".",separator:".",named:!1,empty:"",encoder:a.encode},"/":{first:"/",separator:"/",named:!1,empty:"",encoder:a.encode},";":{first:";",separator:";",named:!0,empty:"",encoder:a.encode},"?":{first:"?",separator:"&",named:!0,empty:"=",encoder:a.encode},"&":{first:"&",separator:"&",named:!0,empty:"=",encoder:a.encode},"=":{reserved:!0},",":{reserved:!0},"!":{reserved:!0},"@":{reserved:!0},"|":{reserved:!0}};return{expand:function(a, b){var f,g,h;h="";for(g=0;;){f=a.indexOf("{",g);if(-1===f){h+=a.slice(g);break}h+=a.slice(g,f);g=a.indexOf("}",f)+1;f=a.slice(f+1,g-1);var k=b,m=void 0;(m=c[f.slice(0,1)])?f=f.slice(1):m=c[""];if(m.reserved)throw Error("Reserved expression operations are not supported");f=d(m,f,k);h+=f}return h}}})})(function(f){k.exports=f(g)})},{"./uriEncoder":80}],82:[function(g,k,h){function f(){if(!a){a=!0;for(var b,f=d.length;f;){b=d;d=[];for(var e=-1;++e<f;)b[e]();f=d.length}a=!1}}function b(){}g=k.exports= {};var d=[],a=!1;g.nextTick=function(b){d.push(b);a||setTimeout(f,0)};g.title="browser";g.browser=!0;g.env={};g.argv=[];g.version="";g.versions={};g.on=b;g.addListener=b;g.once=b;g.off=b;g.removeListener=b;g.removeAllListeners=b;g.emit=b;g.binding=function(a){throw Error("process.binding is not supported");};g.cwd=function(){return"/"};g.chdir=function(a){throw Error("process.chdir is not supported");};g.umask=function(){return 0}},{}]},{},[1])(1)});
common/containers/About.js
kherrick/postpress
import { connect } from 'react-redux' import { isObjectEmpty } from '../utilities/general' import { PageTitle } from '../components/Styled/Headings' import PropTypes from 'prop-types' import querystring from 'querystring' import React from 'react' const About = ({ branding }) => { const query = querystring.parse(branding.query) const isQueryEmpty = isObjectEmpty(query) const Author = query.author === 'true' ? <div>{`Author information...`}</div> : <div /> return ( <div> <PageTitle>{`About`}</PageTitle> {isQueryEmpty ? <div /> : <div>{Author}</div>} <p>{`About content...`}</p> </div> ) } About.propTypes = { branding: PropTypes.shape({ query: PropTypes.string.isRequired, tagline: PropTypes.string.isRequired, title: PropTypes.string.isRequired, url: PropTypes.string.isRequired }).isRequired } const mapStateToProps = ({ branding }) => ({ branding }) export default connect(mapStateToProps)(About)
src/views/pages/login.js
bugra9/adminjs
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { hashHistory } from 'react-router'; import { Segment, Grid, Header, Image, Form, Input, Button, Dimmer, Message, Progress, Container } from 'semantic-ui-react'; import { login } from '../../actions/tree'; class Login extends Component { componentWillReceiveProps(nextProps) { if(nextProps.isLogin) { window.login = true; hashHistory.push(this.props.nextPath); } } handleSubmit = (e, { formData }) => { e.preventDefault(); let nextPath = ''; if(this.props && this.props.location && this.props.location.state && this.props.location.state.nextPath) nextPath = this.props.location.state.nextPath; else nextPath = "/"; this.props.login(formData.token, nextPath); } render() { return ( <Segment color="blue" inverted basic> <Grid verticalAlign="middle" textAlign="center" style={{height: "100vh"}}> <Grid.Column style={{width: 450}}> <Header as="h2" inverted image size="medium"> <Image src="https://jekyllrb.com/img/logo-2x.png" size="large" /> <Header.Content> AdminJS </Header.Content> </Header> <Form size="large" onSubmit={this.handleSubmit}> <Segment stacked> <Message hidden={ !this.props.hasErrored } negative icon="x" header={ this.props.error } size="small" /> <Form.Field> <Input icon="lock" iconPosition="left" name="token" placeholder="Kişisel Erişim Anahtarı" /> </Form.Field> <Button color="blue" size="large" fluid type="submit">Giriş</Button> </Segment> </Form> </Grid.Column> </Grid> <Dimmer active={ this.props.isLoading }> <Container> <Progress percent={ this.props.progressPercent } inverted color="red" label indicating> { this.props.progressMessage } </Progress> </Container> </Dimmer> </Segment> ); } } const mapStateToProps = (state) => ({ isLoading: state.tree.isLoading, isLogin: state.tree.isLogin, hasErrored: state.tree.hasErrored, error: state.tree.error, progressMessage: state.tree.progressMessage, progressPercent: state.tree.progressPercent, tree: state.tree.tree, message: state.tree.lastCommitMessage, nextPath: state.tree.nextPath }); const mapDispatchToProps = (dispatch) => { return { login: (token, nextPath) => dispatch(login(token, nextPath)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(Login);
redpen-server/src/main/webapp/js/jquery-1.11.0.min.js
jmoriya/redpen
/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",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!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));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||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},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:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}: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){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=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&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),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=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="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(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 mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.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},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.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=db.selectors={cacheLength:50,createPseudo:fb,match:V,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(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===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]||db.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]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(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(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!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&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&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]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)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&&(t&&((l[s]||(l[s]={}))[a]=[u,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()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?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===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.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 X.test(a.nodeName)},input:function(a){return W.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:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(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]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[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?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;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=[u,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[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(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 sb(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 tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(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?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(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 n.inArray(a,b)>=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=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},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=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.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:z,!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}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,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))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))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?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):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 E(a,b){do a=a[b];while(a&&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 E(a,"nextSibling")},prev:function(a){return E(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 n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document: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&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){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&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},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 I;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){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(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){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f }}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),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=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(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 n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,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=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=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},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.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=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=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(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.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=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(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,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.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=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(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=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},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||a.getPreventDefault&&a.getPreventDefault())?bb:cb):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:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},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}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.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=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(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(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.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=cb),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}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(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 yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(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=xb(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(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(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(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(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(vb(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,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.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(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}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=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.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+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),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 Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(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}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(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+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},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;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.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"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[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+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(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 Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,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=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.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}}},$b.propHooks.scrollTop=$b.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=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.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 gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(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++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(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 lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),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:_b||gc(),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(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,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(lc,{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],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.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(V).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=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.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=n._data(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(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("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=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=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(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=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,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\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(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b: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||(l.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--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),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}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(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===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),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(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),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){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){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,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){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(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),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 wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;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 Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(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:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,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?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),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(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(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.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),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){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var 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.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return 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||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(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)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},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")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.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(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}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",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.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(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.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,ad.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||z;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 cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}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)&&n.inArray("auto",[f,i])>-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={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.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 W(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 fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
src/components/Tag/Tag-story.js
joshblack/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import { storiesOf } from '@storybook/react'; import { withKnobs, select, text, boolean } from '@storybook/addon-knobs'; import Tag, { types as typesList } from '../Tag'; import TagSkeleton from '../Tag/Tag.Skeleton'; const types = typesList.reduce( (o, type) => ({ ...o, [`${type} (${type})`]: type, }), {} ); storiesOf('Tag', module) .addDecorator(withKnobs) .add( 'Default', () => ( <Tag className="some-class" type={select('Tag type (type)', types, 'red')} disabled={boolean('Disabled (disabled)', false)}> {text('Content (children)', 'This is not a tag')} </Tag> ), { info: { text: ` Tags are used for items that need to be labeled, categorized, or organized using keywords that describe them. The example below shows how the Tag component can be used. Each type has a default message describing the type, but a custom message can also be applied. `, }, } ) .add( 'skeleton', () => ( <div> <TagSkeleton /> </div> ), { info: { text: ` Placeholder skeleton state to use when content is loading. `, }, } );
src/components/Game/index.js
angeloocana/tic-tac-toe-ai
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { newGame, selectPosition } from '../../redux/actions'; import NewGameBtn from './NewGameBtn'; import styled from 'styled-components'; import Canvas from './Canvas'; import AiIcon from 'react-icons/lib/md/phone-android'; import UserIcon from 'react-icons/lib/md/person'; import { FormattedMessage } from 'react-intl'; const Section = styled.section` display: flex; flex-direction: column; margin: auto; width: 100%; max-width: 20rem; text-align: center; `; const Score = styled.div` padding-bottom: 1rem; svg { font-size: ${({ theme }) => theme.scale(1)}; } span, svg { vertical-align: middle; display: inline-block; } .points { font-size: ${({ theme }) => theme.scale(3)}; font-weight: bold; padding: 0 ${({ theme }) => theme.scale(-4)}; top: 0.1rem; position: relative; } `; const getWinLostMsg = (game, forAi) => { if (!game.ended) { return null; } const id = game.winners && game.isAiTurn !== forAi ? 'iWon' : 'iLost'; return (<FormattedMessage id={id} />); }; class Game extends React.PureComponent { render() { const { game, selectPosition } = this.props; return ( <Section> <Score> {getWinLostMsg(game, false)} <UserIcon /> <span className="points">{game.score.human}</span> <span>x</span> <span className="points">{game.score.ai}</span> <AiIcon /> {game.isAiTurn && !game.ended ? (<FormattedMessage id="thinking" />) : null} {getWinLostMsg(game, true)} </Score> <Canvas game={game} selectPosition={selectPosition} /> <div> <NewGameBtn newGame={this.props.newGame} /> </div> </Section> ); } }; Game.propTypes = { game: PropTypes.object.isRequired, selectPosition: PropTypes.func.isRequired, newGame: PropTypes.func.isRequired }; const mapStateToProps = state => { return { game: state.game }; }; const mapDispatchToProps = dispatch => { return { newGame: type => { dispatch(newGame(type)); }, selectPosition: index => { dispatch(selectPosition(index)); } }; }; export default connect( mapStateToProps, mapDispatchToProps )(Game);
src/components/Feedback/Feedback.js
BlackAngus/BVPHackathon
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Feedback.css'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback extends Component { render() { return ( <div className="Feedback"> <div className="Feedback-container"> <a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className="Feedback-spacer">|</span> <a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;
packages/icons/src/md/maps/BeenHere.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdBeenHere(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M38 2c2.21 0 4 1.79 4 4l-.02 25.87c0 1.38-.7 2.6-1.76 3.32L23.99 46 7.76 35.19A4.011 4.011 0 0 1 6 31.87L6.02 6c0-2.21 1.77-4 3.98-4h28zM20 32l18-18-2.83-2.83L20 26.34l-7.17-7.17L10 22l10 10z" /> </IconBase> ); } export default MdBeenHere;
ngrinder-recorder/js/lib/jquery-1.11.3.min.js
chengaomin/ngrinder
/*! jQuery v1.11.3 | (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="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+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);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(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=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){ return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.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):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m});
assets/js/jquery.min.js
jaxkodex/blog
/*! jQuery v1.11.3 | (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="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+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);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(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=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){ return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.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):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m});
node_modules/reactify/node_modules/react-tools/src/browser/server/ServerReactRootIndex.js
chi-sea-lions-2015/house-rules
/** * 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 ServerReactRootIndex * @typechecks */ 'use strict'; /** * Size of the reactRoot ID space. We generate random numbers for React root * IDs and if there's a collision the events and DOM update system will * get confused. In the future we need a way to generate GUIDs but for * now this will work on a smaller scale. */ var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53); var ServerReactRootIndex = { createReactRootIndex: function() { return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX); } }; module.exports = ServerReactRootIndex;
js/react-ssr/src/ssr/index.js
Icokie/study
import React from 'react'; import ReactDOMServer from 'react-dom/server'; import {App} from '../app/containers/App'; function renderComponent(data) { return new Promise((resolve, reject) => { let component = ReactDOMServer.renderToString(<App data={data}/>); resolve(component); }); } export {renderComponent};
web-app/src/shared/components/Table/AllLabelHeadingCell.js
crypticism/FF
import React from 'react'; export default function AllLabelHeadingCell() { return ( <span>All</span> ); }
src/svg-icons/hardware/devices-other.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareDevicesOther = (props) => ( <SvgIcon {...props}> <path d="M3 6h18V4H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V6zm10 6H9v1.78c-.61.55-1 1.33-1 2.22s.39 1.67 1 2.22V20h4v-1.78c.61-.55 1-1.34 1-2.22s-.39-1.67-1-2.22V12zm-2 5.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM22 8h-6c-.5 0-1 .5-1 1v10c0 .5.5 1 1 1h6c.5 0 1-.5 1-1V9c0-.5-.5-1-1-1zm-1 10h-4v-8h4v8z"/> </SvgIcon> ); HardwareDevicesOther = pure(HardwareDevicesOther); HardwareDevicesOther.displayName = 'HardwareDevicesOther'; HardwareDevicesOther.muiName = 'SvgIcon'; export default HardwareDevicesOther;
app/components/templates_page.js
d-reinhold/mass-spec-solver
const React = require('react'); const {Icon} = require('pui-react-iconography'); const {Tooltip} = require('pui-react-tooltip'); const {OverlayTrigger} = require('pui-react-overlay-trigger'); const Actions = require('runtime/actions'); const exampleTemplates = { 'example - (O)2(H)7(C)11': {page:'Solve', totalMass:'171.0473', totalCharge:'', maxError:'0.01', rows:[{id:134, coef:'N', range:{min:0, max:'3'}, charge:0, weight:'14.0030740'}, {id:725, coef:'O', range:{min:0, max:'10'}, charge:0, weight:'15.9949150'}, {id:832, coef:'H', range:{min:0, max:'10'}, charge:0, weight:'1.00782500'}, {id:16, coef:'C', range:{min:0, max:'15'}, charge:0, weight:'12.0000000'}]}, 'example - (Na)1(O)4(OAc)4(Co)4(Py)4': {page:'Solve', totalMass:'874.9324', totalCharge:'1', maxError:'0.02', rows:[{id:723, coef:'Cl', range:{min:0, max:'1'}, charge:-1, weight:'34.9694016'}, {id:40, coef:'NH4', range:{min:0, max:'2'}, charge:1, weight:'18.0338254'}, {id:896, coef:'OH2', range:{min:0, max:'2'}, charge:0, weight:'18.0105650'}, {id:228, coef:'CH3CN', range:{min:0, max:'2'}, charge:0, weight:'41.0265490'}, {id:474, coef:'Na', range:{min:0, max:'2'}, charge:1, weight:'22.9892214'}, {id:897, coef:'H', range:{min:0, max:'2'}, charge:1, weight:'1.00727640'}, {id:338, coef:'O', range:{min:0, max:5}, charge:-2, weight:'15.9960122'}, {id:503, coef:'OAc', range:{min:0, max:5}, charge:-1, weight:'59.0138486'}, {id:779, coef:'Co', range:{min:0, max:5}, charge:3, weight:'58.9315522'}, {id:16, coef:'Py', range:{min:0, max:5}, charge:0, weight:'79.0422000'}]} }; class TemplatesPage extends React.Component { render() { return ( <div className="templates-page"> <h3>Templates</h3> <ul className="list-unstyled"> { Object.entries(exampleTemplates).concat(Object.entries(this.props.templates)).map(([name, data]) => ( <li key={name} className="row"> <span className="col-md-22"><a onClick={Actions.resetState.bind(null, {...data, ...{page: 'Solve', activeTemplateName: name}})}>{name}</a></span> {!Object.keys(exampleTemplates).includes(name) && <a href="javascript:void(0)" className="action-icon col-xs-2" onClick={Actions.removeTemplate.bind(null, name)}> <OverlayTrigger placement="top" overlay={<Tooltip>Delete this Template</Tooltip>}> <Icon name="close" size="h3"/> </OverlayTrigger> </a> } </li> )) } </ul> <p> You can save mass spec problems as templates to reuse later. This allows you to solve similar problems without having to fill in the same fragments over and over. You can create templates by clicking 'save as template' on the <a onClick={Actions.resetState.bind(null, {page: 'Solve'})}>Solve</a> page. </p> <p> After saving, your new template will be listed on the <a onClick={Actions.resetState.bind(null, {page: 'Templates'})}>Templates</a> page. Click on a template to be taken back to the <a onClick={Actions.resetState.bind(null, {page: 'Solve'})}>Solve</a> page with the desired fragments filled in. From there, you can modify fields and properties to test out new ideas. To reset the form to its original values, return to the <a onClick={Actions.resetState.bind(null, {page: 'Templates'})}>Templates</a> page and click the template name. If you want to update the template with the new values, simply click 'save as template'. </p> </div> ); } } module.exports = TemplatesPage;
src/containers/thread/CperMapThread/GeoMap.js
mydearxym/mastani
import React from 'react' import ReactResizeDetector from 'react-resize-detector' import uid from '@/utils/uid' import { buildLog } from '@/utils/logger' import fetchGeoData from './geo_data' import { MapWrapper, RealMap, NoticeWrapper, TheLink } from './styles' import G2 from 'g2' /* eslint-disable-next-line */ const log = buildLog('c:LocationMap') // see example at https://antv.vision/old-site/g2/demo/10-map/map-projection.html class LocationMap extends React.Component { constructor(props) { super(props) this.chart = null this.chartId = `id-${uid.gen()}` const { curTheme } = props this.curTheme = curTheme } componentDidMount() { try { this.initG2() } catch (e) { // TODO: tell toast log('G2 is not load', e) } } shouldComponentUpdate(nextProps) { if (nextProps.curTheme !== this.curTheme) { this.curTheme = nextProps.curTheme this.chart.destroy() setTimeout(() => { this.initG2() }, 500) setTimeout(() => { const curWidth = document.getElementById(this.chartId).offsetWidth this.onResize(curWidth) }, 1500) return false } return true } onResize(width) { const newWidth = Math.ceil(width) const height = Math.ceil(newWidth * 0.625) if (this.chart) this.chart.changeSize(newWidth, height) } /* eslint-disable no-undef */ configG2() { G2.track(false) this.chart.forceFit() // animate it's to0 "dragy" this.chart.animate(false) this.chart.legend(false) this.chart.tooltip({ title: null }) this.chart.coord('map', { projection: 'albers', basic: [110, 0, 25, 47], // 指定投影方法的基本参数,[λ0, φ0, φ1, φ2] 分别表示中央经度、坐标起始纬度、第一标准纬度、第二标准纬度 max: [16.573, -13.613], // 指定投影后最大的坐标点 min: [-27.187, -49.739], // 指定投影后最小的坐标点 }) } initG2() { const { theme } = this.props const { geoMap: { oceanColor, regionBg, restRegionBg, borderStroke, markerBg, markerShadow, }, } = theme const { Stat } = G2 fetchGeoData() .then((mapData) => { const map = [] const { features } = mapData for (let i = 0; i < features.length; i += 1) { const { name } = features[i].properties map.push({ name }) } this.chart = new G2.Chart({ id: this.chartId, height: 500, plotCfg: { margin: [10, 105], border: { fill: oceanColor, }, }, }) this.configG2() const bgView = this.chart.createView() bgView.source(map) bgView.tooltip(false) bgView.axis(false) bgView .polygon() .position(Stat.map.region('name', mapData)) .color('name', (val) => { if (val === 'China') { return regionBg } return restRegionBg }) .style({ stroke: borderStroke, lineWidth: 1, }) const pointView = this.chart.createView() const { markers } = this.props pointView.source(markers, { value: { alias: '人数' }, city: { alias: '城市' }, }) pointView .point() .position(Stat.map.location('long*lant')) .size('value', 12, 1) .color('value', () => markerBg) .tooltip('city*value') .shape('value', () => 'circle') .style({ shadowBlur: 5, shadowColor: markerShadow, }) this.chart.render() }) .catch((ex) => log('parsing failed', ex)) } /* eslint-enable no-undef */ render() { return ( <MapWrapper> <ReactResizeDetector handleWidth refreshMode="debounce" refreshRate={500} skipOnMount={false} querySelector={`#${this.chartId}`} onResize={(width) => this.onResize(width)} /> <RealMap id={this.chartId} /> <NoticeWrapper> 地理坐标信息由注册用户 IP 地址根据第三方地图服务商获得(城市定位仅限国内)。由定位失败或科学上网等因素导致的误差后期会专门提供手动矫正措施。全球范围内的访问数据可 <TheLink href="https://plausible.io/coderplanets.com/countries" target="_blank" > 参考这里 </TheLink> (台湾地区单独统计, <TheLink href="https://en.wikipedia.org/wiki/ISO_3166-2:TW" target="_blank" > 非技术原因 </TheLink> ,本站不讨论政治)。 </NoticeWrapper> </MapWrapper> ) } } export default LocationMap /* fetch('http://antvis.github.io/static/data/china-pm.json') .then(response => response.json()) .then(data => {}) */
node_modules/react-router/es6/IndexLink.js
geng890518/editor-ui
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; }; import React from 'react'; import Link from './Link'; /** * An <IndexLink> is used to link to an <IndexRoute>. */ var IndexLink = React.createClass({ displayName: 'IndexLink', render: function render() { return React.createElement(Link, _extends({}, this.props, { onlyActiveOnIndex: true })); } }); export default IndexLink;
node_modules/accord/lib/index.js
AgbodjogbeYves-alain/ProjetWeb_Kg
// Generated by CoffeeScript 1.12.1 (function() { var abstract_mapper, adapter_to_name, fs, get_version, glob, indx, match_version_to_adapter, name_to_adapter, path, resolve, resolve_engine_path, semver, supports; path = require('path'); fs = require('fs'); glob = require('glob'); indx = require('indx'); resolve = require('resolve'); semver = require('semver'); exports.supports = supports = function(name) { name = adapter_to_name(name); return !!glob.sync("" + (path.join(__dirname, 'adapters', name))).length; }; exports.load = function(name, custom_path, engine_name) { var adapter_name, engine_path, version; name = adapter_to_name(name); engine_path = resolve_engine_path(name, custom_path); version = get_version(engine_path); adapter_name = match_version_to_adapter(name, version); if (!adapter_name) { throw new Error(name + " version " + version + " is not currently supported"); } return new (require(adapter_name))(engine_name, engine_path); }; exports.all = function() { return indx(path.join(__dirname, 'adapters')); }; exports.abstract_mapper = abstract_mapper = function(name, direction) { var name_maps, res; name_maps = [['markdown', 'marked'], ['minify-js', 'uglify-js'], ['minify-css', 'clean-css'], ['minify-html', 'html-minifier'], ['mustache', 'hogan.js'], ['scss', 'node-sass'], ['haml', 'hamljs'], ['escape-html', 'he'], ['jsx', 'react-tools'], ['cjsx', 'coffee-react-transform'], ['babel', 'babel-core'], ['typescript', 'typescript-compiler']]; res = null; name_maps.forEach(function(n) { if (direction === 'left' && n[0] === name) { res = n[1]; } if (direction === 'right' && n[1] === name) { return res = n[0]; } }); return res || name; }; exports.adapter_to_name = adapter_to_name = function(name) { return abstract_mapper(name, 'right'); }; exports.name_to_adapter = name_to_adapter = function(name) { return abstract_mapper(name, 'left'); }; resolve_engine_path = function(name, custom_path) { var filepath; filepath = custom_path != null ? resolve.sync(name_to_adapter(name), { basedir: custom_path }) : require.resolve(name_to_adapter(name)); while (true) { if (filepath === '/') { throw new Error("cannot resolve root of node module " + name); } filepath = path.dirname(filepath); if (fs.existsSync(path.join(filepath, 'package.json'))) { return filepath; } } }; get_version = function(engine_path) { var err; try { return require(engine_path + '/package.json').version; } catch (error) { err = error; } }; match_version_to_adapter = function(name, version) { var adapter, adapters, i, len; adapters = fs.readdirSync(path.join(__dirname, 'adapters', name)); for (i = 0, len = adapters.length; i < len; i++) { adapter = adapters[i]; adapter = adapter.replace(/\.(?:js|coffee)$/, ''); if (semver.satisfies(version, adapter)) { return path.join(__dirname, 'adapters', name, adapter); } } }; }).call(this);
Magistrate/client/components/plate/plateRow.js
Pondidum/Magistrate
import React from 'react' import PlateChildren from './PlateChildren' const PlateRow = ({ title, onClick, onCross, tileSize, additions, children }) => ( <li className="col-md-12 tile"> <div className="row panel panel-default"> <div className="panel-body"> <div className="col-sm-3"><a href="#" onClick={onClick}>{title}</a></div> <div className="col-sm-8"><PlateChildren tileSize={tileSize} children={children} /></div> <div className="col-sm-1"> <a href="#" onClick={onCross}> <span className="glyphicon glyphicon-remove-circle"></span> </a> </div> </div> </div> {additions} </li> ) export default PlateRow
build/content.js
tkorakas/gmail-lists
!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=26)}([function(e,t,n){"use strict";function r(e){return function(){return e}}var o=function(){};o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},e.exports=o},function(e,t,n){"use strict";e.exports=n(23)},function(e,t,n){"use strict";var r=function(){},o=n(22),a={};r=function(e){var t="Warning: "+e;"undefined"!=typeof console&&console.error(t);try{throw new Error(t)}catch(e){}},e.exports=function(e,t,n,i,l){for(var u in e)if(e.hasOwnProperty(u)){var s;try{if("function"!=typeof e[u]){var c=Error((i||"React class")+": "+n+" type `"+u+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[u]+"`.");throw c.name="Invariant Violation",c}s=e[u](t,u,i,n,null,o)}catch(e){s=e}if(!s||s instanceof Error||r((i||"React class")+": type specification of "+n+" `"+u+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof s+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."),s instanceof Error&&!(s.message in a)){a[s.message]=!0;var d=l?l():"";r("Failed "+n+" type: "+s.message+(null!=d?d:""))}}}},function(e,t,n){"use strict";var r=n(0);r=function(e,t){if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(0!==t.indexOf("Failed Composite propType: ")&&!e){for(var n=arguments.length,r=Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];(function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var o=0,a="Warning: "+e.replace(/%s/g,function(){return n[o++]});"undefined"!=typeof console&&console.error(a);try{throw new Error(a)}catch(e){}}).apply(void 0,[t].concat(r))}},e.exports=r},function(e,t,n){"use strict";var r={};Object.freeze(r),e.exports=r},function(e,t,n){"use strict"; /* object-assign (c) Sindre Sorhus @license MIT */var r=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var n,i,l=function(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),u=1;u<arguments.length;u++){for(var s in n=Object(arguments[u]))o.call(n,s)&&(l[s]=n[s]);if(r){i=r(n);for(var c=0;c<i.length;c++)a.call(n,i[c])&&(l[i[c]]=n[i[c]])}}return l}},function(e,t,n){"use strict";var r=function(e){};r=function(e){if(void 0===e)throw new Error("invariant requires an error message argument")},e.exports=function(e,t,n,o,a,i,l,u){if(r(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,o,a,i,l,u],d=0;(s=new Error(t.replace(/%s/g,function(){return c[d++]}))).name="Invariant Violation"}throw s.framesToPop=1,s}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default="sdk_gmail-lists_9f6f1e5451"},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(e=e.replace(/ /g,"")).replace(/[^a-zA-Z1-9]/g,"").toLowerCase()}},function(e,t,n){var r,o,a;o=[e,t],void 0===(a="function"==typeof(r=function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=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}}(),r=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var o="",a=void 0,i=void 0;this.escapeRegExp=function(e){return e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},this.parseInt=function(e,t){return/^(\-|\+)?([0-9]+|Infinity)$/.test(e)?parseInt(e,t):NaN},this.seps="cfhistuCFHISTU",this.minLength=parseInt(n,10)>0?n:0,this.salt="string"==typeof t?t:"","string"==typeof r&&(this.alphabet=r);for(var l=0;l!==this.alphabet.length;l++)-1===o.indexOf(this.alphabet.charAt(l))&&(o+=this.alphabet.charAt(l));if(this.alphabet=o,this.alphabet.length<16)throw"error: alphabet must contain at least X unique characters".replace("X",16);if(-1!==this.alphabet.search(" "))throw"error: alphabet cannot contain spaces";for(var u=0;u!==this.seps.length;u++){var s=this.alphabet.indexOf(this.seps.charAt(u));-1===s?this.seps=this.seps.substr(0,u)+" "+this.seps.substr(u+1):this.alphabet=this.alphabet.substr(0,s)+" "+this.alphabet.substr(s+1)}this.alphabet=this.alphabet.replace(/ /g,""),this.seps=this.seps.replace(/ /g,""),this.seps=this._shuffle(this.seps,this.salt),(!this.seps.length||this.alphabet.length/this.seps.length>3.5)&&(a=Math.ceil(this.alphabet.length/3.5))>this.seps.length&&(i=a-this.seps.length,this.seps+=this.alphabet.substr(0,i),this.alphabet=this.alphabet.substr(i)),this.alphabet=this._shuffle(this.alphabet,this.salt);var c=Math.ceil(this.alphabet.length/12);this.alphabet.length<3?(this.guards=this.seps.substr(0,c),this.seps=this.seps.substr(c)):(this.guards=this.alphabet.substr(0,c),this.alphabet=this.alphabet.substr(c))}return n(e,[{key:"encode",value:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];if(!t.length)return"";if(t[0]&&t[0].constructor===Array&&!(t=t[0]).length)return"";for(var r=0;r!==t.length;r++)if(t[r]=this.parseInt(t[r],10),!(t[r]>=0))return"";return this._encode(t)}},{key:"decode",value:function(e){return e&&e.length&&"string"==typeof e?this._decode(e,this.alphabet):[]}},{key:"encodeHex",value:function(e){if(e=e.toString(),!/^[0-9a-fA-F]+$/.test(e))return"";for(var t=e.match(/[\w\W]{1,12}/g),n=0;n!==t.length;n++)t[n]=parseInt("1"+t[n],16);return this.encode.apply(this,t)}},{key:"decodeHex",value:function(e){for(var t=[],n=this.decode(e),r=0;r!==n.length;r++)t+=n[r].toString(16).substr(1);return t}},{key:"_encode",value:function(e){for(var t=void 0,n=this.alphabet,r=0,o=0;o!==e.length;o++)r+=e[o]%(o+100);for(var a=t=n.charAt(r%n.length),i=0;i!==e.length;i++){var l=e[i],u=a+this.salt+n;n=this._shuffle(n,u.substr(0,n.length));var s=this._toAlphabet(l,n);if(t+=s,i+1<e.length){var c=(l%=s.charCodeAt(0)+i)%this.seps.length;t+=this.seps.charAt(c)}}if(t.length<this.minLength){var d=(r+t[0].charCodeAt(0))%this.guards.length,f=this.guards[d];(t=f+t).length<this.minLength&&(d=(r+t[2].charCodeAt(0))%this.guards.length,f=this.guards[d],t+=f)}for(var p=parseInt(n.length/2,10);t.length<this.minLength;){n=this._shuffle(n,n);var h=(t=n.substr(p)+t+n.substr(0,p)).length-this.minLength;h>0&&(t=t.substr(h/2,this.minLength))}return t}},{key:"_decode",value:function(e,t){var n=[],r=0,o=new RegExp("["+this.escapeRegExp(this.guards)+"]","g"),a=e.replace(o," "),i=a.split(" ");if(3!==i.length&&2!==i.length||(r=1),void 0!==(a=i[r])[0]){var l=a[0];a=a.substr(1),o=new RegExp("["+this.escapeRegExp(this.seps)+"]","g"),a=a.replace(o," "),i=a.split(" ");for(var u=0;u!==i.length;u++){var s=i[u],c=l+this.salt+t;t=this._shuffle(t,c.substr(0,t.length)),n.push(this._fromAlphabet(s,t))}this.encode(n)!==e&&(n=[])}return n}},{key:"_shuffle",value:function(e,t){var n=void 0;if(!t.length)return e;for(var r=(e=e.split("")).length-1,o=0,a=0,i=0;r>0;r--,o++){o%=t.length,a+=n=t.charCodeAt(o);var l=e[i=(n+o+a)%r];e[i]=e[r],e[r]=l}return e=e.join("")}},{key:"_toAlphabet",value:function(e,t){var n="";do{n=t.charAt(e%t.length)+n,e=parseInt(e/t.length,10)}while(e);return n}},{key:"_fromAlphabet",value:function(e,t){return e.split("").map(function(e){return t.indexOf(e)}).reduce(function(e,n){return e*t.length+n},0)}}]),e}();t.default=r,e.exports=t.default})?r.apply(t,o):r)||(e.exports=a)},function(e,t,n){"use strict";var r=n(9);e.exports=((e,t)=>{var n=new r,o=[9,9,parseInt(t)],a={};return e.map(function(e,t){if(o.push(t),"object"==typeof e){var r=0;return Object.keys(e).forEach(function(t){o.push(r),e["_"+t+"Id"]=n.encode(o),o=o.slice(0,6),console.log(o),r++}),e}return a={value:e,id:n.encode(o)},o=o.slice(0,5),a})})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=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}}(),o=n(1),a=u(o),i=u(n(10)),l=u(n(8));function u(e){return e&&e.__esModule?e:{default:e}}var s=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=function(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}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={items:[]},n.fillRecipients=n.fillRecipients.bind(n),n}return function(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)}(t,o.Component),r(t,[{key:"componentDidMount",value:function(){var e=this;chrome.storage.sync.get("gmail_lists",function(t){e.setState({items:void 0!==t.gmail_lists?t.gmail_lists:[]})})}},{key:"fillRecipients",value:function(e,t){var n=this,r=(0,l.default)(e);chrome.storage.sync.get("gmail_lists_"+r,function(e){var o=e["gmail_lists_"+r];n.props.event.composeView[t](void 0!==o?o:[])})}},{key:"render",value:function(){var e=this,t=(0,i.default)(this.state.items,1);return a.default.createElement("ul",{className:"gmails-lists-list"},t.map(function(t){return a.default.createElement(a.default.Fragment,{key:t.id},a.default.createElement("li",{key:t.id},t.value,a.default.createElement("a",{name:t.value,title:"Fill 'Bcc' field.",onClick:function(t){t.preventDefault(),e.fillRecipients(t.target.name,"setBccRecipients")},href:""},"Bcc"),a.default.createElement("a",{name:t.value,title:"Fill 'Cc' field.",onClick:function(t){t.preventDefault(),e.fillRecipients(t.target.name,"setCcRecipients")},href:""},"Cc"),a.default.createElement("a",{name:t.value,title:"Fill 'To' field.",onClick:function(t){t.preventDefault(),e.fillRecipients(t.target.name,"setToRecipients")},href:""},"To")),a.default.createElement("hr",{className:"gmail-lists-list--divider"}))}))}}]),t}();t.default=s},function(e,t,n){"use strict";var r=/-(.)/g;e.exports=function(e){return e.replace(r,function(e,t){return t.toUpperCase()})}},function(e,t,n){"use strict";var r=n(12),o=/^-ms-/;e.exports=function(e){return r(e.replace(o,"ms-"))}},function(e,t,n){"use strict";var r=/([A-Z])/g;e.exports=function(e){return e.replace(r,"-$1").toLowerCase()}},function(e,t,n){"use strict";var r=n(14),o=/^ms-/;e.exports=function(e){return r(e).replace(o,"-ms-")}},function(e,t,n){"use strict";e.exports=function(e){var t=(e?e.ownerDocument||e:document).defaultView||window;return!(!e||!("function"==typeof t.Node?e instanceof t.Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}},function(e,t,n){"use strict";var r=n(16);e.exports=function(e){return r(e)&&3==e.nodeType}},function(e,t,n){"use strict";var r=n(17);e.exports=function e(t,n){return!(!t||!n)&&(t===n||!r(t)&&(r(n)?e(t,n.parentNode):"contains"in t?t.contains(n):!!t.compareDocumentPosition&&!!(16&t.compareDocumentPosition(n))))}},function(e,t,n){"use strict";var r=Object.prototype.hasOwnProperty;function o(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!=e&&t!=t}e.exports=function(e,t){if(o(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length)return!1;for(var i=0;i<n.length;i++)if(!r.call(t,n[i])||!o(e[n[i]],t[n[i]]))return!1;return!0}},function(e,t,n){"use strict";e.exports=function(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}},function(e,t,n){"use strict";var r=!("undefined"==typeof window||!window.document||!window.document.createElement),o={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:r&&!!window.screen,isInWorker:!r};e.exports=o},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict"; /** @license React v16.4.1 * react.development.js * * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */(function(){var t=n(5),r=n(6),o=n(4),a=n(3),i=n(0),l=n(2),u="function"==typeof Symbol&&Symbol.for,s=u?Symbol.for("react.element"):60103,c=u?Symbol.for("react.portal"):60106,d=u?Symbol.for("react.fragment"):60107,f=u?Symbol.for("react.strict_mode"):60108,p=u?Symbol.for("react.profiler"):60114,h=u?Symbol.for("react.provider"):60109,m=u?Symbol.for("react.context"):60110,v=u?Symbol.for("react.async_mode"):60111,g=u?Symbol.for("react.forward_ref"):60112,y=u?Symbol.for("react.timeout"):60113,b="function"==typeof Symbol&&Symbol.iterator,w="@@iterator";function k(e){if(null===e||void 0===e)return null;var t=b&&e[b]||e[w];return"function"==typeof t?t:null}var x=function(e,t){if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(!e){for(var n=arguments.length,r=Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];(function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var o=0,a="Warning: "+e.replace(/%s/g,function(){return n[o++]});"undefined"!=typeof console&&console.warn(a);try{throw new Error(a)}catch(e){}}).apply(void 0,[t].concat(r))}},T={};function C(e,t){var n=e.constructor,r=n&&(n.displayName||n.name)||"ReactClass",o=r+"."+t;T[o]||(a(!1,"Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",t,r),T[o]=!0)}var S={isMounted:function(e){return!1},enqueueForceUpdate:function(e,t,n){C(e,"forceUpdate")},enqueueReplaceState:function(e,t,n,r){C(e,"replaceState")},enqueueSetState:function(e,t,n,r){C(e,"setState")}};function _(e,t,n){this.props=e,this.context=t,this.refs=o,this.updater=n||S}_.prototype.isReactComponent={},_.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e&&r(!1,"setState(...): takes an object of state variables to update or a function which returns an object of state variables."),this.updater.enqueueSetState(this,e,t,"setState")},_.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};var E={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]},P=function(e,t){Object.defineProperty(_.prototype,e,{get:function(){x(!1,"%s(...) is deprecated in plain JavaScript React classes. %s",t[0],t[1])}})};for(var R in E)E.hasOwnProperty(R)&&P(R,E[R]);function N(){}function O(e,t,n){this.props=e,this.context=t,this.refs=o,this.updater=n||S}N.prototype=_.prototype;var I=O.prototype=new N;I.constructor=O,t(I,_.prototype),I.isPureReactComponent=!0;var U={current:null},A=Object.prototype.hasOwnProperty,D={key:!0,ref:!0,__self:!0,__source:!0},M=void 0,F=void 0;function j(e){if(A.call(e,"ref")){var t=Object.getOwnPropertyDescriptor(e,"ref").get;if(t&&t.isReactWarning)return!1}return void 0!==e.ref}function L(e){if(A.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}var W=function(e,t,n,r,o,a,i){var l={$$typeof:s,type:e,key:t,ref:n,props:i,_owner:a,_store:{}};return Object.defineProperty(l._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(l,"_self",{configurable:!1,enumerable:!1,writable:!1,value:r}),Object.defineProperty(l,"_source",{configurable:!1,enumerable:!1,writable:!1,value:o}),Object.freeze&&(Object.freeze(l.props),Object.freeze(l)),l};function z(e,t,n){var r=void 0,o={},i=null,l=null,u=null,c=null;if(null!=t)for(r in j(t)&&(l=t.ref),L(t)&&(i=""+t.key),u=void 0===t.__self?null:t.__self,c=void 0===t.__source?null:t.__source,t)A.call(t,r)&&!D.hasOwnProperty(r)&&(o[r]=t[r]);var d=arguments.length-2;if(1===d)o.children=n;else if(d>1){for(var f=Array(d),p=0;p<d;p++)f[p]=arguments[p+2];Object.freeze&&Object.freeze(f),o.children=f}if(e&&e.defaultProps){var h=e.defaultProps;for(r in h)void 0===o[r]&&(o[r]=h[r])}if((i||l)&&(void 0===o.$$typeof||o.$$typeof!==s)){var m="function"==typeof e?e.displayName||e.name||"Unknown":e;i&&function(e,t){var n=function(){M||(M=!0,a(!1,"%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://fb.me/react-special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}(o,m),l&&function(e,t){var n=function(){F||(F=!0,a(!1,"%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://fb.me/react-special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"ref",{get:n,configurable:!0})}(o,m)}return W(e,i,l,u,c,U.current,o)}function B(e){return"object"==typeof e&&null!==e&&e.$$typeof===s}var V={getCurrentStack:null,getStackAddendum:function(){var e=V.getCurrentStack;return e?e():null}},H=".",q=":";var $=!1,Y=/\/+/g;function Q(e){return(""+e).replace(Y,"$&/")}var K=10,X=[];function G(e,t,n,r){if(X.length){var o=X.pop();return o.result=e,o.keyPrefix=t,o.func=n,o.context=r,o.count=0,o}return{result:e,keyPrefix:t,func:n,context:r,count:0}}function Z(e){e.result=null,e.keyPrefix=null,e.func=null,e.context=null,e.count=0,X.length<K&&X.push(e)}function J(e,t,n){return null==e?0:function e(t,n,o,i){var l=typeof t;"undefined"!==l&&"boolean"!==l||(t=null);var u=!1;if(null===t)u=!0;else switch(l){case"string":case"number":u=!0;break;case"object":switch(t.$$typeof){case s:case c:u=!0}}if(u)return o(i,t,""===n?H+ee(t,0):n),1;var d=void 0,f=0,p=""===n?H:n+q;if(Array.isArray(t))for(var h=0;h<t.length;h++)f+=e(d=t[h],p+ee(d,h),o,i);else{var m=k(t);if("function"==typeof m){m===t.entries&&($||a(!1,"Using Maps as children is unsupported and will likely yield unexpected results. Convert it to a sequence/iterable of keyed ReactElements instead.%s",V.getStackAddendum()),$=!0);for(var v=m.call(t),g=void 0,y=0;!(g=v.next()).done;)f+=e(d=g.value,p+ee(d,y++),o,i)}else if("object"===l){var b;b=" If you meant to render a collection of children, use an array instead."+V.getStackAddendum();var w=""+t;r(!1,"Objects are not valid as a React child (found: %s).%s","[object Object]"===w?"object with keys {"+Object.keys(t).join(", ")+"}":w,b)}}return f}(e,"",t,n)}function ee(e,t){return"object"==typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+(""+e).replace(/[=:]/g,function(e){return t[e]})}(e.key):t.toString(36)}function te(e,t,n){var r=e.func,o=e.context;r.call(o,t,e.count++)}function ne(e,t,n){var r=e.result,o=e.keyPrefix,a=e.func,l=e.context,u=a.call(l,t,e.count++);Array.isArray(u)?re(u,r,n,i.thatReturnsArgument):null!=u&&(B(u)&&(u=function(e,t){return W(e.type,t,e.ref,e._self,e._source,e._owner,e.props)}(u,o+(!u.key||t&&t.key===u.key?"":Q(u.key)+"/")+n)),r.push(u))}function re(e,t,n,r,o){var a="";null!=n&&(a=Q(n)+"/");var i=G(t,a,r,o);J(e,ne,i),Z(i)}function oe(e){var t=e.type;if("function"==typeof t)return t.displayName||t.name;if("string"==typeof t)return t;switch(t){case v:return"AsyncMode";case m:return"Context.Consumer";case d:return"ReactFragment";case c:return"ReactPortal";case p:return"Profiler("+e.pendingProps.id+")";case h:return"Context.Provider";case f:return"StrictMode";case y:return"Timeout"}if("object"==typeof t&&null!==t)switch(t.$$typeof){case g:var n=t.render.displayName||t.render.name||"";return""!==n?"ForwardRef("+n+")":"ForwardRef"}return null}var ae,ie=void 0,le=void 0,ue=function(){};function se(){if(U.current){var e=oe(U.current);if(e)return"\n\nCheck the render method of `"+e+"`."}return""}ie=null,le=!1,ae=function(e){if(null==e)return"#empty";if("string"==typeof e||"number"==typeof e)return"#text";if("string"==typeof e.type)return e.type;var t=e.type;if(t===d)return"React.Fragment";if("object"==typeof t&&null!==t&&t.$$typeof===g){var n=t.render.displayName||t.render.name||"";return""!==n?"ForwardRef("+n+")":"ForwardRef"}return t.displayName||t.name||"Unknown"},ue=function(){var e="";if(ie){var t=ae(ie),n=ie._owner;e+=function(e,t,n){return"\n in "+(e||"Unknown")+(t?" (at "+t.fileName.replace(/^.*[\\\/]/,"")+":"+t.lineNumber+")":n?" (created by "+n+")":"")}(t,ie._source,n&&oe(n))}return e+=V.getStackAddendum()||""};var ce={};function de(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;var n=function(e){var t=se();if(!t){var n="string"==typeof e?e:e.displayName||e.name;n&&(t="\n\nCheck the top-level render call using <"+n+">.")}return t}(t);if(!ce[n]){ce[n]=!0;var r="";e&&e._owner&&e._owner!==U.current&&(r=" It was passed a child from "+oe(e._owner)+"."),ie=e,a(!1,'Each child in an array or iterator should have a unique "key" prop.%s%s See https://fb.me/react-warning-keys for more information.%s',n,r,ue()),ie=null}}}function fe(e,t){if("object"==typeof e)if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];B(r)&&de(r,t)}else if(B(e))e._store&&(e._store.validated=!0);else if(e){var o=k(e);if("function"==typeof o&&o!==e.entries)for(var a=o.call(e),i=void 0;!(i=a.next()).done;)B(i.value)&&de(i.value,t)}}function pe(e){var t=e.type,n=void 0,r=void 0;if("function"==typeof t)n=t.displayName||t.name,r=t.propTypes;else{if("object"!=typeof t||null===t||t.$$typeof!==g)return;var o=t.render.displayName||t.render.name||"";n=""!==o?"ForwardRef("+o+")":"ForwardRef",r=t.propTypes}r?(ie=e,l(r,e.props,"prop",n,ue),ie=null):void 0===t.PropTypes||le||(le=!0,a(!1,"Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",n||"Unknown")),"function"==typeof t.getDefaultProps&&(t.getDefaultProps.isReactClassApproved||a(!1,"getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."))}function he(e,t,n){var r=function(e){return"string"==typeof e||"function"==typeof e||e===d||e===v||e===p||e===f||e===y||"object"==typeof e&&null!==e&&(e.$$typeof===h||e.$$typeof===m||e.$$typeof===g)}(e);if(!r){var o="";(void 0===e||"object"==typeof e&&null!==e&&0===Object.keys(e).length)&&(o+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var i=function(e){if(null!==e&&void 0!==e&&void 0!==e.__source){var t=e.__source;return"\n\nCheck your code at "+t.fileName.replace(/^.*[\\\/]/,"")+":"+t.lineNumber+"."}return""}(t);o+=i||se(),o+=ue()||"";var l=void 0;l=null===e?"null":Array.isArray(e)?"array":typeof e,a(!1,"React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",l,o)}var u=z.apply(this,arguments);if(null==u)return u;if(r)for(var s=2;s<arguments.length;s++)fe(arguments[s],e);return e===d?function(e){ie=e;for(var t=Object.keys(e.props),n=0;n<t.length;n++){var r=t[n];if("children"!==r&&"key"!==r){a(!1,"Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.%s",r,ue());break}}null!==e.ref&&a(!1,"Invalid attribute `ref` supplied to `React.Fragment`.%s",ue()),ie=null}(u):pe(u),u}var me={Children:{map:function(e,t,n){if(null==e)return e;var r=[];return re(e,r,null,t,n),r},forEach:function(e,t,n){if(null==e)return e;var r=G(null,null,t,n);J(e,te,r),Z(r)},count:function(e){return J(e,i.thatReturnsNull,null)},toArray:function(e){var t=[];return re(e,t,null,i.thatReturnsArgument),t},only:function(e){return B(e)||r(!1,"React.Children.only expected to receive a single React element child."),e}},createRef:function(){var e={current:null};return Object.seal(e),e},Component:_,PureComponent:O,createContext:function(e,t){void 0===t?t=null:null!==t&&"function"!=typeof t&&a(!1,"createContext: Expected the optional second argument to be a function. Instead received: %s",t);var n={$$typeof:m,_calculateChangedBits:t,_defaultValue:e,_currentValue:e,_currentValue2:e,_changedBits:0,_changedBits2:0,Provider:null,Consumer:null};return n.Provider={$$typeof:h,_context:n},n.Consumer=n,n._currentRenderer=null,n._currentRenderer2=null,n},forwardRef:function(e){return"function"!=typeof e&&a(!1,"forwardRef requires a render function but was given %s.",null===e?"null":typeof e),null!=e&&(null!=e.defaultProps||null!=e.propTypes)&&a(!1,"forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"),{$$typeof:g,render:e}},Fragment:d,StrictMode:f,unstable_AsyncMode:v,unstable_Profiler:p,createElement:he,cloneElement:function(e,n,o){for(var a=function(e,n,o){(null===e||void 0===e)&&r(!1,"React.cloneElement(...): The argument must be a React element, but you passed %s.",e);var a=void 0,i=t({},e.props),l=e.key,u=e.ref,s=e._self,c=e._source,d=e._owner;if(null!=n){j(n)&&(u=n.ref,d=U.current),L(n)&&(l=""+n.key);var f=void 0;for(a in e.type&&e.type.defaultProps&&(f=e.type.defaultProps),n)A.call(n,a)&&!D.hasOwnProperty(a)&&(void 0===n[a]&&void 0!==f?i[a]=f[a]:i[a]=n[a])}var p=arguments.length-2;if(1===p)i.children=o;else if(p>1){for(var h=Array(p),m=0;m<p;m++)h[m]=arguments[m+2];i.children=h}return W(e.type,l,u,s,c,d,i)}.apply(this,arguments),i=2;i<arguments.length;i++)fe(arguments[i],a.type);return pe(a),a},createFactory:function(e){var t=he.bind(null,e);return t.type=e,Object.defineProperty(t,"type",{enumerable:!1,get:function(){return x(!1,"Factory.type is deprecated. Access the class directly before passing it to createFactory."),Object.defineProperty(this,"type",{value:e}),e}}),t},isValidElement:B,version:"16.4.1",__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{ReactCurrentOwner:U,assign:t}};t(me.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,{ReactDebugCurrentFrame:V,ReactComponentTreeHook:{}});var ve=Object.freeze({default:me}),ge=ve&&me||ve,ye=ge.default?ge.default:ge;e.exports=ye})()},function(e,t,n){"use strict"; /** @license React v16.4.1 * react-dom.development.js * * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */(function(){var t=n(6),r=n(1),o=n(3),a=n(21),i=n(5),l=n(0),u=n(2),s=n(20),c=n(19),d=n(18),f=n(4),p=n(15),h=n(13);r||t(!1,"ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.");var m=function(e,t,n,r,o,a,i,l,u){this._hasCaughtError=!1,this._caughtError=null;var s=Array.prototype.slice.call(arguments,3);try{t.apply(n,s)}catch(e){this._caughtError=e,this._hasCaughtError=!0}};if("undefined"!=typeof window&&"function"==typeof window.dispatchEvent&&"undefined"!=typeof document&&"function"==typeof document.createEvent){var v=document.createElement("react");m=function(e,n,r,o,a,i,l,u,s){"undefined"==typeof document&&t(!1,"The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.");var c=document.createEvent("Event"),d=!0,f=Array.prototype.slice.call(arguments,3);var p=void 0,h=!1,m=!1;function g(e){p=e.error,h=!0,null===p&&0===e.colno&&0===e.lineno&&(m=!0)}var y="react-"+(e||"invokeguardedcallback");window.addEventListener("error",g),v.addEventListener(y,function e(){v.removeEventListener(y,e,!1),n.apply(r,f),d=!1},!1),c.initEvent(y,!1,!1),v.dispatchEvent(c),d?(h?m&&(p=new Error("A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://fb.me/react-crossorigin-error for more information.")):p=new Error("An error was thrown inside one of your components, but React doesn't know what it was. This is likely due to browser flakiness. React does its best to preserve the \"Pause on exceptions\" behavior of the DevTools, which requires some DEV-mode only tricks. It's possible that these don't work in your browser. Try triggering the error in production mode, or switching to a modern browser. If you suspect that this is actually an issue with React, please file an issue."),this._hasCaughtError=!0,this._caughtError=p):(this._hasCaughtError=!1,this._caughtError=null),window.removeEventListener("error",g)}}var g=m,y={_caughtError:null,_hasCaughtError:!1,_rethrowError:null,_hasRethrowError:!1,invokeGuardedCallback:function(e,t,n,r,o,a,i,l,u){g.apply(y,arguments)},invokeGuardedCallbackAndCatchFirstError:function(e,t,n,r,o,a,i,l,u){if(y.invokeGuardedCallback.apply(this,arguments),y.hasCaughtError()){var s=y.clearCaughtError();y._hasRethrowError||(y._hasRethrowError=!0,y._rethrowError=s)}},rethrowCaughtError:function(){return b.apply(y,arguments)},hasCaughtError:function(){return y._hasCaughtError},clearCaughtError:function(){if(y._hasCaughtError){var e=y._caughtError;return y._caughtError=null,y._hasCaughtError=!1,e}t(!1,"clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.")}},b=function(){if(y._hasRethrowError){var e=y._rethrowError;throw y._rethrowError=null,y._hasRethrowError=!1,e}},w=null,k={};function x(){if(w)for(var e in k){var n=k[e],r=w.indexOf(e);if(r>-1||t(!1,"EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.",e),!S[r]){n.extractEvents||t(!1,"EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.",e),S[r]=n;var o=n.eventTypes;for(var a in o)T(o[a],n,a)||t(!1,"EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.",a,e)}}}function T(e,n,r){_.hasOwnProperty(r)&&t(!1,"EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.",r),_[r]=e;var o=e.phasedRegistrationNames;if(o){for(var a in o){if(o.hasOwnProperty(a))C(o[a],n,r)}return!0}return!!e.registrationName&&(C(e.registrationName,n,r),!0)}function C(e,n,r){E[e]&&t(!1,"EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.",e),E[e]=n,P[e]=n.eventTypes[r].dependencies;var o=e.toLowerCase();R[o]=e,"onDoubleClick"===e&&(R.ondblclick=e)}var S=[],_={},E={},P={},R={};function N(e){w&&t(!1,"EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React."),w=Array.prototype.slice.call(e),x()}function O(e){var n=!1;for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];k.hasOwnProperty(r)&&k[r]===o||(k[r]&&t(!1,"EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.",r),k[r]=o,n=!0)}n&&x()}var I=Object.freeze({plugins:S,eventNameDispatchConfigs:_,registrationNameModules:E,registrationNameDependencies:P,possibleRegistrationNames:R,injectEventPluginOrder:N,injectEventPluginsByName:O}),U=null,A=null,D=null,M=function(e){U=e.getFiberCurrentPropsFromNode,A=e.getInstanceFromNode,(D=e.getNodeFromInstance)&&A||o(!1,"EventPluginUtils.injection.injectComponentTree(...): Injected module is missing getNodeFromInstance or getInstanceFromNode.")},F=void 0;function j(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=D(r),y.invokeGuardedCallbackAndCatchFirstError(o,n,void 0,e),e.currentTarget=null}function L(e,n){return null==n&&t(!1,"accumulateInto(...): Accumulated items must not be null or undefined."),null==e?n:Array.isArray(e)?Array.isArray(n)?(e.push.apply(e,n),e):(e.push(n),e):Array.isArray(n)?[e].concat(n):[e,n]}function W(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)}F=function(e){var t=e._dispatchListeners,n=e._dispatchInstances,r=Array.isArray(t),a=r?t.length:t?1:0,i=Array.isArray(n),l=i?n.length:n?1:0;(i!==r||l!==a)&&o(!1,"EventPluginUtils: Invalid `event`.")};var z=null,B=function(e,t){e&&(!function(e,t){var n=e._dispatchListeners,r=e._dispatchInstances;if(F(e),Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)j(e,0,n[o],r[o]);else n&&j(e,0,n,r);e._dispatchListeners=null,e._dispatchInstances=null}(e),e.isPersistent()||e.constructor.release(e))},V=function(e){return B(e)},H=function(e){return B(e)};var q={injectEventPluginOrder:N,injectEventPluginsByName:O};function $(e,n){var r,o=e.stateNode;if(!o)return null;var a=U(o);return a?(r=a[n],function(e,t,n){switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":return!(!n.disabled||!function(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}(t));default:return!1}}(n,e.type,a)?null:(r&&"function"!=typeof r&&t(!1,"Expected `%s` listener to be a function, instead got a value of `%s` type.",n,typeof r),r)):null}function Y(e,n){null!==e&&(z=L(z,e));var r=z;z=null,r&&(W(r,n?V:H),z&&t(!1,"processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented."),y.rethrowCaughtError())}function Q(e,t,n,r){Y(function(e,t,n,r){for(var o=null,a=0;a<S.length;a++){var i=S[a];if(i){var l=i.extractEvents(e,t,n,r);l&&(o=L(o,l))}}return o}(e,t,n,r),!1)}var K=Object.freeze({injection:q,getListener:$,runEventsInBatch:Y,runExtractedEventsInBatch:Q}),X=0,G=1,Z=2,J=3,ee=4,te=5,ne=6,re=10,oe=11,ae=12,ie=13,le=14,ue=15,se=16,ce=Math.random().toString(36).slice(2),de="__reactInternalInstance$"+ce,fe="__reactEventHandlers$"+ce;function pe(e,t){t[de]=e}function he(e){if(e[de])return e[de];for(;!e[de];){if(!e.parentNode)return null;e=e.parentNode}var t=e[de];return t.tag===te||t.tag===ne?t:null}function me(e){var t=e[de];return t&&(t.tag===te||t.tag===ne)?t:null}function ve(e){if(e.tag===te||e.tag===ne)return e.stateNode;t(!1,"getNodeFromInstance: Invalid argument.")}function ge(e){return e[fe]||null}function ye(e,t){e[fe]=t}var be=Object.freeze({precacheFiberNode:pe,getClosestInstanceFromNode:he,getInstanceFromNode:me,getNodeFromInstance:ve,getFiberCurrentPropsFromNode:ge,updateFiberProps:ye});function we(e){do{e=e.return}while(e&&e.tag!==te);return e||null}function ke(e,t,n){for(var r=[];e;)r.push(e),e=we(e);var o=void 0;for(o=r.length;o-- >0;)t(r[o],"captured",n);for(o=0;o<r.length;o++)t(r[o],"bubbled",n)}function xe(e,t,n,r,o){for(var a=e&&t?function(e,t){for(var n=0,r=e;r;r=we(r))n++;for(var o=0,a=t;a;a=we(a))o++;for(;n-o>0;)e=we(e),n--;for(;o-n>0;)t=we(t),o--;for(var i=n;i--;){if(e===t||e===t.alternate)return e;e=we(e),t=we(t)}return null}(e,t):null,i=[];e&&e!==a;){var l=e.alternate;if(null!==l&&l===a)break;i.push(e),e=we(e)}for(var u=[];t&&t!==a;){var s=t.alternate;if(null!==s&&s===a)break;u.push(t),t=we(t)}for(var c=0;c<i.length;c++)n(i[c],"bubbled",r);for(var d=u.length;d-- >0;)n(u[d],"captured",o)}function Te(e,t,n){e||o(!1,"Dispatching inst must not be null");var r=function(e,t,n){return $(e,t.dispatchConfig.phasedRegistrationNames[n])}(e,n,t);r&&(n._dispatchListeners=L(n._dispatchListeners,r),n._dispatchInstances=L(n._dispatchInstances,e))}function Ce(e){e&&e.dispatchConfig.phasedRegistrationNames&&ke(e._targetInst,Te,e)}function Se(e){if(e&&e.dispatchConfig.phasedRegistrationNames){var t=e._targetInst;ke(t?function(e){return we(e)}(t):null,Te,e)}}function _e(e,t,n){if(e&&n&&n.dispatchConfig.registrationName){var r=$(e,n.dispatchConfig.registrationName);r&&(n._dispatchListeners=L(n._dispatchListeners,r),n._dispatchInstances=L(n._dispatchInstances,e))}}function Ee(e){e&&e.dispatchConfig.registrationName&&_e(e._targetInst,0,e)}function Pe(e){W(e,Ce)}function Re(e,t,n,r){xe(n,r,_e,e,t)}var Ne=Object.freeze({accumulateTwoPhaseDispatches:Pe,accumulateTwoPhaseDispatchesSkipTarget:function(e){W(e,Se)},accumulateEnterLeaveDispatches:Re,accumulateDirectDispatches:function(e){W(e,Ee)}});function Oe(e){return e}function Ie(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n["ms"+e]="MS"+t,n["O"+e]="o"+t.toLowerCase(),n}var Ue={animationend:Ie("Animation","AnimationEnd"),animationiteration:Ie("Animation","AnimationIteration"),animationstart:Ie("Animation","AnimationStart"),transitionend:Ie("Transition","TransitionEnd")},Ae={},De={};function Me(e){if(Ae[e])return Ae[e];if(!Ue[e])return e;var t=Ue[e];for(var n in t)if(t.hasOwnProperty(n)&&n in De)return Ae[e]=t[n];return e}a.canUseDOM&&(De=document.createElement("div").style,"AnimationEvent"in window||(delete Ue.animationend.animation,delete Ue.animationiteration.animation,delete Ue.animationstart.animation),"TransitionEvent"in window||delete Ue.transitionend.transition);var Fe=Oe("abort"),je=Oe(Me("animationend")),Le=Oe(Me("animationiteration")),We=Oe(Me("animationstart")),ze=Oe("blur"),Be=Oe("canplay"),Ve=Oe("canplaythrough"),He=Oe("cancel"),qe=Oe("change"),$e=Oe("click"),Ye=Oe("close"),Qe=Oe("compositionend"),Ke=Oe("compositionstart"),Xe=Oe("compositionupdate"),Ge=Oe("contextmenu"),Ze=Oe("copy"),Je=Oe("cut"),et=Oe("dblclick"),tt=Oe("drag"),nt=Oe("dragend"),rt=Oe("dragenter"),ot=Oe("dragexit"),at=Oe("dragleave"),it=Oe("dragover"),lt=Oe("dragstart"),ut=Oe("drop"),st=Oe("durationchange"),ct=Oe("emptied"),dt=Oe("encrypted"),ft=Oe("ended"),pt=Oe("error"),ht=Oe("focus"),mt=Oe("gotpointercapture"),vt=Oe("input"),gt=Oe("invalid"),yt=Oe("keydown"),bt=Oe("keypress"),wt=Oe("keyup"),kt=Oe("load"),xt=Oe("loadstart"),Tt=Oe("loadeddata"),Ct=Oe("loadedmetadata"),St=Oe("lostpointercapture"),_t=Oe("mousedown"),Et=Oe("mousemove"),Pt=Oe("mouseout"),Rt=Oe("mouseover"),Nt=Oe("mouseup"),Ot=Oe("paste"),It=Oe("pause"),Ut=Oe("play"),At=Oe("playing"),Dt=Oe("pointercancel"),Mt=Oe("pointerdown"),Ft=Oe("pointermove"),jt=Oe("pointerout"),Lt=Oe("pointerover"),Wt=Oe("pointerup"),zt=Oe("progress"),Bt=Oe("ratechange"),Vt=Oe("reset"),Ht=Oe("scroll"),qt=Oe("seeked"),$t=Oe("seeking"),Yt=Oe("selectionchange"),Qt=Oe("stalled"),Kt=Oe("submit"),Xt=Oe("suspend"),Gt=Oe("textInput"),Zt=Oe("timeupdate"),Jt=Oe("toggle"),en=Oe("touchcancel"),tn=Oe("touchend"),nn=Oe("touchmove"),rn=Oe("touchstart"),on=Oe(Me("transitionend")),an=Oe("volumechange"),ln=Oe("waiting"),un=Oe("wheel"),sn=[Fe,Be,Ve,st,ct,dt,ft,pt,Tt,Ct,xt,It,Ut,At,zt,Bt,qt,$t,Qt,Xt,Zt,an,ln];function cn(e){return function(e){return e}(e)}var dn=null;function fn(){return!dn&&a.canUseDOM&&(dn="textContent"in document.documentElement?"textContent":"innerText"),dn}var pn={_root:null,_startText:null,_fallbackText:null};function hn(){if(pn._fallbackText)return pn._fallbackText;var e=void 0,t=pn._startText,n=t.length,r=void 0,o=mn(),a=o.length;for(e=0;e<n&&t[e]===o[e];e++);var i=n-e;for(r=1;r<=i&&t[n-r]===o[a-r];r++);var l=r>1?1-r:void 0;return pn._fallbackText=o.slice(e,l),pn._fallbackText}function mn(){return"value"in pn._root?pn._root.value:pn._root[fn()]}var vn=!1,gn=10,yn=["dispatchConfig","_targetInst","nativeEvent","isDefaultPrevented","isPropagationStopped","_dispatchListeners","_dispatchInstances"],bn={type:null,target:null,currentTarget:l.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};function wn(e,t,n,r){delete this.nativeEvent,delete this.preventDefault,delete this.stopPropagation,this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n;var o=this.constructor.Interface;for(var a in o)if(o.hasOwnProperty(a)){delete this[a];var i=o[a];i?this[a]=i(n):"target"===a?this.target=r:this[a]=n[a]}var u=null!=n.defaultPrevented?n.defaultPrevented:!1===n.returnValue;return this.isDefaultPrevented=u?l.thatReturnsTrue:l.thatReturnsFalse,this.isPropagationStopped=l.thatReturnsFalse,this}function kn(e,t){var n="function"==typeof t;return{configurable:!0,set:function(e){return r(n?"setting the method":"setting the property","This is effectively a no-op"),e},get:function(){return r(n?"accessing the method":"accessing the property",n?"This is a no-op function":"This is set to null"),t}};function r(t,n){o(!1,"This synthetic event is reused for performance reasons. If you're seeing this, you're %s `%s` on a released/nullified synthetic event. %s. If you must keep the original synthetic event around, use event.persist(). See https://fb.me/react-event-pooling for more information.",t,e,n)}}function xn(e,t,n,r){if(this.eventPool.length){var o=this.eventPool.pop();return this.call(o,e,t,n,r),o}return new this(e,t,n,r)}function Tn(e){e instanceof this||t(!1,"Trying to release an event instance into a pool of a different type."),e.destructor(),this.eventPool.length<gn&&this.eventPool.push(e)}function Cn(e){e.eventPool=[],e.getPooled=xn,e.release=Tn}i(wn.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=l.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=l.thatReturnsTrue)},persist:function(){this.isPersistent=l.thatReturnsTrue},isPersistent:l.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)Object.defineProperty(this,t,kn(t,e[t]));for(var n=0;n<yn.length;n++)this[yn[n]]=null;Object.defineProperty(this,"nativeEvent",kn("nativeEvent",null)),Object.defineProperty(this,"preventDefault",kn("preventDefault",l)),Object.defineProperty(this,"stopPropagation",kn("stopPropagation",l))}}),wn.Interface=bn,wn.extend=function(e){var t=this,n=function(){};n.prototype=t.prototype;var r=new n;function o(){return t.apply(this,arguments)}return i(r,o.prototype),o.prototype=r,o.prototype.constructor=o,o.Interface=i({},t.Interface,e),o.extend=t.extend,Cn(o),o},"function"==typeof Proxy&&!Object.isSealed(new Proxy({},{}))&&(wn=new Proxy(wn,{construct:function(e,t){return this.apply(e,Object.create(e.prototype),t)},apply:function(e,t,n){return new Proxy(e.apply(t,n),{set:function(e,t,n){return"isPersistent"===t||e.constructor.Interface.hasOwnProperty(t)||-1!==yn.indexOf(t)||(vn||e.isPersistent()||o(!1,"This synthetic event is reused for performance reasons. If you're seeing this, you're adding a new property in the synthetic event object. The property is never released. See https://fb.me/react-event-pooling for more information."),vn=!0),e[t]=n,!0}})}})),Cn(wn);var Sn=wn,_n=Sn.extend({data:null}),En=Sn.extend({data:null}),Pn=[9,13,27,32],Rn=229,Nn=a.canUseDOM&&"CompositionEvent"in window,On=null;a.canUseDOM&&"documentMode"in document&&(On=document.documentMode);var In=a.canUseDOM&&"TextEvent"in window&&!On,Un=a.canUseDOM&&(!Nn||On&&On>8&&On<=11),An=32,Dn=String.fromCharCode(An),Mn={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:[Qe,bt,Gt,Ot]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:[ze,Qe,yt,bt,wt,_t]},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:[ze,Ke,yt,bt,wt,_t]},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:[ze,Xe,yt,bt,wt,_t]}},Fn=!1;function jn(e,t){switch(e){case wt:return-1!==Pn.indexOf(t.keyCode);case yt:return t.keyCode!==Rn;case bt:case _t:case ze:return!0;default:return!1}}function Ln(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}var Wn=!1;function zn(e,t,n,r){var o=void 0,a=void 0;if(Nn?o=function(e){switch(e){case Ke:return Mn.compositionStart;case Qe:return Mn.compositionEnd;case Xe:return Mn.compositionUpdate}}(e):Wn?jn(e,n)&&(o=Mn.compositionEnd):function(e,t){return e===yt&&t.keyCode===Rn}(e,n)&&(o=Mn.compositionStart),!o)return null;Un&&(Wn||o!==Mn.compositionStart?o===Mn.compositionEnd&&Wn&&(a=hn()):Wn=function(e){return pn._root=e,pn._startText=mn(),!0}(r));var i=_n.getPooled(o,t,n,r);if(a)i.data=a;else{var l=Ln(n);null!==l&&(i.data=l)}return Pe(i),i}function Bn(e,t){if(Wn){if(e===Qe||!Nn&&jn(e,t)){var n=hn();return pn._root=null,pn._startText=null,pn._fallbackText=null,Wn=!1,n}return null}switch(e){case Ot:return null;case bt:if(!function(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}(t)){if(t.char&&t.char.length>1)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case Qe:return Un?null:t.data;default:return null}}function Vn(e,t,n,r){var o=void 0;if(!(o=In?function(e,t){switch(e){case Qe:return Ln(t);case bt:return t.which!==An?null:(Fn=!0,Dn);case Gt:var n=t.data;return n===Dn&&Fn?null:n;default:return null}}(e,n):Bn(e,n)))return null;var a=En.getPooled(Mn.beforeInput,t,n,r);return a.data=o,Pe(a),a}var Hn={eventTypes:Mn,extractEvents:function(e,t,n,r){var o=zn(e,t,n,r),a=Vn(e,t,n,r);return null===o?a:null===a?o:[o,a]}},qn=null,$n=null,Yn=null;function Qn(e){var n=A(e);if(n){qn&&"function"==typeof qn.restoreControlledState||t(!1,"Fiber needs to be injected to handle a fiber target for controlled events. This error is likely caused by a bug in React. Please file an issue.");var r=U(n.stateNode);qn.restoreControlledState(n.stateNode,n.type,r)}}var Kn={injectFiberControlledHostComponent:function(e){qn=e}};function Xn(e){$n?Yn?Yn.push(e):Yn=[e]:$n=e}function Gn(){return null!==$n||null!==Yn}function Zn(){if($n){var e=$n,t=Yn;if($n=null,Yn=null,Qn(e),t)for(var n=0;n<t.length;n++)Qn(t[n])}}var Jn=Object.freeze({injection:Kn,enqueueStateRestore:Xn,needsStateRestore:Gn,restoreStateIfNeeded:Zn}),er=function(e,t){return e(t)},tr=function(e,t,n){return e(t,n)},nr=function(){},rr=!1;function or(e,t){if(rr)return e(t);rr=!0;try{return er(e,t)}finally{rr=!1,Gn()&&(nr(),Zn())}}var ar=function(e){er=e.batchedUpdates,tr=e.interactiveUpdates,nr=e.flushInteractiveUpdates},ir={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function lr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!ir[e.type]:"textarea"===t}var ur=1,sr=3,cr=8,dr=9,fr=11;function pr(e){var t=e.target||e.srcElement||window;return t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===sr?t.parentNode:t} /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */function hr(e,t){if(!a.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var o=document.createElement("div");o.setAttribute(n,"return;"),r="function"==typeof o[n]}return r}function mr(e){var t=e.type,n=e.nodeName;return n&&"input"===n.toLowerCase()&&("checkbox"===t||"radio"===t)}function vr(e){return e._valueTracker}function gr(e){vr(e)||(e._valueTracker=function(e){var t=mr(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&void 0!==n&&"function"==typeof n.get&&"function"==typeof n.set){var o=n.get,a=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(e){r=""+e,a.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){!function(e){e._valueTracker=null}(e),delete e[t]}}}}(e))}function yr(e){if(!e)return!1;var t=vr(e);if(!t)return!0;var n=t.getValue(),r=function(e){var t="";return e?t=mr(e)?e.checked?"true":"false":e.value:t}(e);return r!==n&&(t.setValue(r),!0)}var br=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,wr=br.ReactCurrentOwner,kr=br.ReactDebugCurrentFrame,xr=function(e,t,n){return"\n in "+(e||"Unknown")+(t?" (at "+t.fileName.replace(/^.*[\\\/]/,"")+":"+t.lineNumber+")":n?" (created by "+n+")":"")},Tr="function"==typeof Symbol&&Symbol.for,Cr=Tr?Symbol.for("react.element"):60103,Sr=Tr?Symbol.for("react.portal"):60106,_r=Tr?Symbol.for("react.fragment"):60107,Er=Tr?Symbol.for("react.strict_mode"):60108,Pr=Tr?Symbol.for("react.profiler"):60114,Rr=Tr?Symbol.for("react.provider"):60109,Nr=Tr?Symbol.for("react.context"):60110,Or=Tr?Symbol.for("react.async_mode"):60111,Ir=Tr?Symbol.for("react.forward_ref"):60112,Ur=Tr?Symbol.for("react.timeout"):60113,Ar="function"==typeof Symbol&&Symbol.iterator,Dr="@@iterator";function Mr(e){if(null===e||void 0===e)return null;var t=Ar&&e[Ar]||e[Dr];return"function"==typeof t?t:null}function Fr(e){var t=e.type;if("function"==typeof t)return t.displayName||t.name;if("string"==typeof t)return t;switch(t){case Or:return"AsyncMode";case Nr:return"Context.Consumer";case _r:return"ReactFragment";case Sr:return"ReactPortal";case Pr:return"Profiler("+e.pendingProps.id+")";case Rr:return"Context.Provider";case Er:return"StrictMode";case Ur:return"Timeout"}if("object"==typeof t&&null!==t)switch(t.$$typeof){case Ir:var n=t.render.displayName||t.render.name||"";return""!==n?"ForwardRef("+n+")":"ForwardRef"}return null}function jr(e){switch(e.tag){case X:case G:case Z:case te:var t=e._debugOwner,n=e._debugSource,r=Fr(e),o=null;return t&&(o=Fr(t)),xr(r,n,o);default:return""}}function Lr(e){var t="",n=e;do{t+=jr(n),n=n.return}while(n);return t}function Wr(){var e=zr.current;return null===e?null:Lr(e)}var zr={current:null,phase:null,resetCurrentFiber:function(){kr.getCurrentStack=null,zr.current=null,zr.phase=null},setCurrentFiber:function(e){kr.getCurrentStack=Wr,zr.current=e,zr.phase=null},setCurrentPhase:function(e){zr.phase=e},getCurrentFiberOwnerName:function(){var e=zr.current;if(null===e)return null;var t=e._debugOwner;return null!==t&&void 0!==t?Fr(t):null},getCurrentFiberStackAddendum:Wr},Br=0,Vr=2,Hr=3,qr=4,$r=5,Yr=6,Qr=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",Kr=Qr+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Xr="data-reactroot",Gr=new RegExp("^["+Qr+"]["+Kr+"]*$"),Zr={},Jr={};function eo(e){return!!Jr.hasOwnProperty(e)||!Zr.hasOwnProperty(e)&&(Gr.test(e)?(Jr[e]=!0,!0):(Zr[e]=!0,o(!1,"Invalid attribute name: `%s`",e),!1))}function to(e,t,n){return null!==t?t.type===Br:!n&&(e.length>2&&("o"===e[0]||"O"===e[0])&&("n"===e[1]||"N"===e[1]))}function no(e,t,n,r){if(null!==n&&n.type===Br)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":if(r)return!1;if(null!==n)return!n.acceptsBooleans;var o=e.toLowerCase().slice(0,5);return"data-"!==o&&"aria-"!==o;default:return!1}}function ro(e,t,n,r){if(null===t||void 0===t)return!0;if(no(e,t,n,r))return!0;if(r)return!1;if(null!==n)switch(n.type){case Hr:return!t;case qr:return!1===t;case $r:return isNaN(t);case Yr:return isNaN(t)||t<1}return!1}function oo(e){return io.hasOwnProperty(e)?io[e]:null}function ao(e,t,n,r,o){this.acceptsBooleans=t===Vr||t===Hr||t===qr,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t}var io={};["children","dangerouslySetInnerHTML","defaultValue","defaultChecked","innerHTML","suppressContentEditableWarning","suppressHydrationWarning","style"].forEach(function(e){io[e]=new ao(e,Br,!1,e,null)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0],n=e[1];io[t]=new ao(t,1,!1,n,null)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){io[e]=new ao(e,Vr,!1,e.toLowerCase(),null)}),["autoReverse","externalResourcesRequired","preserveAlpha"].forEach(function(e){io[e]=new ao(e,Vr,!1,e,null)}),["allowFullScreen","async","autoFocus","autoPlay","controls","default","defer","disabled","formNoValidate","hidden","loop","noModule","noValidate","open","playsInline","readOnly","required","reversed","scoped","seamless","itemScope"].forEach(function(e){io[e]=new ao(e,Hr,!1,e.toLowerCase(),null)}),["checked","multiple","muted","selected"].forEach(function(e){io[e]=new ao(e,Hr,!0,e.toLowerCase(),null)}),["capture","download"].forEach(function(e){io[e]=new ao(e,qr,!1,e.toLowerCase(),null)}),["cols","rows","size","span"].forEach(function(e){io[e]=new ao(e,Yr,!1,e.toLowerCase(),null)}),["rowSpan","start"].forEach(function(e){io[e]=new ao(e,$r,!1,e.toLowerCase(),null)});var lo=/[\-\:]([a-z])/g,uo=function(e){return e[1].toUpperCase()};function so(e,t,n,r){if(r.mustUseProperty)return e[r.propertyName];var o=r.attributeName,a=null;if(r.type===qr){if(e.hasAttribute(o)){var i=e.getAttribute(o);return""===i||(ro(t,n,r,!1)?i:i===""+n?n:i)}}else if(e.hasAttribute(o)){if(ro(t,n,r,!1))return e.getAttribute(o);if(r.type===Hr)return n;a=e.getAttribute(o)}return ro(t,n,r,!1)?null===a?n:a:a===""+n?n:a}function co(e,t,n){if(eo(t)){if(!e.hasAttribute(t))return void 0===n?void 0:null;var r=e.getAttribute(t);return r===""+n?n:r}}function fo(e,t,n,r){var o=oo(t);if(!to(t,o,r))if(ro(t,n,o,r)&&(n=null),r||null===o){if(eo(t)){var a=t;null===n?e.removeAttribute(a):e.setAttribute(a,""+n)}}else if(o.mustUseProperty){var i=o.propertyName;if(null===n){var l=o.type;e[i]=l!==Hr&&""}else e[i]=n}else{var u=o.attributeName,s=o.attributeNamespace;if(null===n)e.removeAttribute(u);else{var c=o.type,d=void 0;d=c===Hr||c===qr&&!0===n?"":""+n,s?e.setAttributeNS(s,u,d):e.setAttribute(u,d)}}}["accent-height","alignment-baseline","arabic-form","baseline-shift","cap-height","clip-path","clip-rule","color-interpolation","color-interpolation-filters","color-profile","color-rendering","dominant-baseline","enable-background","fill-opacity","fill-rule","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","glyph-name","glyph-orientation-horizontal","glyph-orientation-vertical","horiz-adv-x","horiz-origin-x","image-rendering","letter-spacing","lighting-color","marker-end","marker-mid","marker-start","overline-position","overline-thickness","paint-order","panose-1","pointer-events","rendering-intent","shape-rendering","stop-color","stop-opacity","strikethrough-position","strikethrough-thickness","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-anchor","text-decoration","text-rendering","underline-position","underline-thickness","unicode-bidi","unicode-range","units-per-em","v-alphabetic","v-hanging","v-ideographic","v-mathematical","vector-effect","vert-adv-y","vert-origin-x","vert-origin-y","word-spacing","writing-mode","xmlns:xlink","x-height"].forEach(function(e){var t=e.replace(lo,uo);io[t]=new ao(t,1,!1,e,null)}),["xlink:actuate","xlink:arcrole","xlink:href","xlink:role","xlink:show","xlink:title","xlink:type"].forEach(function(e){var t=e.replace(lo,uo);io[t]=new ao(t,1,!1,e,"http://www.w3.org/1999/xlink")}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(lo,uo);io[t]=new ao(t,1,!1,e,"http://www.w3.org/XML/1998/namespace")}),io.tabIndex=new ao("tabIndex",1,!1,"tabindex",null);var po={checkPropTypes:null},ho={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},mo={value:function(e,t,n){return!e[t]||ho[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")}};po.checkPropTypes=function(e,t,n){u(mo,t,"prop",e,n)};var vo=zr.getCurrentFiberOwnerName,go=zr.getCurrentFiberStackAddendum,yo=!1,bo=!1,wo=!1,ko=!1;function xo(e){return"checkbox"===e.type||"radio"===e.type?null!=e.checked:null!=e.value}function To(e,t){var n=e,r=t.checked;return i({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=r?r:n._wrapperState.initialChecked})}function Co(e,t){po.checkPropTypes("input",t,go),void 0===t.checked||void 0===t.defaultChecked||bo||(o(!1,"%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://fb.me/react-controlled-components",vo()||"A component",t.type),bo=!0),void 0===t.value||void 0===t.defaultValue||yo||(o(!1,"%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://fb.me/react-controlled-components",vo()||"A component",t.type),yo=!0);var n=e,r=null==t.defaultValue?"":t.defaultValue;n._wrapperState={initialChecked:null!=t.checked?t.checked:t.defaultChecked,initialValue:No(null!=t.value?t.value:r),controlled:xo(t)}}function So(e,t){var n=e,r=t.checked;null!=r&&fo(n,"checked",r,!1)}function _o(e,t){var n=e,r=xo(t);n._wrapperState.controlled||!r||ko||(o(!1,"A component is changing an uncontrolled input of type %s to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s",t.type,go()),ko=!0),!n._wrapperState.controlled||r||wo||(o(!1,"A component is changing a controlled input of type %s to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s",t.type,go()),wo=!0),So(e,t);var a=No(t.value);null!=a&&("number"===t.type?(0===a&&""===n.value||n.value!=a)&&(n.value=""+a):n.value!==""+a&&(n.value=""+a)),t.hasOwnProperty("value")?Ro(n,t.type,a):t.hasOwnProperty("defaultValue")&&Ro(n,t.type,No(t.defaultValue)),null==t.checked&&null!=t.defaultChecked&&(n.defaultChecked=!!t.defaultChecked)}function Eo(e,t,n){var r=e;if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var o=""+r._wrapperState.initialValue,a=r.value;n||o!==a&&(r.value=o),r.defaultValue=o}var i=r.name;""!==i&&(r.name=""),r.defaultChecked=!r.defaultChecked,r.defaultChecked=!r.defaultChecked,""!==i&&(r.name=i)}function Po(e,n){var r=e;_o(r,n),function(e,n){var r=n.name;if("radio"===n.type&&null!=r){for(var o=e;o.parentNode;)o=o.parentNode;for(var a=o.querySelectorAll("input[name="+JSON.stringify(""+r)+'][type="radio"]'),i=0;i<a.length;i++){var l=a[i];if(l!==e&&l.form===e.form){var u=ge(l);u||t(!1,"ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."),yr(l),_o(l,u)}}}}(r,n)}function Ro(e,t,n){"number"===t&&e.ownerDocument.activeElement===e||(null==n?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}function No(e){switch(typeof e){case"boolean":case"number":case"object":case"string":case"undefined":return e;default:return""}}var Oo={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:[ze,qe,$e,ht,vt,yt,wt,Yt]}};function Io(e,t,n){var r=Sn.getPooled(Oo.change,e,t,n);return r.type="change",Xn(n),Pe(r),r}var Uo=null,Ao=null;function Do(e){Y(e,!1)}function Mo(e){if(yr(ve(e)))return e}function Fo(e,t){if(e===qe)return t}var jo=!1;function Lo(){Uo&&(Uo.detachEvent("onpropertychange",Wo),Uo=null,Ao=null)}function Wo(e){"value"===e.propertyName&&Mo(Ao)&&function(e){or(Do,Io(Ao,e,pr(e)))}(e)}function zo(e,t,n){e===ht?(Lo(),function(e,t){Ao=t,(Uo=e).attachEvent("onpropertychange",Wo)}(t,n)):e===ze&&Lo()}function Bo(e,t){if(e===Yt||e===wt||e===yt)return Mo(Ao)}function Vo(e,t){if(e===$e)return Mo(t)}function Ho(e,t){if(e===vt||e===qe)return Mo(t)}a.canUseDOM&&(jo=hr("input")&&(!document.documentMode||document.documentMode>9));var qo={eventTypes:Oo,_isInputEventSupported:jo,extractEvents:function(e,t,n,r){var o=t?ve(t):window,a=void 0,i=void 0;if(!function(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}(o)?lr(o)?jo?a=Ho:(a=Bo,i=zo):function(e){var t=e.nodeName;return t&&"input"===t.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}(o)&&(a=Vo):a=Fo,a){var l=a(e,t);if(l)return Io(l,n,r)}i&&i(e,o,t),e===ze&&function(e){var t=e._wrapperState;t&&t.controlled&&"number"===e.type&&Ro(e,"number",e.value)}(o)}},$o=Sn.extend({view:null,detail:null}),Yo={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Qo(e){var t=this.nativeEvent;if(t.getModifierState)return t.getModifierState(e);var n=Yo[e];return!!n&&!!t[n]}function Ko(e){return Qo}var Xo=$o.extend({screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:Ko,button:null,buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)}}),Go=Xo.extend({pointerId:null,width:null,height:null,pressure:null,tiltX:null,tiltY:null,pointerType:null,isPrimary:null}),Zo={mouseEnter:{registrationName:"onMouseEnter",dependencies:[Pt,Rt]},mouseLeave:{registrationName:"onMouseLeave",dependencies:[Pt,Rt]},pointerEnter:{registrationName:"onPointerEnter",dependencies:[jt,Lt]},pointerLeave:{registrationName:"onPointerLeave",dependencies:[jt,Lt]}},Jo={eventTypes:Zo,extractEvents:function(e,t,n,r){var o=e===Rt||e===Lt,a=e===Pt||e===jt;if(o&&(n.relatedTarget||n.fromElement))return null;if(!a&&!o)return null;var i=void 0;if(r.window===r)i=r;else{var l=r.ownerDocument;i=l?l.defaultView||l.parentWindow:window}var u=void 0,s=void 0;if(a){u=t;var c=n.relatedTarget||n.toElement;s=c?he(c):null}else u=null,s=t;if(u===s)return null;var d=void 0,f=void 0,p=void 0,h=void 0;e===Pt||e===Rt?(d=Xo,f=Zo.mouseLeave,p=Zo.mouseEnter,h="mouse"):e!==jt&&e!==Lt||(d=Go,f=Zo.pointerLeave,p=Zo.pointerEnter,h="pointer");var m=null==u?i:ve(u),v=null==s?i:ve(s),g=d.getPooled(f,u,n,r);g.type=h+"leave",g.target=m,g.relatedTarget=v;var y=d.getPooled(p,s,n,r);return y.type=h+"enter",y.target=v,y.relatedTarget=m,Re(g,y,u,s),[g,y]}};function ea(e){return e._reactInternalFiber}var ta=0,na=1,ra=2,oa=4,aa=6,ia=8,la=16,ua=32,sa=64,ca=128,da=256,fa=511,pa=512,ha=1024,ma=1,va=2,ga=3;function ya(e){var t=e;if(e.alternate)for(;t.return;)t=t.return;else{if((t.effectTag&ra)!==ta)return ma;for(;t.return;)if(((t=t.return).effectTag&ra)!==ta)return ma}return t.tag===J?va:ga}function ba(e){return ya(e)===va}function wa(e){ya(e)!==va&&t(!1,"Unable to find node on an unmounted component.")}function ka(e){var n=e.alternate;if(!n){var r=ya(e);return r===ga&&t(!1,"Unable to find node on an unmounted component."),r===ma?null:e}for(var o=e,a=n;;){var i=o.return,l=i?i.alternate:null;if(!i||!l)break;if(i.child===l.child){for(var u=i.child;u;){if(u===o)return wa(i),e;if(u===a)return wa(i),n;u=u.sibling}t(!1,"Unable to find node on an unmounted component.")}if(o.return!==a.return)o=i,a=l;else{for(var s=!1,c=i.child;c;){if(c===o){s=!0,o=i,a=l;break}if(c===a){s=!0,a=i,o=l;break}c=c.sibling}if(!s){for(c=l.child;c;){if(c===o){s=!0,o=l,a=i;break}if(c===a){s=!0,a=l,o=i;break}c=c.sibling}s||t(!1,"Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.")}}o.alternate!==a&&t(!1,"Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.")}return o.tag!==J&&t(!1,"Unable to find node on an unmounted component."),o.stateNode.current===o?e:n}function xa(e){var t=ka(e);if(!t)return null;for(var n=t;;){if(n.tag===te||n.tag===ne)return n;if(n.child)n.child.return=n,n=n.child;else{if(n===t)return null;for(;!n.sibling;){if(!n.return||n.return===t)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}}return null}var Ta=Sn.extend({animationName:null,elapsedTime:null,pseudoElement:null}),Ca=Sn.extend({clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),Sa=$o.extend({relatedTarget:null});function _a(e){var t=void 0,n=e.keyCode;return"charCode"in e?0===(t=e.charCode)&&13===n&&(t=13):t=n,10===t&&(t=13),t>=32||13===t?t:0}var Ea={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Pa={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};var Ra=$o.extend({key:function(e){if(e.key){var t=Ea[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=_a(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?Pa[e.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:Ko,charCode:function(e){return"keypress"===e.type?_a(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?_a(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),Na=Xo.extend({dataTransfer:null}),Oa=$o.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:Ko}),Ia=Sn.extend({propertyName:null,elapsedTime:null,pseudoElement:null}),Ua=Xo.extend({deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null}),Aa=[[Fe,"abort"],[je,"animationEnd"],[Le,"animationIteration"],[We,"animationStart"],[Be,"canPlay"],[Ve,"canPlayThrough"],[tt,"drag"],[rt,"dragEnter"],[ot,"dragExit"],[at,"dragLeave"],[it,"dragOver"],[st,"durationChange"],[ct,"emptied"],[dt,"encrypted"],[ft,"ended"],[pt,"error"],[mt,"gotPointerCapture"],[kt,"load"],[Tt,"loadedData"],[Ct,"loadedMetadata"],[xt,"loadStart"],[St,"lostPointerCapture"],[Et,"mouseMove"],[Pt,"mouseOut"],[Rt,"mouseOver"],[At,"playing"],[Ft,"pointerMove"],[jt,"pointerOut"],[Lt,"pointerOver"],[zt,"progress"],[Ht,"scroll"],[$t,"seeking"],[Qt,"stalled"],[Xt,"suspend"],[Zt,"timeUpdate"],[Jt,"toggle"],[nn,"touchMove"],[on,"transitionEnd"],[ln,"waiting"],[un,"wheel"]],Da={},Ma={};function Fa(e,t){var n=e[0],r=e[1],o="on"+(r[0].toUpperCase()+r.slice(1)),a={phasedRegistrationNames:{bubbled:o,captured:o+"Capture"},dependencies:[n],isInteractive:t};Da[r]=a,Ma[n]=a}[[ze,"blur"],[He,"cancel"],[$e,"click"],[Ye,"close"],[Ge,"contextMenu"],[Ze,"copy"],[Je,"cut"],[et,"doubleClick"],[nt,"dragEnd"],[lt,"dragStart"],[ut,"drop"],[ht,"focus"],[vt,"input"],[gt,"invalid"],[yt,"keyDown"],[bt,"keyPress"],[wt,"keyUp"],[_t,"mouseDown"],[Nt,"mouseUp"],[Ot,"paste"],[It,"pause"],[Ut,"play"],[Dt,"pointerCancel"],[Mt,"pointerDown"],[Wt,"pointerUp"],[Bt,"rateChange"],[Vt,"reset"],[qt,"seeked"],[Kt,"submit"],[en,"touchCancel"],[tn,"touchEnd"],[rn,"touchStart"],[an,"volumeChange"]].forEach(function(e){Fa(e,!0)}),Aa.forEach(function(e){Fa(e,!1)});var ja=[Fe,He,Be,Ve,Ye,st,ct,dt,ft,pt,vt,gt,kt,Tt,Ct,xt,It,Ut,At,zt,Bt,Vt,qt,$t,Qt,Kt,Xt,Zt,Jt,an,ln],La={eventTypes:Da,isInteractiveTopLevelEventType:function(e){var t=Ma[e];return void 0!==t&&!0===t.isInteractive},extractEvents:function(e,t,n,r){var a=Ma[e];if(!a)return null;var i=void 0;switch(e){case bt:if(0===_a(n))return null;case yt:case wt:i=Ra;break;case ze:case ht:i=Sa;break;case $e:if(2===n.button)return null;case et:case _t:case Et:case Nt:case Pt:case Rt:case Ge:i=Xo;break;case tt:case nt:case rt:case ot:case at:case it:case lt:case ut:i=Na;break;case en:case tn:case nn:case rn:i=Oa;break;case je:case Le:case We:i=Ta;break;case on:i=Ia;break;case Ht:i=$o;break;case un:i=Ua;break;case Ze:case Je:case Ot:i=Ca;break;case mt:case St:case Dt:case Mt:case Ft:case jt:case Lt:case Wt:i=Go;break;default:-1===ja.indexOf(e)&&o(!1,"SimpleEventPlugin: Unhandled event type, `%s`. This warning is likely caused by a bug in React. Please file an issue.",e),i=Sn}var l=i.getPooled(a,t,n,r);return Pe(l),l}},Wa=La.isInteractiveTopLevelEventType,za=10,Ba=[];function Va(e){for(;e.return;)e=e.return;return e.tag!==J?null:e.stateNode.containerInfo}function Ha(e){var t=e.targetInst,n=t;do{if(!n){e.ancestors.push(n);break}var r=Va(n);if(!r)break;e.ancestors.push(n),n=he(r)}while(n);for(var o=0;o<e.ancestors.length;o++)t=e.ancestors[o],Q(e.topLevelType,t,e.nativeEvent,pr(e.nativeEvent))}var qa=!0;function $a(e){qa=!!e}function Ya(){return qa}function Qa(e,t){if(!t)return null;var n=Wa(e)?Xa:Ga;!function(e,t,n){e.addEventListener(t,n,!1)}(t,cn(e),n.bind(null,e))}function Ka(e,t){if(!t)return null;var n=Wa(e)?Xa:Ga;!function(e,t,n){e.addEventListener(t,n,!0)}(t,cn(e),n.bind(null,e))}function Xa(e,t){!function(e,t,n){tr(e,t,n)}(Ga,e,t)}function Ga(e,t){if(qa){var n=he(pr(t));null===n||"number"!=typeof n.tag||ba(n)||(n=null);var r=function(e,t,n){if(Ba.length){var r=Ba.pop();return r.topLevelType=e,r.nativeEvent=t,r.targetInst=n,r}return{topLevelType:e,nativeEvent:t,targetInst:n,ancestors:[]}}(e,t,n);try{or(Ha,r)}finally{!function(e){e.topLevelType=null,e.nativeEvent=null,e.targetInst=null,e.ancestors.length=0,Ba.length<za&&Ba.push(e)}(r)}}}var Za=Object.freeze({get _enabled(){return qa},setEnabled:$a,isEnabled:Ya,trapBubbledEvent:Qa,trapCapturedEvent:Ka,dispatchEvent:Ga}),Ja={},ei=0,ti="_reactListenersID"+(""+Math.random()).slice(2);function ni(e){return Object.prototype.hasOwnProperty.call(e,ti)||(e[ti]=ei++,Ja[e[ti]]={}),Ja[e[ti]]}function ri(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function oi(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function ai(e,t){for(var n=ri(e),r=0,o=0;n;){if(n.nodeType===sr){if(o=r+n.textContent.length,r<=t&&o>=t)return{node:n,offset:t-r};r=o}n=ri(oi(n))}}function ii(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,r=t.anchorOffset,o=t.focusNode,a=t.focusOffset;try{n.nodeType,o.nodeType}catch(e){return null}return function(e,t,n,r,o){var a=0,i=-1,l=-1,u=0,s=0,c=e,d=null;e:for(;;){for(var f=null;c!==t||0!==n&&c.nodeType!==sr||(i=a+n),c!==r||0!==o&&c.nodeType!==sr||(l=a+o),c.nodeType===sr&&(a+=c.nodeValue.length),null!==(f=c.firstChild);)d=c,c=f;for(;;){if(c===e)break e;if(d===t&&++u===n&&(i=a),d===r&&++s===o&&(l=a),null!==(f=c.nextSibling))break;d=(c=d).parentNode}c=f}if(-1===i||-1===l)return null;return{start:i,end:l}}(e,n,r,o,a)}function li(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}function ui(){var e=s();return{focusedElem:e,selectionRange:li(e)?function(e){var t=void 0;t="selectionStart"in e?{start:e.selectionStart,end:e.selectionEnd}:ii(e);return t||{start:0,end:0}}(e):null}}function si(e){var t=s(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&function(e){return d(document.documentElement,e)}(n)){null!==r&&li(n)&&function(e,t){var n=t.start,r=t.end;void 0===r&&(r=n);"selectionStart"in e?(e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length)):function(e,t){if(window.getSelection){var n=window.getSelection(),r=e[fn()].length,o=Math.min(t.start,r),a=void 0===t.end?o:Math.min(t.end,r);if(!n.extend&&o>a){var i=a;a=o,o=i}var l=ai(e,o),u=ai(e,a);if(l&&u){if(1===n.rangeCount&&n.anchorNode===l.node&&n.anchorOffset===l.offset&&n.focusNode===u.node&&n.focusOffset===u.offset)return;var s=document.createRange();s.setStart(l.node,l.offset),n.removeAllRanges(),o>a?(n.addRange(s),n.extend(u.node,u.offset)):(s.setEnd(u.node,u.offset),n.addRange(s))}}}(e,t)}(n,r);for(var o=[],a=n;a=a.parentNode;)a.nodeType===ur&&o.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"==typeof n.focus&&n.focus();for(var i=0;i<o.length;i++){var l=o[i];l.element.scrollLeft=l.left,l.element.scrollTop=l.top}}}var ci=a.canUseDOM&&"documentMode"in document&&document.documentMode<=11,di={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:[ze,Ge,ht,yt,wt,_t,Nt,Yt]}},fi=null,pi=null,hi=null,mi=!1;function vi(e,t){if(mi||null==fi||fi!==s())return null;var n=function(e){if("selectionStart"in e&&li(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}}(fi);if(!hi||!c(hi,n)){hi=n;var r=Sn.getPooled(di.select,pi,e,t);return r.type="select",r.target=fi,Pe(r),r}return null}var gi={eventTypes:di,extractEvents:function(e,t,n,r){var o=r.window===r?r.document:r.nodeType===dr?r:r.ownerDocument;if(!o||!function(e,t){for(var n=ni(t),r=P[e],o=0;o<r.length;o++){var a=r[o];if(!n.hasOwnProperty(a)||!n[a])return!1}return!0}("onSelect",o))return null;var a=t?ve(t):window;switch(e){case ht:(lr(a)||"true"===a.contentEditable)&&(fi=a,pi=t,hi=null);break;case ze:fi=null,pi=null,hi=null;break;case _t:mi=!0;break;case Ge:case Nt:return mi=!1,vi(n,r);case Yt:if(ci)break;case yt:case wt:return vi(n,r)}return null}};q.injectEventPluginOrder(["ResponderEventPlugin","SimpleEventPlugin","TapEventPlugin","EnterLeaveEventPlugin","ChangeEventPlugin","SelectEventPlugin","BeforeInputEventPlugin"]),M(be),q.injectEventPluginsByName({SimpleEventPlugin:La,EnterLeaveEventPlugin:Jo,ChangeEventPlugin:qo,SelectEventPlugin:gi,BeforeInputEventPlugin:Hn});var yi="function"==typeof requestAnimationFrame?requestAnimationFrame:void 0,bi=Date,wi=setTimeout,ki=clearTimeout,xi=void 0;if("object"==typeof performance&&"function"==typeof performance.now){var Ti=performance;xi=function(){return Ti.now()}}else xi=function(){return bi.now()};var Ci=void 0,Si=void 0;if(a.canUseDOM){"function"!=typeof yi&&o(!1,"React depends on requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills");var _i="function"==typeof yi?yi:function(e){t(!1,"React depends on requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills")},Ei=null,Pi=null,Ri=-1,Ni=!1,Oi=!1,Ii=0,Ui=33,Ai=33,Di={didTimeout:!1,timeRemaining:function(){var e=Ii-xi();return e>0?e:0}},Mi=function(e,t){var n=e.scheduledCallback,r=!1;try{n(t),r=!0}finally{Si(e),r||(Ni=!0,window.postMessage(Fi,"*"))}},Fi="__reactIdleCallback$"+Math.random().toString(36).slice(2);window.addEventListener("message",function(e){if(e.source===window&&e.data===Fi&&(Ni=!1,null!==Ei)){!function(){if(null!==Ei){var e=xi();if(!(-1===Ri||Ri>e)){for(var t=-1,n=[],r=Ei;null!==r;){var o=r.timeoutTime;-1!==o&&o<=e?n.push(r):-1!==o&&(-1===t||o<t)&&(t=o),r=r.next}if(n.length>0){Di.didTimeout=!0;for(var a=0,i=n.length;a<i;a++)Mi(n[a],Di)}Ri=t}}}();for(var t=xi();Ii-t>0&&null!==Ei;){var n=Ei;Di.didTimeout=!1,Mi(n,Di),t=xi()}null!==Ei&&(Oi||(Oi=!0,_i(ji)))}},!1);var ji=function(e){Oi=!1;var t=e-Ii+Ai;t<Ai&&Ui<Ai?(t<8&&(t=8),Ai=t<Ui?Ui:t):Ui=t,Ii=e+Ai,Ni||(Ni=!0,window.postMessage(Fi,"*"))};Ci=function(e,t){var n=-1;null!=t&&"number"==typeof t.timeout&&(n=xi()+t.timeout),(-1===Ri||-1!==n&&n<Ri)&&(Ri=n);var r={scheduledCallback:e,timeoutTime:n,prev:null,next:null};if(null===Ei)Ei=r,Pi=r;else{r.prev=Pi;null!==Pi&&(Pi.next=r),Pi=r}return Oi||(Oi=!0,_i(ji)),r},Si=function(e){if(null!==e.prev||Ei===e){var t=e.next,n=e.prev;return e.next=null,e.prev=null,null!==t?null!==n?(n.next=t,void(t.prev=n)):(t.prev=null,void(Ei=t)):null!==n?(n.next=null,void(Pi=n)):(Ei=null,void(Pi=null))}}}else{var Li=new Map;Ci=function(e,t){var n={scheduledCallback:e,timeoutTime:0,next:null,prev:null},r=wi(function(){e({timeRemaining:function(){return 1/0},didTimeout:!1})});return Li.set(e,r),n},Si=function(e){var t=e.scheduledCallback,n=Li.get(t);Li.delete(e),ki(n)}}var Wi=!1;function zi(e,t){null==t.selected||Wi||(o(!1,"Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."),Wi=!0)}function Bi(e,t){var n=i({children:void 0},t),o=function(e){var t="";return r.Children.forEach(e,function(e){null!=e&&("string"!=typeof e&&"number"!=typeof e||(t+=e))}),t}(t.children);return o&&(n.children=o),n}var Vi=zr.getCurrentFiberOwnerName,Hi=zr.getCurrentFiberStackAddendum,qi=void 0;function $i(){var e=Vi();return e?"\n\nCheck the render method of `"+e+"`.":""}qi=!1;var Yi=["value","defaultValue"];function Qi(e,t,n,r){var o=e.options;if(t){for(var a=n,i={},l=0;l<a.length;l++)i["$"+a[l]]=!0;for(var u=0;u<o.length;u++){var s=i.hasOwnProperty("$"+o[u].value);o[u].selected!==s&&(o[u].selected=s),s&&r&&(o[u].defaultSelected=!0)}}else{for(var c=""+n,d=null,f=0;f<o.length;f++){if(o[f].value===c)return o[f].selected=!0,void(r&&(o[f].defaultSelected=!0));null!==d||o[f].disabled||(d=o[f])}null!==d&&(d.selected=!0)}}function Ki(e,t){return i({},t,{value:void 0})}function Xi(e,t){var n=e;!function(e){po.checkPropTypes("select",e,Hi);for(var t=0;t<Yi.length;t++){var n=Yi[t];if(null!=e[n]){var r=Array.isArray(e[n]);e.multiple&&!r?o(!1,"The `%s` prop supplied to <select> must be an array if `multiple` is true.%s",n,$i()):!e.multiple&&r&&o(!1,"The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s",n,$i())}}}(t);var r=t.value;n._wrapperState={initialValue:null!=r?r:t.defaultValue,wasMultiple:!!t.multiple},void 0===t.value||void 0===t.defaultValue||qi||(o(!1,"Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://fb.me/react-controlled-components"),qi=!0)}var Gi=zr.getCurrentFiberStackAddendum,Zi=!1;function Ji(e,n){var r=e;return null!=n.dangerouslySetInnerHTML&&t(!1,"`dangerouslySetInnerHTML` does not make sense on <textarea>."),i({},n,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function el(e,n){var r=e;po.checkPropTypes("textarea",n,Gi),void 0===n.value||void 0===n.defaultValue||Zi||(o(!1,"Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://fb.me/react-controlled-components"),Zi=!0);var a=n.value;if(null==a){var i=n.defaultValue,l=n.children;null!=l&&(o(!1,"Use the `defaultValue` or `value` props instead of setting children on <textarea>."),null!=i&&t(!1,"If you supply `defaultValue` on a <textarea>, do not pass children."),Array.isArray(l)&&(l.length<=1||t(!1,"<textarea> can only have at most one child."),l=l[0]),i=""+l),null==i&&(i=""),a=i}r._wrapperState={initialValue:""+a}}function tl(e,t){var n=e,r=t.value;if(null!=r){var o=""+r;o!==n.value&&(n.value=o),null==t.defaultValue&&(n.defaultValue=o)}null!=t.defaultValue&&(n.defaultValue=t.defaultValue)}function nl(e,t){var n=e,r=n.textContent;r===n._wrapperState.initialValue&&(n.value=r)}var rl="http://www.w3.org/1999/xhtml",ol="http://www.w3.org/1998/Math/MathML",al="http://www.w3.org/2000/svg",il={html:rl,mathml:ol,svg:al};function ll(e){switch(e){case"svg":return al;case"math":return ol;default:return rl}}function ul(e,t){return null==e||e===rl?ll(t):e===al&&"foreignObject"===t?rl:e}var sl=void 0,cl=function(e){return"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(t,n,r,o){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,o)})}:e}(function(e,t){if(e.namespaceURI!==il.svg||"innerHTML"in e)e.innerHTML=t;else{(sl=sl||document.createElement("div")).innerHTML="<svg>"+t+"</svg>";for(var n=sl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}}),dl=function(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===sr)return void(n.nodeValue=t)}e.textContent=t},fl={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0};var pl=["Webkit","ms","Moz","O"];function hl(e,t,n){return null==t||"boolean"==typeof t||""===t?"":n||"number"!=typeof t||0===t||fl.hasOwnProperty(e)&&fl[e]?(""+t).trim():t+"px"}Object.keys(fl).forEach(function(e){pl.forEach(function(t){fl[function(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}(t,e)]=fl[e]})});var ml=/^(?:webkit|moz|o)[A-Z]/,vl=/;\s*$/,gl={},yl={},bl=!1,wl=!1,kl=function(e,t,n){e.indexOf("-")>-1?function(e,t){gl.hasOwnProperty(e)&&gl[e]||(gl[e]=!0,o(!1,"Unsupported style property %s. Did you mean %s?%s",e,h(e),t()))}(e,n):ml.test(e)?function(e,t){gl.hasOwnProperty(e)&&gl[e]||(gl[e]=!0,o(!1,"Unsupported vendor-prefixed style property %s. Did you mean %s?%s",e,e.charAt(0).toUpperCase()+e.slice(1),t()))}(e,n):vl.test(t)&&function(e,t,n){yl.hasOwnProperty(t)&&yl[t]||(yl[t]=!0,o(!1,'Style property values shouldn\'t contain a semicolon. Try "%s: %s" instead.%s',e,t.replace(vl,""),n()))}(e,t,n),"number"==typeof t&&(isNaN(t)?function(e,t,n){bl||(bl=!0,o(!1,"`NaN` is an invalid value for the `%s` css style property.%s",e,n()))}(e,0,n):isFinite(t)||function(e,t,n){wl||(wl=!0,o(!1,"`Infinity` is an invalid value for the `%s` css style property.%s",e,n()))}(e,0,n))};function xl(e){var t="",n="";for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];if(null!=o){var a=0===r.indexOf("--");t+=n+p(r)+":",t+=hl(r,o,a),n=";"}}return t||null}function Tl(e,t,n){var r=e.style;for(var o in t)if(t.hasOwnProperty(o)){var a=0===o.indexOf("--");a||kl(o,t[o],n);var i=hl(o,t[o],a);"float"===o&&(o="cssFloat"),a?r.setProperty(o,i):r[o]=i}}var Cl=i({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}),Sl="__html";function _l(e,n,r){n&&(Cl[e]&&(null!=n.children||null!=n.dangerouslySetInnerHTML)&&t(!1,"%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s",e,r()),null!=n.dangerouslySetInnerHTML&&(null!=n.children&&t(!1,"Can only set one of `children` or `props.dangerouslySetInnerHTML`."),"object"==typeof n.dangerouslySetInnerHTML&&Sl in n.dangerouslySetInnerHTML||t(!1,"`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.")),!n.suppressContentEditableWarning&&n.contentEditable&&null!=n.children&&o(!1,"A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.%s",r()),null!=n.style&&"object"!=typeof n.style&&t(!1,"The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.%s",r()))}function El(e,t){if(-1===e.indexOf("-"))return"string"==typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Pl={accept:"accept",acceptcharset:"acceptCharset","accept-charset":"acceptCharset",accesskey:"accessKey",action:"action",allowfullscreen:"allowFullScreen",alt:"alt",as:"as",async:"async",autocapitalize:"autoCapitalize",autocomplete:"autoComplete",autocorrect:"autoCorrect",autofocus:"autoFocus",autoplay:"autoPlay",autosave:"autoSave",capture:"capture",cellpadding:"cellPadding",cellspacing:"cellSpacing",challenge:"challenge",charset:"charSet",checked:"checked",children:"children",cite:"cite",class:"className",classid:"classID",classname:"className",cols:"cols",colspan:"colSpan",content:"content",contenteditable:"contentEditable",contextmenu:"contextMenu",controls:"controls",controlslist:"controlsList",coords:"coords",crossorigin:"crossOrigin",dangerouslysetinnerhtml:"dangerouslySetInnerHTML",data:"data",datetime:"dateTime",default:"default",defaultchecked:"defaultChecked",defaultvalue:"defaultValue",defer:"defer",dir:"dir",disabled:"disabled",download:"download",draggable:"draggable",enctype:"encType",for:"htmlFor",form:"form",formmethod:"formMethod",formaction:"formAction",formenctype:"formEncType",formnovalidate:"formNoValidate",formtarget:"formTarget",frameborder:"frameBorder",headers:"headers",height:"height",hidden:"hidden",high:"high",href:"href",hreflang:"hrefLang",htmlfor:"htmlFor",httpequiv:"httpEquiv","http-equiv":"httpEquiv",icon:"icon",id:"id",innerhtml:"innerHTML",inputmode:"inputMode",integrity:"integrity",is:"is",itemid:"itemID",itemprop:"itemProp",itemref:"itemRef",itemscope:"itemScope",itemtype:"itemType",keyparams:"keyParams",keytype:"keyType",kind:"kind",label:"label",lang:"lang",list:"list",loop:"loop",low:"low",manifest:"manifest",marginwidth:"marginWidth",marginheight:"marginHeight",max:"max",maxlength:"maxLength",media:"media",mediagroup:"mediaGroup",method:"method",min:"min",minlength:"minLength",multiple:"multiple",muted:"muted",name:"name",nomodule:"noModule",nonce:"nonce",novalidate:"noValidate",open:"open",optimum:"optimum",pattern:"pattern",placeholder:"placeholder",playsinline:"playsInline",poster:"poster",preload:"preload",profile:"profile",radiogroup:"radioGroup",readonly:"readOnly",referrerpolicy:"referrerPolicy",rel:"rel",required:"required",reversed:"reversed",role:"role",rows:"rows",rowspan:"rowSpan",sandbox:"sandbox",scope:"scope",scoped:"scoped",scrolling:"scrolling",seamless:"seamless",selected:"selected",shape:"shape",size:"size",sizes:"sizes",span:"span",spellcheck:"spellCheck",src:"src",srcdoc:"srcDoc",srclang:"srcLang",srcset:"srcSet",start:"start",step:"step",style:"style",summary:"summary",tabindex:"tabIndex",target:"target",title:"title",type:"type",usemap:"useMap",value:"value",width:"width",wmode:"wmode",wrap:"wrap",about:"about",accentheight:"accentHeight","accent-height":"accentHeight",accumulate:"accumulate",additive:"additive",alignmentbaseline:"alignmentBaseline","alignment-baseline":"alignmentBaseline",allowreorder:"allowReorder",alphabetic:"alphabetic",amplitude:"amplitude",arabicform:"arabicForm","arabic-form":"arabicForm",ascent:"ascent",attributename:"attributeName",attributetype:"attributeType",autoreverse:"autoReverse",azimuth:"azimuth",basefrequency:"baseFrequency",baselineshift:"baselineShift","baseline-shift":"baselineShift",baseprofile:"baseProfile",bbox:"bbox",begin:"begin",bias:"bias",by:"by",calcmode:"calcMode",capheight:"capHeight","cap-height":"capHeight",clip:"clip",clippath:"clipPath","clip-path":"clipPath",clippathunits:"clipPathUnits",cliprule:"clipRule","clip-rule":"clipRule",color:"color",colorinterpolation:"colorInterpolation","color-interpolation":"colorInterpolation",colorinterpolationfilters:"colorInterpolationFilters","color-interpolation-filters":"colorInterpolationFilters",colorprofile:"colorProfile","color-profile":"colorProfile",colorrendering:"colorRendering","color-rendering":"colorRendering",contentscripttype:"contentScriptType",contentstyletype:"contentStyleType",cursor:"cursor",cx:"cx",cy:"cy",d:"d",datatype:"datatype",decelerate:"decelerate",descent:"descent",diffuseconstant:"diffuseConstant",direction:"direction",display:"display",divisor:"divisor",dominantbaseline:"dominantBaseline","dominant-baseline":"dominantBaseline",dur:"dur",dx:"dx",dy:"dy",edgemode:"edgeMode",elevation:"elevation",enablebackground:"enableBackground","enable-background":"enableBackground",end:"end",exponent:"exponent",externalresourcesrequired:"externalResourcesRequired",fill:"fill",fillopacity:"fillOpacity","fill-opacity":"fillOpacity",fillrule:"fillRule","fill-rule":"fillRule",filter:"filter",filterres:"filterRes",filterunits:"filterUnits",floodopacity:"floodOpacity","flood-opacity":"floodOpacity",floodcolor:"floodColor","flood-color":"floodColor",focusable:"focusable",fontfamily:"fontFamily","font-family":"fontFamily",fontsize:"fontSize","font-size":"fontSize",fontsizeadjust:"fontSizeAdjust","font-size-adjust":"fontSizeAdjust",fontstretch:"fontStretch","font-stretch":"fontStretch",fontstyle:"fontStyle","font-style":"fontStyle",fontvariant:"fontVariant","font-variant":"fontVariant",fontweight:"fontWeight","font-weight":"fontWeight",format:"format",from:"from",fx:"fx",fy:"fy",g1:"g1",g2:"g2",glyphname:"glyphName","glyph-name":"glyphName",glyphorientationhorizontal:"glyphOrientationHorizontal","glyph-orientation-horizontal":"glyphOrientationHorizontal",glyphorientationvertical:"glyphOrientationVertical","glyph-orientation-vertical":"glyphOrientationVertical",glyphref:"glyphRef",gradienttransform:"gradientTransform",gradientunits:"gradientUnits",hanging:"hanging",horizadvx:"horizAdvX","horiz-adv-x":"horizAdvX",horizoriginx:"horizOriginX","horiz-origin-x":"horizOriginX",ideographic:"ideographic",imagerendering:"imageRendering","image-rendering":"imageRendering",in2:"in2",in:"in",inlist:"inlist",intercept:"intercept",k1:"k1",k2:"k2",k3:"k3",k4:"k4",k:"k",kernelmatrix:"kernelMatrix",kernelunitlength:"kernelUnitLength",kerning:"kerning",keypoints:"keyPoints",keysplines:"keySplines",keytimes:"keyTimes",lengthadjust:"lengthAdjust",letterspacing:"letterSpacing","letter-spacing":"letterSpacing",lightingcolor:"lightingColor","lighting-color":"lightingColor",limitingconeangle:"limitingConeAngle",local:"local",markerend:"markerEnd","marker-end":"markerEnd",markerheight:"markerHeight",markermid:"markerMid","marker-mid":"markerMid",markerstart:"markerStart","marker-start":"markerStart",markerunits:"markerUnits",markerwidth:"markerWidth",mask:"mask",maskcontentunits:"maskContentUnits",maskunits:"maskUnits",mathematical:"mathematical",mode:"mode",numoctaves:"numOctaves",offset:"offset",opacity:"opacity",operator:"operator",order:"order",orient:"orient",orientation:"orientation",origin:"origin",overflow:"overflow",overlineposition:"overlinePosition","overline-position":"overlinePosition",overlinethickness:"overlineThickness","overline-thickness":"overlineThickness",paintorder:"paintOrder","paint-order":"paintOrder",panose1:"panose1","panose-1":"panose1",pathlength:"pathLength",patterncontentunits:"patternContentUnits",patterntransform:"patternTransform",patternunits:"patternUnits",pointerevents:"pointerEvents","pointer-events":"pointerEvents",points:"points",pointsatx:"pointsAtX",pointsaty:"pointsAtY",pointsatz:"pointsAtZ",prefix:"prefix",preservealpha:"preserveAlpha",preserveaspectratio:"preserveAspectRatio",primitiveunits:"primitiveUnits",property:"property",r:"r",radius:"radius",refx:"refX",refy:"refY",renderingintent:"renderingIntent","rendering-intent":"renderingIntent",repeatcount:"repeatCount",repeatdur:"repeatDur",requiredextensions:"requiredExtensions",requiredfeatures:"requiredFeatures",resource:"resource",restart:"restart",result:"result",results:"results",rotate:"rotate",rx:"rx",ry:"ry",scale:"scale",security:"security",seed:"seed",shaperendering:"shapeRendering","shape-rendering":"shapeRendering",slope:"slope",spacing:"spacing",specularconstant:"specularConstant",specularexponent:"specularExponent",speed:"speed",spreadmethod:"spreadMethod",startoffset:"startOffset",stddeviation:"stdDeviation",stemh:"stemh",stemv:"stemv",stitchtiles:"stitchTiles",stopcolor:"stopColor","stop-color":"stopColor",stopopacity:"stopOpacity","stop-opacity":"stopOpacity",strikethroughposition:"strikethroughPosition","strikethrough-position":"strikethroughPosition",strikethroughthickness:"strikethroughThickness","strikethrough-thickness":"strikethroughThickness",string:"string",stroke:"stroke",strokedasharray:"strokeDasharray","stroke-dasharray":"strokeDasharray",strokedashoffset:"strokeDashoffset","stroke-dashoffset":"strokeDashoffset",strokelinecap:"strokeLinecap","stroke-linecap":"strokeLinecap",strokelinejoin:"strokeLinejoin","stroke-linejoin":"strokeLinejoin",strokemiterlimit:"strokeMiterlimit","stroke-miterlimit":"strokeMiterlimit",strokewidth:"strokeWidth","stroke-width":"strokeWidth",strokeopacity:"strokeOpacity","stroke-opacity":"strokeOpacity",suppresscontenteditablewarning:"suppressContentEditableWarning",suppresshydrationwarning:"suppressHydrationWarning",surfacescale:"surfaceScale",systemlanguage:"systemLanguage",tablevalues:"tableValues",targetx:"targetX",targety:"targetY",textanchor:"textAnchor","text-anchor":"textAnchor",textdecoration:"textDecoration","text-decoration":"textDecoration",textlength:"textLength",textrendering:"textRendering","text-rendering":"textRendering",to:"to",transform:"transform",typeof:"typeof",u1:"u1",u2:"u2",underlineposition:"underlinePosition","underline-position":"underlinePosition",underlinethickness:"underlineThickness","underline-thickness":"underlineThickness",unicode:"unicode",unicodebidi:"unicodeBidi","unicode-bidi":"unicodeBidi",unicoderange:"unicodeRange","unicode-range":"unicodeRange",unitsperem:"unitsPerEm","units-per-em":"unitsPerEm",unselectable:"unselectable",valphabetic:"vAlphabetic","v-alphabetic":"vAlphabetic",values:"values",vectoreffect:"vectorEffect","vector-effect":"vectorEffect",version:"version",vertadvy:"vertAdvY","vert-adv-y":"vertAdvY",vertoriginx:"vertOriginX","vert-origin-x":"vertOriginX",vertoriginy:"vertOriginY","vert-origin-y":"vertOriginY",vhanging:"vHanging","v-hanging":"vHanging",videographic:"vIdeographic","v-ideographic":"vIdeographic",viewbox:"viewBox",viewtarget:"viewTarget",visibility:"visibility",vmathematical:"vMathematical","v-mathematical":"vMathematical",vocab:"vocab",widths:"widths",wordspacing:"wordSpacing","word-spacing":"wordSpacing",writingmode:"writingMode","writing-mode":"writingMode",x1:"x1",x2:"x2",x:"x",xchannelselector:"xChannelSelector",xheight:"xHeight","x-height":"xHeight",xlinkactuate:"xlinkActuate","xlink:actuate":"xlinkActuate",xlinkarcrole:"xlinkArcrole","xlink:arcrole":"xlinkArcrole",xlinkhref:"xlinkHref","xlink:href":"xlinkHref",xlinkrole:"xlinkRole","xlink:role":"xlinkRole",xlinkshow:"xlinkShow","xlink:show":"xlinkShow",xlinktitle:"xlinkTitle","xlink:title":"xlinkTitle",xlinktype:"xlinkType","xlink:type":"xlinkType",xmlbase:"xmlBase","xml:base":"xmlBase",xmllang:"xmlLang","xml:lang":"xmlLang",xmlns:"xmlns","xml:space":"xmlSpace",xmlnsxlink:"xmlnsXlink","xmlns:xlink":"xmlnsXlink",xmlspace:"xmlSpace",y1:"y1",y2:"y2",y:"y",ychannelselector:"yChannelSelector",z:"z",zoomandpan:"zoomAndPan"},Rl={"aria-current":0,"aria-details":0,"aria-disabled":0,"aria-hidden":0,"aria-invalid":0,"aria-keyshortcuts":0,"aria-label":0,"aria-roledescription":0,"aria-autocomplete":0,"aria-checked":0,"aria-expanded":0,"aria-haspopup":0,"aria-level":0,"aria-modal":0,"aria-multiline":0,"aria-multiselectable":0,"aria-orientation":0,"aria-placeholder":0,"aria-pressed":0,"aria-readonly":0,"aria-required":0,"aria-selected":0,"aria-sort":0,"aria-valuemax":0,"aria-valuemin":0,"aria-valuenow":0,"aria-valuetext":0,"aria-atomic":0,"aria-busy":0,"aria-live":0,"aria-relevant":0,"aria-dropeffect":0,"aria-grabbed":0,"aria-activedescendant":0,"aria-colcount":0,"aria-colindex":0,"aria-colspan":0,"aria-controls":0,"aria-describedby":0,"aria-errormessage":0,"aria-flowto":0,"aria-labelledby":0,"aria-owns":0,"aria-posinset":0,"aria-rowcount":0,"aria-rowindex":0,"aria-rowspan":0,"aria-setsize":0},Nl={},Ol=new RegExp("^(aria)-["+Kr+"]*$"),Il=new RegExp("^(aria)[A-Z]["+Kr+"]*$"),Ul=Object.prototype.hasOwnProperty;function Al(){var e=kr.getStackAddendum();return null!=e?e:""}function Dl(e,t){if(Ul.call(Nl,t)&&Nl[t])return!0;if(Il.test(t)){var n="aria-"+t.slice(4).toLowerCase(),r=Rl.hasOwnProperty(n)?n:null;if(null==r)return o(!1,"Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.%s",t,Al()),Nl[t]=!0,!0;if(t!==r)return o(!1,"Invalid ARIA attribute `%s`. Did you mean `%s`?%s",t,r,Al()),Nl[t]=!0,!0}if(Ol.test(t)){var a=t.toLowerCase(),i=Rl.hasOwnProperty(a)?a:null;if(null==i)return Nl[t]=!0,!1;if(t!==i)return o(!1,"Unknown ARIA attribute `%s`. Did you mean `%s`?%s",t,i,Al()),Nl[t]=!0,!0}return!0}function Ml(e,t){El(e,t)||function(e,t){var n=[];for(var r in t)Dl(0,r)||n.push(r);var a=n.map(function(e){return"`"+e+"`"}).join(", ");1===n.length?o(!1,"Invalid aria prop %s on <%s> tag. For details, see https://fb.me/invalid-aria-prop%s",a,e,Al()):n.length>1&&o(!1,"Invalid aria props %s on <%s> tag. For details, see https://fb.me/invalid-aria-prop%s",a,e,Al())}(e,t)}var Fl=!1;function jl(){var e=kr.getStackAddendum();return null!=e?e:""}function Ll(){var e=kr.getStackAddendum();return null!=e?e:""}var Wl,zl={},Bl=Object.prototype.hasOwnProperty,Vl=/^on./,Hl=/^on[^A-Z]/,ql=new RegExp("^(aria)-["+Kr+"]*$"),$l=new RegExp("^(aria)[A-Z]["+Kr+"]*$");Wl=function(e,t,n,r){if(Bl.call(zl,t)&&zl[t])return!0;var a=t.toLowerCase();if("onfocusin"===a||"onfocusout"===a)return o(!1,"React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React."),zl[t]=!0,!0;if(r){if(E.hasOwnProperty(t))return!0;var i=R.hasOwnProperty(a)?R[a]:null;if(null!=i)return o(!1,"Invalid event handler property `%s`. Did you mean `%s`?%s",t,i,Ll()),zl[t]=!0,!0;if(Vl.test(t))return o(!1,"Unknown event handler property `%s`. It will be ignored.%s",t,Ll()),zl[t]=!0,!0}else if(Vl.test(t))return Hl.test(t)&&o(!1,"Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.%s",t,Ll()),zl[t]=!0,!0;if(ql.test(t)||$l.test(t))return!0;if("innerhtml"===a)return o(!1,"Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."),zl[t]=!0,!0;if("aria"===a)return o(!1,"The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead."),zl[t]=!0,!0;if("is"===a&&null!==n&&void 0!==n&&"string"!=typeof n)return o(!1,"Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.%s",typeof n,Ll()),zl[t]=!0,!0;if("number"==typeof n&&isNaN(n))return o(!1,"Received NaN for the `%s` attribute. If this is expected, cast the value to a string.%s",t,Ll()),zl[t]=!0,!0;var l=oo(t),u=null!==l&&l.type===Br;if(Pl.hasOwnProperty(a)){var s=Pl[a];if(s!==t)return o(!1,"Invalid DOM property `%s`. Did you mean `%s`?%s",t,s,Ll()),zl[t]=!0,!0}else if(!u&&t!==a)return o(!1,"React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.%s",t,a,Ll()),zl[t]=!0,!0;return"boolean"==typeof n&&no(t,n,l,!1)?(n?o(!1,'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.%s',n,t,t,n,t,Ll()):o(!1,'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.%s',n,t,t,n,t,t,t,Ll()),zl[t]=!0,!0):!!u||(!no(t,n,l,!1)||(zl[t]=!0,!1))};var Yl=function(e,t,n){var r=[];for(var a in t){Wl(0,a,t[a],n)||r.push(a)}var i=r.map(function(e){return"`"+e+"`"}).join(", ");1===r.length?o(!1,"Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://fb.me/react-attribute-behavior%s",i,e,Ll()):r.length>1&&o(!1,"Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://fb.me/react-attribute-behavior%s",i,e,Ll())};var Ql,Kl=zr.getCurrentFiberOwnerName,Xl=zr.getCurrentFiberStackAddendum,Gl=!1,Zl=!1,Jl="dangerouslySetInnerHTML",eu="suppressContentEditableWarning",tu="suppressHydrationWarning",nu="autoFocus",ru="children",ou="style",au="__html",iu=il.html,lu=l.thatReturns(""),uu=void 0,su=void 0,cu=void 0,du=void 0,fu=void 0,pu=void 0,hu=void 0,mu=void 0;lu=Xl,uu={time:!0,dialog:!0},cu=function(e,t){Ml(e,t),function(e,t){"input"!==e&&"textarea"!==e&&"select"!==e||null==t||null!==t.value||Fl||(Fl=!0,"select"===e&&t.multiple?o(!1,"`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.%s",e,jl()):o(!1,"`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.%s",e,jl()))}(e,t),function(e,t,n){El(e,t)||Yl(e,t,n)}(e,t,!0)};var vu=/\r\n?/g,gu=/\u0000|\uFFFD/g;function yu(e,t){!function(e,t){for(var n=ni(t),r=P[e],o=0;o<r.length;o++){var a=r[o];if(!n.hasOwnProperty(a)||!n[a]){switch(a){case Ht:Ka(Ht,t);break;case ht:case ze:Ka(ht,t),Ka(ze,t),n[ze]=!0,n[ht]=!0;break;case He:case Ye:hr(cn(a),!0)&&Ka(a,t);break;case gt:case Kt:case Vt:break;default:-1!==sn.indexOf(a)||Qa(a,t)}n[a]=!0}}}(t,e.nodeType===dr||e.nodeType===fr?e:e.ownerDocument)}function bu(e){return e.nodeType===dr?e:e.ownerDocument}function wu(e){e.onclick=l}function ku(e,t,n,r){var a=void 0,i=bu(n),l=void 0,u=r;if(u===iu&&(u=ll(e)),u===iu)if((a=El(e,t))||e===e.toLowerCase()||o(!1,"<%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.",e),"script"===e){var s=i.createElement("div");s.innerHTML="<script><\/script>";var c=s.firstChild;l=s.removeChild(c)}else l="string"==typeof t.is?i.createElement(e,{is:t.is}):i.createElement(e);else l=i.createElementNS(u,e);return u===iu&&(a||"[object HTMLUnknownElement]"!==Object.prototype.toString.call(l)||Object.prototype.hasOwnProperty.call(uu,e)||(uu[e]=!0,o(!1,"The tag <%s> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.",e))),l}function xu(e,t){return bu(t).createTextNode(e)}function Tu(e,t,n,r){var a=El(t,n);cu(t,n),a&&!Zl&&e.shadyRoot&&(o(!1,"%s is using shady DOM. Using shady DOM with React can cause things to break subtly.",Kl()||"A component"),Zl=!0);var i=void 0;switch(t){case"iframe":case"object":Qa(kt,e),i=n;break;case"video":case"audio":for(var l=0;l<sn.length;l++)Qa(sn[l],e);i=n;break;case"source":Qa(pt,e),i=n;break;case"img":case"image":case"link":Qa(pt,e),Qa(kt,e),i=n;break;case"form":Qa(Vt,e),Qa(Kt,e),i=n;break;case"details":Qa(Jt,e),i=n;break;case"input":Co(e,n),i=To(e,n),Qa(gt,e),yu(r,"onChange");break;case"option":zi(0,n),i=Bi(0,n);break;case"select":Xi(e,n),i=Ki(0,n),Qa(gt,e),yu(r,"onChange");break;case"textarea":el(e,n),i=Ji(e,n),Qa(gt,e),yu(r,"onChange");break;default:i=n}switch(_l(t,i,lu),function(e,t,n,r,o){for(var a in r)if(r.hasOwnProperty(a)){var i=r[a];if(a===ou)i&&Object.freeze(i),Tl(t,i,lu);else if(a===Jl){var l=i?i[au]:void 0;null!=l&&cl(t,l)}else a===ru?"string"==typeof i?("textarea"!==e||""!==i)&&dl(t,i):"number"==typeof i&&dl(t,""+i):a===eu||a===tu||a===nu||(E.hasOwnProperty(a)?null!=i&&("function"!=typeof i&&hu(a,i),yu(n,a)):null!=i&&fo(t,a,i,o))}}(t,e,r,i,a),t){case"input":gr(e),Eo(e,n,!1);break;case"textarea":gr(e),nl(e);break;case"option":!function(e,t){null!=t.value&&e.setAttribute("value",t.value)}(e,n);break;case"select":!function(e,t){var n=e;n.multiple=!!t.multiple;var r=t.value;null!=r?Qi(n,!!t.multiple,r,!1):null!=t.defaultValue&&Qi(n,!!t.multiple,t.defaultValue,!0)}(e,n);break;default:"function"==typeof i.onClick&&wu(e)}}function Cu(e,t,n,r,o){cu(t,r);var a=null,i=void 0,l=void 0;switch(t){case"input":i=To(e,n),l=To(e,r),a=[];break;case"option":i=Bi(0,n),l=Bi(0,r),a=[];break;case"select":i=Ki(0,n),l=Ki(0,r),a=[];break;case"textarea":i=Ji(e,n),l=Ji(e,r),a=[];break;default:l=r,"function"!=typeof(i=n).onClick&&"function"==typeof l.onClick&&wu(e)}_l(t,l,lu);var u=void 0,s=void 0,c=null;for(u in i)if(!l.hasOwnProperty(u)&&i.hasOwnProperty(u)&&null!=i[u])if(u===ou){var d=i[u];for(s in d)d.hasOwnProperty(s)&&(c||(c={}),c[s]="")}else u===Jl||u===ru||u===eu||u===tu||u===nu||(E.hasOwnProperty(u)?a||(a=[]):(a=a||[]).push(u,null));for(u in l){var f=l[u],p=null!=i?i[u]:void 0;if(l.hasOwnProperty(u)&&f!==p&&(null!=f||null!=p))if(u===ou)if(f&&Object.freeze(f),p){for(s in p)!p.hasOwnProperty(s)||f&&f.hasOwnProperty(s)||(c||(c={}),c[s]="");for(s in f)f.hasOwnProperty(s)&&p[s]!==f[s]&&(c||(c={}),c[s]=f[s])}else c||(a||(a=[]),a.push(u,c)),c=f;else if(u===Jl){var h=f?f[au]:void 0,m=p?p[au]:void 0;null!=h&&m!==h&&(a=a||[]).push(u,""+h)}else u===ru?p===f||"string"!=typeof f&&"number"!=typeof f||(a=a||[]).push(u,""+f):u===eu||u===tu||(E.hasOwnProperty(u)?(null!=f&&("function"!=typeof f&&hu(u,f),yu(o,u)),a||p===f||(a=[])):(a=a||[]).push(u,f))}return c&&(a=a||[]).push(ou,c),a}function Su(e,t,n,r,o){"input"===n&&"radio"===o.type&&null!=o.name&&So(e,o);El(n,r);switch(function(e,t,n,r){for(var o=0;o<t.length;o+=2){var a=t[o],i=t[o+1];a===ou?Tl(e,i,lu):a===Jl?cl(e,i):a===ru?dl(e,i):fo(e,a,i,r)}}(e,t,0,El(n,o)),n){case"input":_o(e,o);break;case"textarea":tl(e,o);break;case"select":!function(e,t){var n=e;n._wrapperState.initialValue=void 0;var r=n._wrapperState.wasMultiple;n._wrapperState.wasMultiple=!!t.multiple;var o=t.value;null!=o?Qi(n,!!t.multiple,o,!1):r!==!!t.multiple&&(null!=t.defaultValue?Qi(n,!!t.multiple,t.defaultValue,!0):Qi(n,!!t.multiple,t.multiple?[]:"",!1))}(e,o)}}function _u(e){var t=e.toLowerCase();return Pl.hasOwnProperty(t)&&Pl[t]||null}function Eu(e,t,n,r,a){var i,l=void 0;switch(su=!0===n[tu],i=El(t,n),cu(t,n),i&&!Zl&&e.shadyRoot&&(o(!1,"%s is using shady DOM. Using shady DOM with React can cause things to break subtly.",Kl()||"A component"),Zl=!0),t){case"iframe":case"object":Qa(kt,e);break;case"video":case"audio":for(var u=0;u<sn.length;u++)Qa(sn[u],e);break;case"source":Qa(pt,e);break;case"img":case"image":case"link":Qa(pt,e),Qa(kt,e);break;case"form":Qa(Vt,e),Qa(Kt,e);break;case"details":Qa(Jt,e);break;case"input":Co(e,n),Qa(gt,e),yu(a,"onChange");break;case"option":zi(0,n);break;case"select":Xi(e,n),Qa(gt,e),yu(a,"onChange");break;case"textarea":el(e,n),Qa(gt,e),yu(a,"onChange")}_l(t,n,lu),l=new Set;for(var s=e.attributes,c=0;c<s.length;c++){switch(s[c].name.toLowerCase()){case"data-reactroot":case"value":case"checked":case"selected":break;default:l.add(s[c].name)}}var d=null;for(var f in n)if(n.hasOwnProperty(f)){var p=n[f];if(f===ru)"string"==typeof p?e.textContent!==p&&(su||du(e.textContent,p),d=[ru,p]):"number"==typeof p&&e.textContent!==""+p&&(su||du(e.textContent,p),d=[ru,""+p]);else if(E.hasOwnProperty(f))null!=p&&("function"!=typeof p&&hu(f,p),yu(a,f));else if("boolean"==typeof i){var h=void 0,m=oo(f);if(su);else if(f===eu||f===tu||"value"===f||"checked"===f||"selected"===f);else if(f===Jl){var v=p&&p[au]||"",g=e.innerHTML,y=mu(e,v);y!==g&&fu(f,g,y)}else if(f===ou){l.delete(f);var b=xl(p);b!==(h=e.getAttribute("style"))&&fu(f,h,b)}else if(i)l.delete(f.toLowerCase()),p!==(h=co(e,f,p))&&fu(f,h,p);else if(!to(f,m,i)&&!ro(f,p,m,i)){var w=!1;if(null!==m)l.delete(m.attributeName),h=so(e,f,p,m);else{var k=r;if(k===iu&&(k=ll(t)),k===iu)l.delete(f.toLowerCase());else{var x=_u(f);null!==x&&x!==f&&(w=!0,l.delete(x)),l.delete(f)}h=co(e,f,p)}p===h||w||fu(f,h,p)}}}switch(l.size>0&&!su&&pu(l),t){case"input":gr(e),Eo(e,n,!0);break;case"textarea":gr(e),nl(e);break;case"select":case"option":break;default:"function"==typeof n.onClick&&wu(e)}return d}function Pu(e,t){return e.nodeValue!==t}function Ru(e,t){du(e.nodeValue,t)}function Nu(e,t){Gl||(Gl=!0,o(!1,"Did not expect server HTML to contain a <%s> in <%s>.",t.nodeName.toLowerCase(),e.nodeName.toLowerCase()))}function Ou(e,t){Gl||(Gl=!0,o(!1,'Did not expect server HTML to contain the text node "%s" in <%s>.',t.nodeValue,e.nodeName.toLowerCase()))}function Iu(e,t,n){Gl||(Gl=!0,o(!1,"Expected server HTML to contain a matching <%s> in <%s>.",t,e.nodeName.toLowerCase()))}function Uu(e,t){""!==t&&(Gl||(Gl=!0,o(!1,'Expected server HTML to contain a matching text node for "%s" in <%s>.',t,e.nodeName.toLowerCase())))}Ql=function(e){return("string"==typeof e?e:""+e).replace(vu,"\n").replace(gu,"")},du=function(e,t){if(!Gl){var n=Ql(t),r=Ql(e);r!==n&&(Gl=!0,o(!1,'Text content did not match. Server: "%s" Client: "%s"',r,n))}},fu=function(e,t,n){if(!Gl){var r=Ql(n),a=Ql(t);a!==r&&(Gl=!0,o(!1,"Prop `%s` did not match. Server: %s Client: %s",e,JSON.stringify(a),JSON.stringify(r)))}},pu=function(e){if(!Gl){Gl=!0;var t=[];e.forEach(function(e){t.push(e)}),o(!1,"Extra attributes from the server: %s",t)}},hu=function(e,t){!1===t?o(!1,"Expected `%s` listener to be a function, instead got `false`.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.%s",e,e,e,Xl()):o(!1,"Expected `%s` listener to be a function, instead got a value of `%s` type.%s",e,typeof t,Xl())},mu=function(e,t){var n=e.namespaceURI===iu?e.ownerDocument.createElement(e.tagName):e.ownerDocument.createElementNS(e.namespaceURI,e.tagName);return n.innerHTML=t,n.innerHTML};var Au,Du=Object.freeze({createElement:ku,createTextNode:xu,setInitialProperties:Tu,diffProperties:Cu,updateProperties:Su,diffHydratedProperties:Eu,diffHydratedText:Pu,warnForUnmatchedText:Ru,warnForDeletedHydratableElement:Nu,warnForDeletedHydratableText:Ou,warnForInsertedHydratedElement:Iu,warnForInsertedHydratedText:Uu,restoreControlledState:function(e,t,n){switch(t){case"input":return void Po(e,n);case"textarea":return void function(e,t){tl(e,t)}(e,n);case"select":return void function(e,t){var n=e,r=t.value;null!=r&&Qi(n,!!t.multiple,r,!1)}(e,n)}}}),Mu=zr.getCurrentFiberStackAddendum,Fu=["address","applet","area","article","aside","base","basefont","bgsound","blockquote","body","br","button","caption","center","col","colgroup","dd","details","dir","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","iframe","img","input","isindex","li","link","listing","main","marquee","menu","menuitem","meta","nav","noembed","noframes","noscript","object","ol","p","param","plaintext","pre","script","section","select","source","style","summary","table","tbody","td","template","textarea","tfoot","th","thead","title","tr","track","ul","wbr","xmp"],ju=["applet","caption","html","table","td","th","marquee","object","template","foreignObject","desc","title"],Lu=ju.concat(["button"]),Wu=["dd","dt","li","option","optgroup","p","rp","rt"],zu={current:null,formTag:null,aTagInScope:null,buttonTagInScope:null,nobrTagInScope:null,pTagInButtonScope:null,listItemTagAutoclosing:null,dlItemTagAutoclosing:null},Bu={};(Au=function(e,t,n){var r=(n=n||zu).current,a=r&&r.tag;null!=t&&(null!=e&&o(!1,"validateDOMNesting: when childText is passed, childTag should be null"),e="#text");var i=function(e,t){switch(t){case"select":return"option"===e||"optgroup"===e||"#text"===e;case"optgroup":return"option"===e||"#text"===e;case"option":return"#text"===e;case"tr":return"th"===e||"td"===e||"style"===e||"script"===e||"template"===e;case"tbody":case"thead":case"tfoot":return"tr"===e||"style"===e||"script"===e||"template"===e;case"colgroup":return"col"===e||"template"===e;case"table":return"caption"===e||"colgroup"===e||"tbody"===e||"tfoot"===e||"thead"===e||"style"===e||"script"===e||"template"===e;case"head":return"base"===e||"basefont"===e||"bgsound"===e||"link"===e||"meta"===e||"title"===e||"noscript"===e||"noframes"===e||"style"===e||"script"===e||"template"===e;case"html":return"head"===e||"body"===e;case"#document":return"html"===e}switch(e){case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return"h1"!==t&&"h2"!==t&&"h3"!==t&&"h4"!==t&&"h5"!==t&&"h6"!==t;case"rp":case"rt":return-1===Wu.indexOf(t);case"body":case"caption":case"col":case"colgroup":case"frame":case"head":case"html":case"tbody":case"td":case"tfoot":case"th":case"thead":case"tr":return null==t}return!0}(e,a)?null:r,l=i?null:function(e,t){switch(e){case"address":case"article":case"aside":case"blockquote":case"center":case"details":case"dialog":case"dir":case"div":case"dl":case"fieldset":case"figcaption":case"figure":case"footer":case"header":case"hgroup":case"main":case"menu":case"nav":case"ol":case"p":case"section":case"summary":case"ul":case"pre":case"listing":case"table":case"hr":case"xmp":case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return t.pTagInButtonScope;case"form":return t.formTag||t.pTagInButtonScope;case"li":return t.listItemTagAutoclosing;case"dd":case"dt":return t.dlItemTagAutoclosing;case"button":return t.buttonTagInScope;case"a":return t.aTagInScope;case"nobr":return t.nobrTagInScope}return null}(e,n),u=i||l;if(u){var s=u.tag,c=Mu(),d=!!i+"|"+e+"|"+s+"|"+c;if(!Bu[d]){Bu[d]=!0;var f=e,p="";if("#text"===e?/\S/.test(t)?f="Text nodes":(f="Whitespace text nodes",p=" Make sure you don't have any extra whitespace between tags on each line of your source code."):f="<"+e+">",i){var h="";"table"===s&&"tr"===e&&(h+=" Add a <tbody> to your code to match the DOM tree generated by the browser."),o(!1,"validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s",f,s,p,h,c)}else o(!1,"validateDOMNesting(...): %s cannot appear as a descendant of <%s>.%s",f,s,c)}}}).updatedAncestorInfo=function(e,t,n){var r=i({},e||zu),o={tag:t,instance:n};return-1!==ju.indexOf(t)&&(r.aTagInScope=null,r.buttonTagInScope=null,r.nobrTagInScope=null),-1!==Lu.indexOf(t)&&(r.pTagInButtonScope=null),-1!==Fu.indexOf(t)&&"address"!==t&&"div"!==t&&"p"!==t&&(r.listItemTagAutoclosing=null,r.dlItemTagAutoclosing=null),r.current=o,"form"===t&&(r.formTag=o),"a"===t&&(r.aTagInScope=o),"button"===t&&(r.buttonTagInScope=o),"nobr"===t&&(r.nobrTagInScope=o),"p"===t&&(r.pTagInButtonScope=o),"li"===t&&(r.listItemTagAutoclosing=o),"dd"!==t&&"dt"!==t||(r.dlItemTagAutoclosing=o),r};var Vu=Au;function Hu(){t(!1,"The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.")}var qu=!1,$u=Hu,Yu=Hu,Qu=Hu,Ku=Hu,Xu=Hu,Gu=ku,Zu=xu,Ju=Tu,es=Cu,ts=Su,ns=Eu,rs=Pu,os=Ru,as=Nu,is=Ou,ls=Iu,us=Uu,ss=Vu.updatedAncestorInfo,cs=pe,ds=ye,fs=void 0;fs="suppressHydrationWarning";var ps=null,hs=null;function ms(e,t){switch(e){case"button":case"input":case"select":case"textarea":return!!t.autoFocus}return!1}function vs(e){return e}function gs(e,t){e.appendChild(t)}function ys(e,t,n,r,o){return Ju(e,t,n,r),ms(t,n)}function bs(e,t){return"textarea"===e||"string"==typeof t.children||"number"==typeof t.children||"object"==typeof t.dangerouslySetInnerHTML&&null!==t.dangerouslySetInnerHTML&&"string"==typeof t.dangerouslySetInnerHTML.__html}function ws(e,t){return!!t.hidden}function ks(e,t,n,r){Vu(null,e,n.ancestorInfo);var o=Zu(e,t);return cs(r,o),o}var xs=xi,Ts=!0,Cs=Ci,Ss=Si,_s=!0;function Es(e){dl(e,"")}function Ps(e,t){e.appendChild(t)}function Rs(e,t){e.nodeType===cr?e.parentNode.insertBefore(t,e):e.appendChild(t)}function Ns(e,t,n){e.insertBefore(t,n)}function Os(e,t,n){e.nodeType===cr?e.parentNode.insertBefore(t,n):e.insertBefore(t,n)}function Is(e,t){e.removeChild(t)}function Us(e,t){e.nodeType===cr?e.parentNode.removeChild(t):e.removeChild(t)}var As=!0;function Ds(e){for(var t=e.nextSibling;t&&t.nodeType!==ur&&t.nodeType!==sr;)t=t.nextSibling;return t}function Ms(e){for(var t=e.firstChild;t&&t.nodeType!==ur&&t.nodeType!==sr;)t=t.nextSibling;return t}var Fs=!0,js=!1,Ls=!1,Ws=!1,zs=!0,Bs=!0,Vs=!1,Hs=!1,qs=!0,$s="undefined"!=typeof performance&&"function"==typeof performance.mark&&"function"==typeof performance.clearMarks&&"function"==typeof performance.measure&&"function"==typeof performance.clearMeasures,Ys=null,Qs=null,Ks=null,Xs=!1,Gs=!1,Zs=!1,Js=0,ec=0,tc=!1,nc=new Set,rc=function(e){return"⚛ "+e},oc=function(e){performance.mark(rc(e))},ac=function(e,t,n){var r=rc(t),o=function(e,t){return(t?"⛔ ":"⚛ ")+e+(t?" Warning: "+t:"")}(e,n);try{performance.measure(o,r)}catch(e){}performance.clearMarks(r),performance.clearMeasures(o)},ic=function(e,t){return e+" (#"+t+")"},lc=function(e,t,n){return null===n?e+" ["+(t?"update":"mount")+"]":e+"."+n},uc=function(e,t){var n=Fr(e)||"Unknown",r=e._debugID,o=null!==e.alternate,a=lc(n,o,t);if(Xs&&nc.has(a))return!1;nc.add(a);var i=ic(a,r);return oc(i),!0},sc=function(e,t){var n=Fr(e)||"Unknown",r=e._debugID,o=null!==e.alternate,a=lc(n,o,t);!function(e){performance.clearMarks(rc(e))}(ic(a,r))},cc=function(e,t,n){var r=Fr(e)||"Unknown",o=e._debugID,a=null!==e.alternate,i=lc(r,a,t),l=ic(i,o);ac(i,l,n)},dc=function(e){switch(e.tag){case J:case te:case ne:case ee:case re:case ie:case ae:case oe:return!0;default:return!1}},fc=function(){null!==Qs&&null!==Ks&&sc(Ks,Qs),Ks=null,Qs=null,Zs=!1},pc=function(){for(var e=Ys;e;)e._debugIsCurrentlyTiming&&cc(e,null,null),e=e.return},hc=function(e){null!==e.return&&hc(e.return),e._debugIsCurrentlyTiming&&uc(e,null)},mc=function(){null!==Ys&&hc(Ys)};function vc(){Fs&&ec++}function gc(e){if(Fs){if(!$s||dc(e))return;e._debugIsCurrentlyTiming=!1,sc(e,null)}}function yc(e){if(Fs){if(!$s||dc(e))return;if(Ys=e.return,!e._debugIsCurrentlyTiming)return;e._debugIsCurrentlyTiming=!1,cc(e,null,null)}}function bc(e){if(Fs){if(!$s||dc(e))return;if(Ys=e.return,!e._debugIsCurrentlyTiming)return;e._debugIsCurrentlyTiming=!1;cc(e,null,"An error was thrown inside this error boundary")}}function wc(e,t){if(Fs){if(!$s)return;if(fc(),!uc(e,t))return;Ks=e,Qs=t}}function kc(){if(Fs){if(!$s)return;if(null!==Qs&&null!==Ks)cc(Ks,Qs,Zs?"Scheduled a cascading update":null);Qs=null,Ks=null}}function xc(e,t){if(Fs){if(!$s)return;var n=null;if(null!==e)if(e.tag===J)n="A top-level update interrupted the previous render";else n="An update to "+(Fr(e)||"Unknown")+" interrupted the previous render";else Js>1&&(n="There were cascading updates");Js=0;var r=t?"(React Tree Reconciliation: Completed Root)":"(React Tree Reconciliation: Yielded)";pc(),ac(r,"(React Tree Reconciliation)",n)}}var Tc=[],Cc=void 0;Cc=[];var Sc=-1;function _c(e){return{current:e}}function Ec(e,t){Sc<0?o(!1,"Unexpected pop."):(t!==Cc[Sc]&&o(!1,"Unexpected Fiber popped."),e.current=Tc[Sc],Tc[Sc]=null,Cc[Sc]=null,Sc--)}function Pc(e,t,n){Tc[++Sc]=e.current,Cc[Sc]=n,e.current=t}var Rc=void 0;Rc={};var Nc=_c(f),Oc=_c(!1),Ic=f;function Uc(e){return Fc(e)?Ic:Nc.current}function Ac(e,t,n){var r=e.stateNode;r.__reactInternalMemoizedUnmaskedChildContext=t,r.__reactInternalMemoizedMaskedChildContext=n}function Dc(e,t){var n=e.type.contextTypes;if(!n)return f;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={};for(var a in n)o[a]=t[a];var i=Fr(e)||"Unknown";return u(n,o,"context",i,zr.getCurrentFiberStackAddendum),r&&Ac(e,t,o),o}function Mc(){return Oc.current}function Fc(e){return e.tag===Z&&null!=e.type.childContextTypes}function jc(e){Fc(e)&&(Ec(Oc,e),Ec(Nc,e))}function Lc(e){Ec(Oc,e),Ec(Nc,e)}function Wc(e,n,r){Nc.current!==f&&t(!1,"Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue."),Pc(Nc,n,e),Pc(Oc,r,e)}function zc(e,n){var r=e.stateNode,a=e.type.childContextTypes;if("function"!=typeof r.getChildContext){var l=Fr(e)||"Unknown";return Rc[l]||(Rc[l]=!0,o(!1,"%s.childContextTypes is specified but there is no getChildContext() method on the instance. You can either define getChildContext() on %s or remove childContextTypes from it.",l,l)),n}var s;for(var c in zr.setCurrentPhase("getChildContext"),wc(e,"getChildContext"),s=r.getChildContext(),kc(),zr.setCurrentPhase(null),s)c in a||t(!1,'%s.getChildContext(): key "%s" is not defined in childContextTypes.',Fr(e)||"Unknown",c);var d=Fr(e)||"Unknown";return u(a,s,"child context",d,zr.getCurrentFiberStackAddendum),i({},n,s)}function Bc(e){if(!Fc(e))return!1;var t=e.stateNode,n=t&&t.__reactInternalMemoizedMergedChildContext||f;return Ic=Nc.current,Pc(Nc,n,e),Pc(Oc,Oc.current,e),!0}function Vc(e,n){var r=e.stateNode;if(r||t(!1,"Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue."),n){var o=zc(e,Ic);r.__reactInternalMemoizedMergedChildContext=o,Ec(Oc,e),Ec(Nc,e),Pc(Nc,o,e),Pc(Oc,n,e)}else Ec(Oc,e),Pc(Oc,n,e)}var Hc=1073741823,qc=0,$c=1,Yc=Hc,Qc=10,Kc=2;function Xc(e){return(e/Qc|0)+Kc}function Gc(e){return(e-Kc)*Qc}function Zc(e,t,n){return Kc+function(e,t){return(1+(e/t|0))*t}(e-Kc+t/Qc,n/Qc)}var Jc=0,ed=1,td=2,nd=4,rd=void 0;rd=!1;try{var od=Object.preventExtensions({}),ad=new Map([[od,null]]),id=new Set([od]);ad.set(0,0),id.add(0)}catch(e){rd=!0}var ld=void 0;ld=1;var ud=function(e,t,n,r){return new function(e,t,n,r){this.tag=e,this.key=n,this.type=null,this.stateNode=null,this.return=null,this.child=null,this.sibling=null,this.index=0,this.ref=null,this.pendingProps=t,this.memoizedProps=null,this.updateQueue=null,this.memoizedState=null,this.mode=r,this.effectTag=ta,this.nextEffect=null,this.firstEffect=null,this.lastEffect=null,this.expirationTime=qc,this.alternate=null,qs&&(this.actualDuration=0,this.actualStartTime=0,this.selfBaseTime=0,this.treeBaseTime=0),this._debugID=ld++,this._debugSource=null,this._debugOwner=null,this._debugIsCurrentlyTiming=!1,rd||"function"!=typeof Object.preventExtensions||Object.preventExtensions(this)}(e,t,n,r)};function sd(e,t,n){var r=e.alternate;return null===r?((r=ud(e.tag,t,e.key,e.mode)).type=e.type,r.stateNode=e.stateNode,r._debugID=e._debugID,r._debugSource=e._debugSource,r._debugOwner=e._debugOwner,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.effectTag=ta,r.nextEffect=null,r.firstEffect=null,r.lastEffect=null,qs&&(r.actualDuration=0,r.actualStartTime=0)),r.expirationTime=n,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,qs&&(r.selfBaseTime=e.selfBaseTime,r.treeBaseTime=e.treeBaseTime),r}function cd(e,n,r){var o;o=e._owner;var a=void 0,i=e.type,l=e.key,u=e.props,s=void 0;if("function"==typeof i)s=function(e){return!(!e.prototype||!e.prototype.isReactComponent)}(i)?Z:X;else if("string"==typeof i)s=te;else switch(i){case _r:return dd(u.children,n,r,l);case Or:s=oe,n|=ed|td;break;case Er:s=oe,n|=td;break;case Pr:return function(e,n,r,o){"string"==typeof e.id&&"function"==typeof e.onRender||t(!1,'Profiler must specify an "id" string and "onRender" function as props');var a=ud(ue,e,o,n|nd);return a.type=Pr,a.expirationTime=r,a}(u,n,r,l);case Ur:s=se,n|=td;break;default:s=function(e,n){switch("object"==typeof e&&null!==e?e.$$typeof:null){case Rr:return ie;case Nr:return ae;case Ir:return le;default:var r="";(void 0===e||"object"==typeof e&&null!==e&&0===Object.keys(e).length)&&(r+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var o=n?Fr(n):null;o&&(r+="\n\nCheck the render method of `"+o+"`."),t(!1,"Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",null==e?e:typeof e,r)}}(i,o)}return(a=ud(s,u,l,n)).type=i,a.expirationTime=r,a._debugSource=e._source,a._debugOwner=e._owner,a}function dd(e,t,n,r){var o=ud(re,e,r,t);return o.expirationTime=n,o}function fd(e,t,n){var r=ud(ne,e,null,t);return r.expirationTime=n,r}function pd(e,t,n){var r=null!==e.children?e.children:[],o=ud(ee,r,e.key,t);return o.expirationTime=n,o.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},o}function hd(e,t){return null===e&&(e=ud(X,null,null,Jc)),e.tag=t.tag,e.key=t.key,e.type=t.type,e.stateNode=t.stateNode,e.return=t.return,e.child=t.child,e.sibling=t.sibling,e.index=t.index,e.ref=t.ref,e.pendingProps=t.pendingProps,e.memoizedProps=t.memoizedProps,e.updateQueue=t.updateQueue,e.memoizedState=t.memoizedState,e.mode=t.mode,e.effectTag=t.effectTag,e.nextEffect=t.nextEffect,e.firstEffect=t.firstEffect,e.lastEffect=t.lastEffect,e.expirationTime=t.expirationTime,e.alternate=t.alternate,qs&&(e.actualDuration=t.actualDuration,e.actualStartTime=t.actualStartTime,e.selfBaseTime=t.selfBaseTime,e.treeBaseTime=t.treeBaseTime),e._debugID=t._debugID,e._debugSource=t._debugSource,e._debugOwner=t._debugOwner,e._debugIsCurrentlyTiming=t._debugIsCurrentlyTiming,e}function md(e,t,n){var r=function(e){return ud(J,null,null,e?ed|td:Jc)}(t),o={current:r,containerInfo:e,pendingChildren:null,earliestPendingTime:qc,latestPendingTime:qc,earliestSuspendedTime:qc,latestSuspendedTime:qc,latestPingedTime:qc,pendingCommitExpirationTime:qc,finishedWork:null,context:null,pendingContext:null,hydrate:n,remainingExpirationTime:qc,firstBatch:null,nextScheduledRoot:null};return r.stateNode=o,o}var vd=null,gd=null,yd=!1;function bd(e){return function(t){try{return e(t)}catch(e){yd||(yd=!0,o(!1,"React DevTools encountered an error: %s",e))}}}function wd(e){"function"==typeof vd&&vd(e)}function kd(e){"function"==typeof gd&&gd(e)}var xd=function(e,t){if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(!e){for(var n=arguments.length,r=Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];(function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var o=0,a="Warning: "+e.replace(/%s/g,function(){return n[o++]});"undefined"!=typeof console&&console.warn(a);try{throw new Error(a)}catch(e){}}).apply(void 0,[t].concat(r))}},Td={discardPendingWarnings:function(){},flushPendingDeprecationWarnings:function(){},flushPendingUnsafeLifecycleWarnings:function(){},recordDeprecationWarnings:function(e,t){},recordUnsafeLifecycleWarnings:function(e,t){},recordLegacyContextWarning:function(e,t){},flushLegacyContextWarning:function(){}},Cd={UNSAFE_componentWillMount:"componentDidMount",UNSAFE_componentWillReceiveProps:"static getDerivedStateFromProps",UNSAFE_componentWillUpdate:"componentDidUpdate"},Sd=[],_d=[],Ed=[],Pd=new Map,Rd=new Map,Nd=new Set,Od=new Set,Id=new Set,Ud=function(e){var t=[];return e.forEach(function(e){t.push(e)}),t.sort().join(", ")};Td.discardPendingWarnings=function(){Sd=[],_d=[],Ed=[],Pd=new Map,Rd=new Map},Td.flushPendingUnsafeLifecycleWarnings=function(){Pd.forEach(function(e,t){var n=[];if(Object.keys(e).forEach(function(t){var r=e[t];if(r.length>0){var o=new Set;r.forEach(function(e){o.add(Fr(e)||"Component"),Od.add(e.type)});var a=t.replace("UNSAFE_",""),i=Cd[t],l=Ud(o);n.push(a+": Please update the following components to use "+i+" instead: "+l)}}),n.length>0){var r=Lr(t);o(!1,"Unsafe lifecycle methods were found within a strict-mode tree:%s\n\n%s\n\nLearn more about this warning here:\nhttps://fb.me/react-strict-mode-warnings",r,n.join("\n\n"))}}),Pd=new Map};var Ad=function(e){for(var t=null,n=e;null!==n;)n.mode&td&&(t=n),n=n.return;return t};Td.flushPendingDeprecationWarnings=function(){if(Sd.length>0){var e=new Set;Sd.forEach(function(t){e.add(Fr(t)||"Component"),Nd.add(t.type)});var t=Ud(e);xd(!1,"componentWillMount is deprecated and will be removed in the next major version. Use componentDidMount instead. As a temporary workaround, you can rename to UNSAFE_componentWillMount.\n\nPlease update the following components: %s\n\nLearn more about this warning here:\nhttps://fb.me/react-async-component-lifecycle-hooks",t),Sd=[]}if(_d.length>0){var n=new Set;_d.forEach(function(e){n.add(Fr(e)||"Component"),Nd.add(e.type)});var r=Ud(n);xd(!1,"componentWillReceiveProps is deprecated and will be removed in the next major version. Use static getDerivedStateFromProps instead.\n\nPlease update the following components: %s\n\nLearn more about this warning here:\nhttps://fb.me/react-async-component-lifecycle-hooks",r),_d=[]}if(Ed.length>0){var o=new Set;Ed.forEach(function(e){o.add(Fr(e)||"Component"),Nd.add(e.type)});var a=Ud(o);xd(!1,"componentWillUpdate is deprecated and will be removed in the next major version. Use componentDidUpdate instead. As a temporary workaround, you can rename to UNSAFE_componentWillUpdate.\n\nPlease update the following components: %s\n\nLearn more about this warning here:\nhttps://fb.me/react-async-component-lifecycle-hooks",a),Ed=[]}},Td.recordDeprecationWarnings=function(e,t){Nd.has(e.type)||("function"==typeof t.componentWillMount&&!0!==t.componentWillMount.__suppressDeprecationWarning&&Sd.push(e),"function"==typeof t.componentWillReceiveProps&&!0!==t.componentWillReceiveProps.__suppressDeprecationWarning&&_d.push(e),"function"==typeof t.componentWillUpdate&&!0!==t.componentWillUpdate.__suppressDeprecationWarning&&Ed.push(e))},Td.recordUnsafeLifecycleWarnings=function(e,t){var n=Ad(e);if(null!==n){if(!Od.has(e.type)){var r=void 0;Pd.has(n)?r=Pd.get(n):(r={UNSAFE_componentWillMount:[],UNSAFE_componentWillReceiveProps:[],UNSAFE_componentWillUpdate:[]},Pd.set(n,r));var a=[];("function"==typeof t.componentWillMount&&!0!==t.componentWillMount.__suppressDeprecationWarning||"function"==typeof t.UNSAFE_componentWillMount)&&a.push("UNSAFE_componentWillMount"),("function"==typeof t.componentWillReceiveProps&&!0!==t.componentWillReceiveProps.__suppressDeprecationWarning||"function"==typeof t.UNSAFE_componentWillReceiveProps)&&a.push("UNSAFE_componentWillReceiveProps"),("function"==typeof t.componentWillUpdate&&!0!==t.componentWillUpdate.__suppressDeprecationWarning||"function"==typeof t.UNSAFE_componentWillUpdate)&&a.push("UNSAFE_componentWillUpdate"),a.length>0&&a.forEach(function(t){r[t].push(e)})}}else o(!1,"Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue.")},Td.recordLegacyContextWarning=function(e,t){var n=Ad(e);if(null!==n){if(!Id.has(e.type)){var r=Rd.get(n);(null!=e.type.contextTypes||null!=e.type.childContextTypes||null!==t&&"function"==typeof t.getChildContext)&&(void 0===r&&(r=[],Rd.set(n,r)),r.push(e))}}else o(!1,"Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue.")},Td.flushLegacyContextWarning=function(){Rd.forEach(function(e,t){var n=new Set;e.forEach(function(e){n.add(Fr(e)||"Component"),Id.add(e.type)});var r=Ud(n),a=Lr(t);o(!1,"Legacy context API has been detected within a strict-mode tree: %s\n\nPlease update the following components: %s\n\nLearn more about this warning here:\nhttps://fb.me/react-strict-mode-warnings",a,r)})};var Dd={debugTool:null};function Md(e,t){if(Ls){var n=e.earliestPendingTime;if(n===qc)e.earliestPendingTime=e.latestPendingTime=t;else if(n>t)e.earliestPendingTime=t;else e.latestPendingTime<t&&(e.latestPendingTime=t)}}function Fd(e){if(Ls){var t=e.earliestSuspendedTime,n=e.earliestPendingTime;return t===qc?n:n!==qc?n:e.latestPingedTime}return e.current.expirationTime}var jd=0,Ld=1,Wd=2,zd=3,Bd=!1,Vd=void 0,Hd=void 0,qd=void 0;function $d(e){return{expirationTime:qc,baseState:e,firstUpdate:null,lastUpdate:null,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Yd(e){return{expirationTime:e.expirationTime,baseState:e.baseState,firstUpdate:e.firstUpdate,lastUpdate:e.lastUpdate,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Qd(e){return{expirationTime:e,tag:jd,payload:null,callback:null,next:null,nextEffect:null}}function Kd(e,t,n){null===e.lastUpdate?e.firstUpdate=e.lastUpdate=t:(e.lastUpdate.next=t,e.lastUpdate=t),(e.expirationTime===qc||e.expirationTime>n)&&(e.expirationTime=n)}function Xd(e,t,n){var r=e.alternate,a=void 0,i=void 0;null===r?(i=null,null===(a=e.updateQueue)&&(a=e.updateQueue=$d(e.memoizedState))):(a=e.updateQueue,i=r.updateQueue,null===a?null===i?(a=e.updateQueue=$d(e.memoizedState),i=r.updateQueue=$d(r.memoizedState)):a=e.updateQueue=Yd(i):null===i&&(i=r.updateQueue=Yd(a))),null===i||a===i?Kd(a,t,n):null===a.lastUpdate||null===i.lastUpdate?(Kd(a,t,n),Kd(i,t,n)):(Kd(a,t,n),i.lastUpdate=t),e.tag!==Z||Hd!==a&&(null===i||Hd!==i)||Vd||(o(!1,"An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback."),Vd=!0)}function Gd(e,t,n){var r=e.updateQueue;null===(r=null===r?e.updateQueue=$d(e.memoizedState):Zd(e,r)).lastCapturedUpdate?r.firstCapturedUpdate=r.lastCapturedUpdate=t:(r.lastCapturedUpdate.next=t,r.lastCapturedUpdate=t),(r.expirationTime===qc||r.expirationTime>n)&&(r.expirationTime=n)}function Zd(e,t){var n=e.alternate;return null!==n&&t===n.updateQueue&&(t=e.updateQueue=Yd(t)),t}function Jd(e,t,n,r,o,a){switch(n.tag){case Ld:var l=n.payload;return"function"==typeof l?((Ws||zs&&e.mode&td)&&l.call(a,r,o),l.call(a,r,o)):l;case zd:e.effectTag=e.effectTag&~ha|sa;case jd:var u=n.payload,s=void 0;return"function"==typeof u?((Ws||zs&&e.mode&td)&&u.call(a,r,o),s=u.call(a,r,o)):s=u,null===s||void 0===s?r:i({},r,s);case Wd:return Bd=!0,r}return r}function ef(e,t,n,r,o){if(Bd=!1,!(t.expirationTime===qc||t.expirationTime>o)){t=Zd(e,t),Hd=t;for(var a=t.baseState,i=null,l=qc,u=t.firstUpdate,s=a;null!==u;){var c=u.expirationTime;if(c>o)null===i&&(i=u,a=s),(l===qc||l>c)&&(l=c);else s=Jd(e,0,u,s,n,r),null!==u.callback&&(e.effectTag|=ua,u.nextEffect=null,null===t.lastEffect?t.firstEffect=t.lastEffect=u:(t.lastEffect.nextEffect=u,t.lastEffect=u));u=u.next}var d=null;for(u=t.firstCapturedUpdate;null!==u;){var f=u.expirationTime;if(f>o)null===d&&(d=u,null===i&&(a=s)),(l===qc||l>f)&&(l=f);else s=Jd(e,0,u,s,n,r),null!==u.callback&&(e.effectTag|=ua,u.nextEffect=null,null===t.lastCapturedEffect?t.firstCapturedEffect=t.lastCapturedEffect=u:(t.lastCapturedEffect.nextEffect=u,t.lastCapturedEffect=u));u=u.next}null===i&&(t.lastUpdate=null),null===d?t.lastCapturedUpdate=null:e.effectTag|=ua,null===i&&null===d&&(a=s),t.baseState=a,t.firstUpdate=i,t.firstCapturedUpdate=d,t.expirationTime=l,e.memoizedState=s,Hd=null}}function tf(e,n){"function"!=typeof e&&t(!1,"Invalid argument passed as callback. Expected a function. Instead received: %s",e),e.call(n)}function nf(){Bd=!1}function rf(){return Bd}function of(e,t,n,r){null!==t.firstCapturedUpdate&&(null!==t.lastUpdate&&(t.lastUpdate.next=t.firstCapturedUpdate,t.lastUpdate=t.lastCapturedUpdate),t.firstCapturedUpdate=t.lastCapturedUpdate=null);var o=t.firstEffect;for(t.firstEffect=t.lastEffect=null;null!==o;){var a=o.callback;null!==a&&(o.callback=null,tf(a,n)),o=o.nextEffect}for(o=t.firstCapturedEffect,t.firstCapturedEffect=t.lastCapturedEffect=null;null!==o;){var i=o.callback;null!==i&&(o.callback=null,tf(i,n)),o=o.nextEffect}}function af(e,t){return{value:e,source:t,stack:Lr(t)}}Vd=!1,Hd=null,qd=function(){Hd=null};var lf=_c(null),uf=_c(null),sf=_c(0),cf=void 0;function df(e){var t=e.type._context;Ts?(Pc(sf,t._changedBits,e),Pc(uf,t._currentValue,e),Pc(lf,e,e),t._currentValue=e.pendingProps.value,t._changedBits=e.stateNode,void 0!==t._currentRenderer&&null!==t._currentRenderer&&t._currentRenderer!==cf&&o(!1,"Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."),t._currentRenderer=cf):(Pc(sf,t._changedBits2,e),Pc(uf,t._currentValue2,e),Pc(lf,e,e),t._currentValue2=e.pendingProps.value,t._changedBits2=e.stateNode,void 0!==t._currentRenderer2&&null!==t._currentRenderer2&&t._currentRenderer2!==cf&&o(!1,"Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."),t._currentRenderer2=cf)}function ff(e){var t=sf.current,n=uf.current;Ec(lf,e),Ec(uf,e),Ec(sf,e);var r=e.type._context;Ts?(r._currentValue=n,r._changedBits=t):(r._currentValue2=n,r._changedBits2=t)}cf={};var pf={},hf=_c(pf),mf=_c(pf),vf=_c(pf);function gf(e){return e===pf&&t(!1,"Expected host context to exist. This error is likely caused by a bug in React. Please file an issue."),e}function yf(){return gf(vf.current)}function bf(e,t){Pc(vf,t,e),Pc(mf,e,e),Pc(hf,pf,e);var n=function(e){var t=void 0,n=void 0,r=e.nodeType;switch(r){case dr:case fr:t=r===dr?"#document":"#fragment";var o=e.documentElement;n=o?o.namespaceURI:ul(null,"");break;default:var a=r===cr?e.parentNode:e;n=ul(a.namespaceURI||null,t=a.tagName)}var i=t.toLowerCase();return{namespace:n,ancestorInfo:ss(null,i,null)}}(t);Ec(hf,e),Pc(hf,n,e)}function wf(e){Ec(hf,e),Ec(mf,e),Ec(vf,e)}function kf(){return gf(hf.current)}function xf(e){gf(vf.current);var t=gf(hf.current),n=function(e,t,n){var r=e;return{namespace:ul(r.namespace,t),ancestorInfo:ss(r.ancestorInfo,t,null)}}(t,e.type);t!==n&&(Pc(mf,e,e),Pc(hf,n,e))}function Tf(e){mf.current===e&&(Ec(hf,e),Ec(mf,e))}var Cf=0;var Sf=void 0;Sf=[];var _f=0,Ef=0;function Pf(){qs&&0===_f&&(_f=xs())}function Rf(e){qs&&(e!==Sf.pop()&&o(!1,"Unexpected Fiber (%s) popped.",Fr(e)),e.actualDuration=xs()-Ef-e.actualDuration)}function Nf(){qs&&_f>0&&(Ef+=xs()-_f,_f=0)}var Of=-1;function If(){qs&&(Of=-1)}var Uf,Af={},Df=Array.isArray,Mf=void 0,Ff=void 0,jf=void 0,Lf=void 0,Wf=void 0,zf=void 0;Mf=new Set,Ff=new Set,jf=new Set,Lf=new Set,Wf=new Set;var Bf=new Set;function Vf(e,t,n){var r=e.memoizedState;(Ws||zs&&e.mode&td)&&t(n,r);var o=t(n,r);zf(e,o);var a=null===o||void 0===o?r:i({},r,o);e.memoizedState=a;var l=e.updateQueue;null!==l&&l.expirationTime===qc&&(l.baseState=a)}Uf=function(e,t){if(null!==e&&"function"!=typeof e){var n=t+"_"+e;Bf.has(n)||(Bf.add(n),o(!1,"%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.",t,e))}},zf=function(e,t){if(void 0===t){var n=Fr(e)||"Component";Wf.has(n)||(Wf.add(n),o(!1,"%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.",n))}},Object.defineProperty(Af,"_processChildContext",{enumerable:!1,value:function(){t(!1,"_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).")}}),Object.freeze(Af);var Hf={isMounted:function(e){var t=wr.current;if(null!==t&&t.tag===Z){var n=t,r=n.stateNode;r._warnedAboutRefsInRender||o(!1,"%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.",Fr(n)||"A component"),r._warnedAboutRefsInRender=!0}var a=ea(e);return!!a&&ya(a)===va},enqueueSetState:function(e,t,n){var r=ea(e),o=om(lm(),r),a=Qd(o);a.payload=t,void 0!==n&&null!==n&&(Uf(n,"setState"),a.callback=n),Xd(r,a,o),im(r,o)},enqueueReplaceState:function(e,t,n){var r=ea(e),o=om(lm(),r),a=Qd(o);a.tag=Ld,a.payload=t,void 0!==n&&null!==n&&(Uf(n,"replaceState"),a.callback=n),Xd(r,a,o),im(r,o)},enqueueForceUpdate:function(e,t){var n=ea(e),r=om(lm(),n),o=Qd(r);o.tag=Wd,void 0!==t&&null!==t&&(Uf(t,"forceUpdate"),o.callback=t),Xd(n,o,r),im(n,r)}};function qf(e,t,n,r,a,i){var l=e.stateNode,u=e.type;if("function"==typeof l.shouldComponentUpdate){wc(e,"shouldComponentUpdate");var s=l.shouldComponentUpdate(n,a,i);return kc(),void 0===s&&o(!1,"%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.",Fr(e)||"Component"),s}return!u.prototype||!u.prototype.isPureReactComponent||(!c(t,n)||!c(r,a))}function $f(e,t){t.updater=Hf,e.stateNode=t,function(e,t){e._reactInternalFiber=t}(t,e),t._reactInternalInstance=Af}function Yf(e,t,n){var r=e.type,a=Uc(e),i=function(e){return e.tag===Z&&null!=e.type.contextTypes}(e),l=i?Dc(e,a):f;(Ws||zs&&e.mode&td)&&new r(t,l);var u=new r(t,l),s=e.memoizedState=null!==u.state&&void 0!==u.state?u.state:null;if($f(e,u),"function"==typeof r.getDerivedStateFromProps&&null===s){var c=Fr(e)||"Component";Ff.has(c)||(Ff.add(c),o(!1,"%s: Did not properly initialize state during construction. Expected state to be an object, but it was %s.",c,null===u.state?"null":"undefined"))}if("function"==typeof r.getDerivedStateFromProps||"function"==typeof u.getSnapshotBeforeUpdate){var d=null,p=null,h=null;if("function"==typeof u.componentWillMount&&!0!==u.componentWillMount.__suppressDeprecationWarning?d="componentWillMount":"function"==typeof u.UNSAFE_componentWillMount&&(d="UNSAFE_componentWillMount"),"function"==typeof u.componentWillReceiveProps&&!0!==u.componentWillReceiveProps.__suppressDeprecationWarning?p="componentWillReceiveProps":"function"==typeof u.UNSAFE_componentWillReceiveProps&&(p="UNSAFE_componentWillReceiveProps"),"function"==typeof u.componentWillUpdate&&!0!==u.componentWillUpdate.__suppressDeprecationWarning?h="componentWillUpdate":"function"==typeof u.UNSAFE_componentWillUpdate&&(h="UNSAFE_componentWillUpdate"),null!==d||null!==p||null!==h){var m=Fr(e)||"Component",v="function"==typeof r.getDerivedStateFromProps?"getDerivedStateFromProps()":"getSnapshotBeforeUpdate()";Lf.has(m)||(Lf.add(m),o(!1,"Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://fb.me/react-async-component-lifecycle-hooks",m,v,null!==d?"\n "+d:"",null!==p?"\n "+p:"",null!==h?"\n "+h:""))}}return i&&Ac(e,a,l),u}function Qf(e,t,n,r){var a=t.state;if(wc(e,"componentWillReceiveProps"),"function"==typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(n,r),"function"==typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(n,r),kc(),t.state!==a){var i=Fr(e)||"Component";Mf.has(i)||(Mf.add(i),o(!1,"%s.componentWillReceiveProps(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",i)),Hf.enqueueReplaceState(t,t.state,null)}}function Kf(e,t){var n=e.type;!function(e){var t=e.stateNode,n=e.type,r=Fr(e)||"Component";t.render||(n.prototype&&"function"==typeof n.prototype.render?o(!1,"%s(...): No `render` method found on the returned component instance: did you accidentally return an object from the constructor?",r):o(!1,"%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.",r)),!t.getInitialState||t.getInitialState.isReactClassApproved||t.state||o(!1,"getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",r),!t.getDefaultProps||t.getDefaultProps.isReactClassApproved||o(!1,"getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",r),!t.propTypes||o(!1,"propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.",r),!t.contextTypes||o(!1,"contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.",r),"function"!=typeof t.componentShouldUpdate||o(!1,"%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",r),n.prototype&&n.prototype.isPureReactComponent&&void 0!==t.shouldComponentUpdate&&o(!1,"%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.",Fr(e)||"A pure component"),"function"!=typeof t.componentDidUnmount||o(!1,"%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?",r),"function"!=typeof t.componentDidReceiveProps||o(!1,"%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().",r),"function"!=typeof t.componentWillRecieveProps||o(!1,"%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",r),"function"!=typeof t.UNSAFE_componentWillRecieveProps||o(!1,"%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?",r);var a=t.props!==e.pendingProps;void 0!==t.props&&a&&o(!1,"%s(...): When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.",r,r),!t.defaultProps||o(!1,"Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.",r,r),"function"!=typeof t.getSnapshotBeforeUpdate||"function"==typeof t.componentDidUpdate||jf.has(n)||(jf.add(n),o(!1,"%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.",Fr(e))),"function"!=typeof t.getDerivedStateFromProps||o(!1,"%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.",r),"function"!=typeof t.getDerivedStateFromCatch||o(!1,"%s: getDerivedStateFromCatch() is defined as an instance method and will be ignored. Instead, declare it as a static method.",r),"function"!=typeof n.getSnapshotBeforeUpdate||o(!1,"%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.",r);var i=t.state;i&&("object"!=typeof i||Df(i))&&o(!1,"%s.state: must be set to an object or null",r),"function"==typeof t.getChildContext&&"object"!=typeof n.childContextTypes&&o(!1,"%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",r)}(e);var r=e.stateNode,a=e.pendingProps,i=Uc(e);r.props=a,r.state=e.memoizedState,r.refs=f,r.context=Dc(e,i),e.mode&td&&(Td.recordUnsafeLifecycleWarnings(e,r),Td.recordLegacyContextWarning(e,r)),Vs&&Td.recordDeprecationWarnings(e,r);var l=e.updateQueue;null!==l&&(ef(e,l,a,r,t),r.state=e.memoizedState);var u=e.type.getDerivedStateFromProps;"function"==typeof u&&(Vf(e,u,a),r.state=e.memoizedState),"function"==typeof n.getDerivedStateFromProps||"function"==typeof r.getSnapshotBeforeUpdate||"function"!=typeof r.UNSAFE_componentWillMount&&"function"!=typeof r.componentWillMount||(!function(e,t){wc(e,"componentWillMount");var n=t.state;"function"==typeof t.componentWillMount&&t.componentWillMount(),"function"==typeof t.UNSAFE_componentWillMount&&t.UNSAFE_componentWillMount(),kc(),n!==t.state&&(o(!1,"%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",Fr(e)||"Component"),Hf.enqueueReplaceState(t,t.state,null))}(e,r),null!==(l=e.updateQueue)&&(ef(e,l,a,r,t),r.state=e.memoizedState)),"function"==typeof r.componentDidMount&&(e.effectTag|=oa)}var Xf=zr.getCurrentFiberStackAddendum,Gf=void 0,Zf=void 0,Jf=void 0,ep=void 0,tp=function(e){};Gf=!1,Zf={},Jf={},ep={},tp=function(e){if(null!==e&&"object"==typeof e&&e._store&&!e._store.validated&&null==e.key){"object"!=typeof e._store&&t(!1,"React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue."),e._store.validated=!0;var n='Each child in an array or iterator should have a unique "key" prop. See https://fb.me/react-warning-keys for more information.'+(Xf()||"");Jf[n]||(Jf[n]=!0,o(!1,'Each child in an array or iterator should have a unique "key" prop. See https://fb.me/react-warning-keys for more information.%s',Xf()))}};var np=Array.isArray;function rp(e,n,r){var a=r.ref;if(null!==a&&"function"!=typeof a&&"object"!=typeof a){if(e.mode&td){var i=Fr(e)||"Component";Zf[i]||(o(!1,'A string ref, "%s", has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using createRef() instead.\n%s\n\nLearn more about using refs safely here:\nhttps://fb.me/react-strict-mode-string-ref',a,Lr(e)),Zf[i]=!0)}if(r._owner){var l=r._owner,u=void 0;if(l){var s=l;s.tag!==Z&&t(!1,"Stateless function components cannot have refs."),u=s.stateNode}u||t(!1,"Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.",a);var c=""+a;if(null!==n&&null!==n.ref&&"function"==typeof n.ref&&n.ref._stringRef===c)return n.ref;var d=function(e){var t=u.refs===f?u.refs={}:u.refs;null===e?delete t[c]:t[c]=e};return d._stringRef=c,d}"string"!=typeof a&&t(!1,"Expected ref to be a function or a string."),r._owner||t(!1,"Element ref was specified as a string (%s) but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a functional component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information.",a)}return a}function op(e,n){if("textarea"!==e.type){var r;r=" If you meant to render a collection of children, use an array instead."+(Xf()||""),t(!1,"Objects are not valid as a React child (found: %s).%s","[object Object]"===Object.prototype.toString.call(n)?"object with keys {"+Object.keys(n).join(", ")+"}":n,r)}}function ap(){var e="Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it."+(Xf()||"");ep[e]||(ep[e]=!0,o(!1,"Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.%s",Xf()||""))}function ip(e){function n(t,n){if(e){var r=t.lastEffect;null!==r?(r.nextEffect=n,t.lastEffect=n):t.firstEffect=t.lastEffect=n,n.nextEffect=null,n.effectTag=ia}}function r(t,r){if(!e)return null;for(var o=r;null!==o;)n(t,o),o=o.sibling;return null}function a(e,t){for(var n=new Map,r=t;null!==r;)null!==r.key?n.set(r.key,r):n.set(r.index,r),r=r.sibling;return n}function i(e,t,n){var r=sd(e,t,n);return r.index=0,r.sibling=null,r}function l(t,n,r){if(t.index=r,!e)return n;var o=t.alternate;if(null!==o){var a=o.index;return a<n?(t.effectTag=ra,n):a}return t.effectTag=ra,n}function u(t){return e&&null===t.alternate&&(t.effectTag=ra),t}function s(e,t,n,r){if(null===t||t.tag!==ne){var o=fd(n,e.mode,r);return o.return=e,o}var a=i(t,n,r);return a.return=e,a}function c(e,t,n,r){if(null!==t&&t.type===n.type){var o=i(t,n.props,r);return o.ref=rp(e,t,n),o.return=e,o._debugSource=n._source,o._debugOwner=n._owner,o}var a=cd(n,e.mode,r);return a.ref=rp(e,t,n),a.return=e,a}function d(e,t,n,r){if(null===t||t.tag!==ee||t.stateNode.containerInfo!==n.containerInfo||t.stateNode.implementation!==n.implementation){var o=pd(n,e.mode,r);return o.return=e,o}var a=i(t,n.children||[],r);return a.return=e,a}function f(e,t,n,r,o){if(null===t||t.tag!==re){var a=dd(n,e.mode,r,o);return a.return=e,a}var l=i(t,n,r);return l.return=e,l}function p(e,t,n){if("string"==typeof t||"number"==typeof t){var r=fd(""+t,e.mode,n);return r.return=e,r}if("object"==typeof t&&null!==t){switch(t.$$typeof){case Cr:var o=cd(t,e.mode,n);return o.ref=rp(e,null,t),o.return=e,o;case Sr:var a=pd(t,e.mode,n);return a.return=e,a}if(np(t)||Mr(t)){var i=dd(t,e.mode,n,null);return i.return=e,i}op(e,t)}return"function"==typeof t&&ap(),null}function h(e,t,n,r){var o=null!==t?t.key:null;if("string"==typeof n||"number"==typeof n)return null!==o?null:s(e,t,""+n,r);if("object"==typeof n&&null!==n){switch(n.$$typeof){case Cr:return n.key===o?n.type===_r?f(e,t,n.props.children,r,o):c(e,t,n,r):null;case Sr:return n.key===o?d(e,t,n,r):null}if(np(n)||Mr(n))return null!==o?null:f(e,t,n,r,null);op(e,n)}return"function"==typeof n&&ap(),null}function m(e,t,n,r,o){if("string"==typeof r||"number"==typeof r)return s(t,e.get(n)||null,""+r,o);if("object"==typeof r&&null!==r){switch(r.$$typeof){case Cr:var a=e.get(null===r.key?n:r.key)||null;return r.type===_r?f(t,a,r.props.children,o,r.key):c(t,a,r,o);case Sr:return d(t,e.get(null===r.key?n:r.key)||null,r,o)}if(np(r)||Mr(r))return f(t,e.get(n)||null,r,o,null);op(t,r)}return"function"==typeof r&&ap(),null}function v(e,t){if("object"!=typeof e||null===e)return t;switch(e.$$typeof){case Cr:case Sr:tp(e);var n=e.key;if("string"!=typeof n)break;if(null===t){(t=new Set).add(n);break}if(!t.has(n)){t.add(n);break}o(!1,"Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.%s",n,Xf())}return t}return function(s,c,d,f){var g="object"==typeof d&&null!==d&&d.type===_r&&null===d.key;g&&(d=d.props.children);var y="object"==typeof d&&null!==d;if(y)switch(d.$$typeof){case Cr:return u(function(e,t,o,a){for(var l=o.key,u=t;null!==u;){if(u.key===l){if(u.tag===re?o.type===_r:u.type===o.type){r(e,u.sibling);var s=i(u,o.type===_r?o.props.children:o.props,a);return s.ref=rp(e,u,o),s.return=e,s._debugSource=o._source,s._debugOwner=o._owner,s}r(e,u);break}n(e,u),u=u.sibling}if(o.type===_r){var c=dd(o.props.children,e.mode,a,o.key);return c.return=e,c}var d=cd(o,e.mode,a);return d.ref=rp(e,t,o),d.return=e,d}(s,c,d,f));case Sr:return u(function(e,t,o,a){for(var l=o.key,u=t;null!==u;){if(u.key===l){if(u.tag===ee&&u.stateNode.containerInfo===o.containerInfo&&u.stateNode.implementation===o.implementation){r(e,u.sibling);var s=i(u,o.children||[],a);return s.return=e,s}r(e,u);break}n(e,u),u=u.sibling}var c=pd(o,e.mode,a);return c.return=e,c}(s,c,d,f))}if("string"==typeof d||"number"==typeof d)return u(function(e,t,n,o){if(null!==t&&t.tag===ne){r(e,t.sibling);var a=i(t,n,o);return a.return=e,a}r(e,t);var l=fd(n,e.mode,o);return l.return=e,l}(s,c,""+d,f));if(np(d))return function(t,o,i,u){for(var s=null,c=0;c<i.length;c++)s=v(i[c],s);for(var d=null,f=null,g=o,y=0,b=0,w=null;null!==g&&b<i.length;b++){g.index>b?(w=g,g=null):w=g.sibling;var k=h(t,g,i[b],u);if(null===k){null===g&&(g=w);break}e&&g&&null===k.alternate&&n(t,g),y=l(k,y,b),null===f?d=k:f.sibling=k,f=k,g=w}if(b===i.length)return r(t,g),d;if(null===g){for(;b<i.length;b++){var x=p(t,i[b],u);x&&(y=l(x,y,b),null===f?d=x:f.sibling=x,f=x)}return d}for(var T=a(0,g);b<i.length;b++){var C=m(T,t,b,i[b],u);C&&(e&&null!==C.alternate&&T.delete(null===C.key?b:C.key),y=l(C,y,b),null===f?d=C:f.sibling=C,f=C)}return e&&T.forEach(function(e){return n(t,e)}),d}(s,c,d,f);if(Mr(d))return function(i,u,s,c){var d=Mr(s);"function"!=typeof d&&t(!1,"An object is not an iterable. This error is likely caused by a bug in React. Please file an issue."),s.entries===d&&(Gf||o(!1,"Using Maps as children is unsupported and will likely yield unexpected results. Convert it to a sequence/iterable of keyed ReactElements instead.%s",Xf()),Gf=!0);var f=d.call(s);if(f)for(var g=null,y=f.next();!y.done;y=f.next())g=v(y.value,g);var b=d.call(s);null==b&&t(!1,"An iterable object provided no iterator.");for(var w=null,k=null,x=u,T=0,C=0,S=null,_=b.next();null!==x&&!_.done;C++,_=b.next()){x.index>C?(S=x,x=null):S=x.sibling;var E=h(i,x,_.value,c);if(null===E){x||(x=S);break}e&&x&&null===E.alternate&&n(i,x),T=l(E,T,C),null===k?w=E:k.sibling=E,k=E,x=S}if(_.done)return r(i,x),w;if(null===x){for(;!_.done;C++,_=b.next()){var P=p(i,_.value,c);null!==P&&(T=l(P,T,C),null===k?w=P:k.sibling=P,k=P)}return w}for(var R=a(0,x);!_.done;C++,_=b.next()){var N=m(R,i,C,_.value,c);null!==N&&(e&&null!==N.alternate&&R.delete(null===N.key?C:N.key),T=l(N,T,C),null===k?w=N:k.sibling=N,k=N)}return e&&R.forEach(function(e){return n(i,e)}),w}(s,c,d,f);if(y&&op(s,d),"function"==typeof d&&ap(),void 0===d&&!g)switch(s.tag){case Z:if(s.stateNode.render._isMockFunction)break;case G:var b=s.type;t(!1,"%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.",b.displayName||b.name||"Component")}return r(s,c)}}var lp=ip(!0),up=ip(!1);var sp=null,cp=null,dp=!1;function fp(e,t){switch(e.tag){case J:!function(e,t){1===t.nodeType?as(e,t):is(e,t)}(e.stateNode.containerInfo,t);break;case te:!function(e,t,n,r){!0!==t[fs]&&(1===r.nodeType?as(n,r):is(n,r))}(e.type,e.memoizedProps,e.stateNode,t)}var n=function(){var e=ud(te,null,null,Jc);return e.type="DELETED",e}();n.stateNode=t,n.return=e,n.effectTag=ia,null!==e.lastEffect?(e.lastEffect.nextEffect=n,e.lastEffect=n):e.firstEffect=e.lastEffect=n}function pp(e,t){switch(t.effectTag|=ra,e.tag){case J:var n=e.stateNode.containerInfo;switch(t.tag){case te:!function(e,t,n){ls(e,t,n)}(n,t.type,t.pendingProps);break;case ne:!function(e,t){us(e,t)}(n,t.pendingProps)}break;case te:e.type;var r=e.memoizedProps,o=e.stateNode;switch(t.tag){case te:!function(e,t,n,r,o){!0!==t[fs]&&ls(n,r,o)}(0,r,o,t.type,t.pendingProps);break;case ne:!function(e,t,n,r){!0!==t[fs]&&us(n,r)}(0,r,o,t.pendingProps)}break;default:return}}function hp(e,t){switch(e.tag){case te:var n=e.type,r=(e.pendingProps,function(e,t,n){return e.nodeType!==ur||t.toLowerCase()!==e.nodeName.toLowerCase()?null:e}(t,n));return null!==r&&(e.stateNode=r,!0);case ne:var o=function(e,t){return""===t||e.nodeType!==sr?null:e}(t,e.pendingProps);return null!==o&&(e.stateNode=o,!0);default:return!1}}function mp(e){if(dp){var t=cp;if(!t)return pp(sp,e),dp=!1,void(sp=e);var n=t;if(!hp(e,t)){if(!(t=Ds(n))||!hp(e,t))return pp(sp,e),dp=!1,void(sp=e);fp(sp,n)}sp=e,cp=Ms(t)}}function vp(e,n,r){As||t(!1,"Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");var o=function(e,t,n,r,o,a){var i;return cs(a,e),ds(e,n),i=o.namespace,ns(e,t,n,i,r)}(e.stateNode,e.type,e.memoizedProps,n,r,e);return e.updateQueue=o,null!==o}function gp(e){As||t(!1,"Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.");var n=e.stateNode,r=e.memoizedProps,o=function(e,t,n){return cs(n,e),rs(e,t)}(n,r,e);if(o){var a=sp;if(null!==a)switch(a.tag){case J:a.stateNode.containerInfo;!function(e,t,n){os(t,n)}(0,n,r);break;case te:a.type;var i=a.memoizedProps;a.stateNode;!function(e,t,n,r,o){!0!==t[fs]&&os(r,o)}(0,i,0,n,r)}}return o}function yp(e){for(var t=e.return;null!==t&&t.tag!==te&&t.tag!==J;)t=t.return;sp=t}function bp(e){if(!As)return!1;if(e!==sp)return!1;if(!dp)return yp(e),dp=!0,!1;var t=e.type;if(e.tag!==te||"head"!==t&&"body"!==t&&!bs(t,e.memoizedProps))for(var n=cp;n;)fp(e,n),n=Ds(n);return yp(e),cp=sp?Ds(e.stateNode):null,!0}function wp(){As&&(sp=null,cp=null,dp=!1)}var kp=zr.getCurrentFiberStackAddendum,xp=void 0,Tp=void 0,Cp=void 0;function Sp(e,t,n){_p(e,t,n,t.expirationTime)}function _p(e,t,n,r){t.child=null===e?up(t,null,n,r):lp(t,e.child,n,r)}function Ep(e,t){var n=t.ref;(null===e&&null!==n||null!==e&&e.ref!==n)&&(t.effectTag|=ca)}function Pp(e,t,n){var r=Bc(t),o=void 0;return null===e?null===t.stateNode?(Yf(t,t.pendingProps),Kf(t,n),o=!0):o=function(e,t){var n=e.type,r=e.stateNode,o=e.memoizedProps,a=e.pendingProps;r.props=o;var i=r.context,l=Dc(e,Uc(e)),u=n.getDerivedStateFromProps,s="function"==typeof u||"function"==typeof r.getSnapshotBeforeUpdate;s||"function"!=typeof r.UNSAFE_componentWillReceiveProps&&"function"!=typeof r.componentWillReceiveProps||o===a&&i===l||Qf(e,r,a,l),nf();var c=e.memoizedState,d=r.state=c,f=e.updateQueue;if(null!==f&&(ef(e,f,a,r,t),d=e.memoizedState),o===a&&c===d&&!Mc()&&!rf())return"function"==typeof r.componentDidMount&&(e.effectTag|=oa),!1;"function"==typeof u&&(Vf(e,u,a),d=e.memoizedState);var p=rf()||qf(e,o,a,c,d,l);return p?(s||"function"!=typeof r.UNSAFE_componentWillMount&&"function"!=typeof r.componentWillMount||(wc(e,"componentWillMount"),"function"==typeof r.componentWillMount&&r.componentWillMount(),"function"==typeof r.UNSAFE_componentWillMount&&r.UNSAFE_componentWillMount(),kc()),"function"==typeof r.componentDidMount&&(e.effectTag|=oa)):("function"==typeof r.componentDidMount&&(e.effectTag|=oa),e.memoizedProps=a,e.memoizedState=d),r.props=a,r.state=d,r.context=l,p}(t,n):o=function(e,t,n){var r=t.type,o=t.stateNode,a=t.memoizedProps,i=t.pendingProps;o.props=a;var l=o.context,u=Dc(t,Uc(t)),s=r.getDerivedStateFromProps,c="function"==typeof s||"function"==typeof o.getSnapshotBeforeUpdate;c||"function"!=typeof o.UNSAFE_componentWillReceiveProps&&"function"!=typeof o.componentWillReceiveProps||a===i&&l===u||Qf(t,o,i,u),nf();var d=t.memoizedState,f=o.state=d,p=t.updateQueue;if(null!==p&&(ef(t,p,i,o,n),f=t.memoizedState),a===i&&d===f&&!Mc()&&!rf())return"function"==typeof o.componentDidUpdate&&(a===e.memoizedProps&&d===e.memoizedState||(t.effectTag|=oa)),"function"==typeof o.getSnapshotBeforeUpdate&&(a===e.memoizedProps&&d===e.memoizedState||(t.effectTag|=da)),!1;"function"==typeof s&&(Vf(t,s,i),f=t.memoizedState);var h=rf()||qf(t,a,i,d,f,u);return h?(c||"function"!=typeof o.UNSAFE_componentWillUpdate&&"function"!=typeof o.componentWillUpdate||(wc(t,"componentWillUpdate"),"function"==typeof o.componentWillUpdate&&o.componentWillUpdate(i,f,u),"function"==typeof o.UNSAFE_componentWillUpdate&&o.UNSAFE_componentWillUpdate(i,f,u),kc()),"function"==typeof o.componentDidUpdate&&(t.effectTag|=oa),"function"==typeof o.getSnapshotBeforeUpdate&&(t.effectTag|=da)):("function"==typeof o.componentDidUpdate&&(a===e.memoizedProps&&d===e.memoizedState||(t.effectTag|=oa)),"function"==typeof o.getSnapshotBeforeUpdate&&(a===e.memoizedProps&&d===e.memoizedState||(t.effectTag|=da)),t.memoizedProps=i,t.memoizedState=f),o.props=i,o.state=f,o.context=u,h}(e,t,n),Rp(e,t,o,r,n)}function Rp(e,t,n,r,o){Ep(e,t);var a=(t.effectTag&sa)!==ta;if(!n&&!a)return r&&Vc(t,!1),Ap(e,t);var i=t.type,l=t.stateNode;wr.current=t;var u=void 0;return!a||js&&"function"==typeof i.getDerivedStateFromCatch?(zr.setCurrentPhase("render"),u=l.render(),(Ws||zs&&t.mode&td)&&l.render(),zr.setCurrentPhase(null)):(u=null,qs&&If()),t.effectTag|=na,a&&(_p(e,t,null,o),t.child=null),_p(e,t,u,o),function(e,t){e.memoizedState=t}(t,l.state),Dp(t,l.props),r&&Vc(t,!0),t.child}function Np(e){var t=e.stateNode;t.pendingContext?Wc(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Wc(e,t.context,!1),bf(e,t.containerInfo)}function Op(e,t,n){Np(t);var r=t.updateQueue;if(null!==r){var o=t.pendingProps,a=t.memoizedState,i=null!==a?a.element:null;ef(t,r,o,null,n);var l=t.memoizedState.element;if(l===i)return wp(),Ap(e,t);var u=t.stateNode;return(null===e||null===e.child)&&u.hydrate&&function(e){if(!As)return!1;var t=e.stateNode.containerInfo;return cp=Ms(t),sp=e,dp=!0,!0}(t)?(t.effectTag|=ra,t.child=up(t,null,l,n)):(wp(),Sp(e,t,l)),t.child}return wp(),Ap(e,t)}function Ip(e,t,n,r){var o=e.child;for(null!==o&&(o.return=e);null!==o;){var a=void 0;switch(o.tag){case ae:var i=0|o.stateNode;if(o.type===t&&0!=(i&n)){for(var l=o;null!==l;){var u=l.alternate;if(l.expirationTime===qc||l.expirationTime>r)l.expirationTime=r,null!==u&&(u.expirationTime===qc||u.expirationTime>r)&&(u.expirationTime=r);else{if(null===u||!(u.expirationTime===qc||u.expirationTime>r))break;u.expirationTime=r}l=l.return}a=null}else a=o.child;break;case ie:a=o.type===e.type?null:o.child;break;default:a=o.child}if(null!==a)a.return=o;else for(a=o;null!==a;){if(a===e){a=null;break}var s=a.sibling;if(null!==s){s.return=a.return,a=s;break}a=a.return}o=a}}function Up(e,t,n){var r=t.type,a=t.pendingProps,i=t.memoizedProps,l=function(e){return Ts?e._currentValue:e._currentValue2}(r),u=function(e){return Ts?e._changedBits:e._changedBits2}(r);if(Mc());else if(0===u&&i===a)return Ap(e,t);t.memoizedProps=a;var s=a.unstable_observedBits;if(void 0!==s&&null!==s||(s=Hc),t.stateNode=s,0!=(u&s))Ip(t,r,u,n);else if(i===a)return Ap(e,t);var c=a.children;"function"!=typeof c&&o(!1,"A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it.");var d;return wr.current=t,zr.setCurrentPhase("render"),d=c(l),zr.setCurrentPhase(null),t.effectTag|=na,Sp(e,t,d),t.child}function Ap(e,n){return gc(n),qs&&If(),function(e,n){if(null!==e&&n.child!==e.child&&t(!1,"Resuming work not yet implemented."),null!==n.child){var r=n.child,o=sd(r,r.pendingProps,r.expirationTime);for(n.child=o,o.return=n;null!==r.sibling;)r=r.sibling,(o=o.sibling=sd(r,r.pendingProps,r.expirationTime)).return=n;o.sibling=null}}(e,n),n.child}function Dp(e,t){e.memoizedProps=t}function Mp(e,n,r){if(qs&&n.mode&nd&&function(e){qs&&(Sf.push(e),e.actualDuration=xs()-e.actualDuration-Ef,e.actualStartTime=xs())}(n),n.expirationTime===qc||n.expirationTime>r)return function(e,t){switch(gc(t),qs&&If(),t.tag){case J:Np(t);break;case Z:Bc(t);break;case ee:bf(t,t.stateNode.containerInfo);break;case ie:df(t)}return null}(0,n);switch(n.tag){case X:return function(e,n,r){null!==e&&t(!1,"An indeterminate component should never have mounted. This error is likely caused by a bug in React. Please file an issue.");var a,i=n.type,l=n.pendingProps,u=Dc(n,Uc(n));if(i.prototype&&"function"==typeof i.prototype.render){var s=Fr(n)||"Unknown";xp[s]||(o(!1,"The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.",s,s),xp[s]=!0)}if(n.mode&td&&Td.recordLegacyContextWarning(n,null),wr.current=n,a=i(l,u),n.effectTag|=na,"object"==typeof a&&null!==a&&"function"==typeof a.render&&void 0===a.$$typeof){var c=n.type;n.tag=Z,n.memoizedState=null!==a.state&&void 0!==a.state?a.state:null;var d=c.getDerivedStateFromProps;"function"==typeof d&&Vf(n,d,l);var f=Bc(n);return $f(n,a),Kf(n,r),Rp(e,n,!0,f,r)}n.tag=G;var p=n.type;if(p&&p.childContextTypes&&o(!1,"%s(...): childContextTypes cannot be defined on a functional component.",p.displayName||p.name||"Component"),null!==n.ref){var h="",m=zr.getCurrentFiberOwnerName();m&&(h+="\n\nCheck the render method of `"+m+"`.");var v=m||n._debugID||"",g=n._debugSource;g&&(v=g.fileName+":"+g.lineNumber),Cp[v]||(Cp[v]=!0,o(!1,"Stateless function components cannot be given refs. Attempts to access this ref will fail.%s%s",h,zr.getCurrentFiberStackAddendum()))}if("function"==typeof i.getDerivedStateFromProps){var y=Fr(n)||"Unknown";Tp[y]||(o(!1,"%s: Stateless functional components do not support getDerivedStateFromProps.",y),Tp[y]=!0)}return Sp(e,n,a),Dp(n,l),n.child}(e,n,r);case G:return function(e,t){var n=t.type,r=t.pendingProps;if(Mc());else if(t.memoizedProps===r)return Ap(e,t);var o,a=Dc(t,Uc(t));return wr.current=t,zr.setCurrentPhase("render"),o=n(r,a),zr.setCurrentPhase(null),t.effectTag|=na,Sp(e,t,o),Dp(t,r),t.child}(e,n);case Z:return Pp(e,n,r);case J:return Op(e,n,r);case te:return function(e,t,n){xf(t),null===e&&mp(t);var r=t.type,o=t.memoizedProps,a=t.pendingProps,i=null!==e?e.memoizedProps:null;if(Mc());else if(o===a){var l=t.mode&ed&&ws(0,a);if(l&&(t.expirationTime=Yc),!l||n!==Yc)return Ap(e,t)}var u=a.children;return bs(r,a)?u=null:i&&bs(r,i)&&(t.effectTag|=la),Ep(e,t),n!==Yc&&t.mode&ed&&ws(0,a)?(t.expirationTime=Yc,t.memoizedProps=a,null):(Sp(e,t,u),Dp(t,a),t.child)}(e,n,r);case ne:return function(e,t){return null===e&&mp(t),Dp(t,t.pendingProps),null}(e,n);case se:return function(e,t,n){if(Ls){var r=t.pendingProps,o=t.memoizedProps,a=t.memoizedState,i=!((t.effectTag&sa)===ta);if(Mc());else if(r===o&&i===a)return Ap(e,t);var l=(0,r.children)(i);return t.memoizedProps=r,t.memoizedState=i,Sp(e,t,l),t.child}return null}(e,n);case ee:return function(e,t,n){bf(t,t.stateNode.containerInfo);var r=t.pendingProps;if(Mc());else if(t.memoizedProps===r)return Ap(e,t);return null===e?(t.child=lp(t,null,r,n),Dp(t,r)):(Sp(e,t,r),Dp(t,r)),t.child}(e,n,r);case le:return function(e,t){var n,r=t.type.render,o=t.pendingProps,a=t.ref;if(Mc());else if(t.memoizedProps===o&&a===(null!==e?e.ref:null))return Ap(e,t);return wr.current=t,zr.setCurrentPhase("render"),n=r(o,a),zr.setCurrentPhase(null),Sp(e,t,n),Dp(t,o),t.child}(e,n);case re:return function(e,t){var n=t.pendingProps;if(Mc());else if(t.memoizedProps===n)return Ap(e,t);return Sp(e,t,n),Dp(t,n),t.child}(e,n);case oe:return function(e,t){var n=t.pendingProps.children;if(Mc());else if(null===n||t.memoizedProps===n)return Ap(e,t);return Sp(e,t,n),Dp(t,n),t.child}(e,n);case ue:return function(e,t){var n=t.pendingProps;return qs&&(t.effectTag|=oa),t.memoizedProps===n?Ap(e,t):(Sp(e,t,n.children),Dp(t,n),t.child)}(e,n);case ie:return function(e,t,n){var r=t.type._context,a=t.pendingProps,i=t.memoizedProps,l=!0;if(Mc())l=!1;else if(i===a)return t.stateNode=0,df(t),Ap(e,t);var s=a.value;t.memoizedProps=a;var c=t.type.propTypes;c&&u(c,a,"prop","Context.Provider",kp);var d=void 0;if(null===i)d=Hc;else if(i.value===a.value){if(i.children===a.children&&l)return t.stateNode=0,df(t),Ap(e,t);d=0}else{var f=i.value;if(f===s&&(0!==f||1/f==1/s)||f!=f&&s!=s){if(i.children===a.children&&l)return t.stateNode=0,df(t),Ap(e,t);d=0}else if(((d="function"==typeof r._calculateChangedBits?r._calculateChangedBits(f,s):Hc)&Hc)!==d&&o(!1,"calculateChangedBits: Expected the return value to be a 31-bit integer. Instead received: %s",d),0==(d|=0)){if(i.children===a.children&&l)return t.stateNode=0,df(t),Ap(e,t)}else Ip(t,r,d,n)}return t.stateNode=d,df(t),Sp(e,t,a.children),t.child}(e,n,r);case ae:return Up(e,n,r);default:t(!1,"Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.")}}function Fp(e){e.effectTag|=oa}function jp(e){e.effectTag|=ca}function Lp(e,t){for(var n=t.child;null!==n;){if(n.tag===te||n.tag===ne)gs(e,n.stateNode);else if(n.tag===ee);else if(null!==n.child){n.child.return=n,n=n.child;continue}if(n===t)return;for(;null===n.sibling;){if(null===n.return||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}}xp={},Tp={},Cp={};var Wp=void 0,zp=void 0,Bp=void 0;if(_s)Wp=function(e){},zp=function(e,t,n,r,o,a,i,l){t.updateQueue=n,n&&Fp(t)},Bp=function(e,t,n,r){n!==r&&Fp(t)};else if(qu){Wp=function(e){var t=e.stateNode;if(null===e.firstEffect);else{var n=t.containerInfo,r=Yu(n);!function(e,t){for(var n=t.child;null!==n;){if(n.tag===te||n.tag===ne)Qu(e,n.stateNode);else if(n.tag===ee);else if(null!==n.child){n.child.return=n,n=n.child;continue}if(n===t)return;for(;null===n.sibling;){if(null===n.return||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}}(r,e),t.pendingChildren=r,Fp(e),Ku(n,r)}},zp=function(e,t,n,r,o,a,i,l){var u=null===t.firstEffect,s=e.stateNode;if(u&&null===n)t.stateNode=s;else{var c=t.stateNode,d=$u(s,n,r,o,a,t,u,c);ys(d,r,a,i)&&Fp(t),t.stateNode=d,u?Fp(t):Lp(d,t)}},Bp=function(e,t,n,r){if(n!==r){var o=yf(),a=kf();t.stateNode=ks(r,o,a,t),Fp(t)}}}else Wp=function(e){},zp=function(e,t,n,r,o,a,i,l){},Bp=function(e,t,n,r){};function Vp(e,n,r){var o=n.pendingProps;switch(qs&&n.mode&nd&&Rf(n),n.tag){case G:return null;case Z:return jc(n),null;case J:wf(n),Lc(n);var a=n.stateNode;return a.pendingContext&&(a.context=a.pendingContext,a.pendingContext=null),null!==e&&null!==e.child||(bp(n),n.effectTag&=~ra),Wp(n),null;case te:Tf(n);var i=yf(),l=n.type;if(null!==e&&null!=n.stateNode){var u=e.memoizedProps,s=n.stateNode,c=kf(),d=function(e,t,n,r,o,a){var i=a;if(typeof r.children!=typeof n.children&&("string"==typeof r.children||"number"==typeof r.children)){var l=""+r.children,u=ss(i.ancestorInfo,t,null);Vu(null,l,u)}return es(e,t,n,r,o)}(s,l,u,o,i,c);zp(e,n,d,l,u,o,i,c),e.ref!==n.ref&&jp(n)}else{if(!o)return null===n.stateNode&&t(!1,"We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."),null;var f=kf();if(bp(n))vp(n,i,f)&&Fp(n);else{var p=function(e,t,n,r,o){var a,i=r;if(Vu(e,null,i.ancestorInfo),"string"==typeof t.children||"number"==typeof t.children){var l=""+t.children,u=ss(i.ancestorInfo,e,null);Vu(null,l,u)}a=i.namespace;var s=Gu(e,t,n,a);return cs(o,s),ds(s,t),s}(l,o,i,f,n);Lp(p,n),ys(p,l,o,i)&&Fp(n),n.stateNode=p}null!==n.ref&&jp(n)}return null;case ne:var h=o;if(e&&null!=n.stateNode){var m=e.memoizedProps;Bp(e,n,m,h)}else{if("string"!=typeof h)return null===n.stateNode&&t(!1,"We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."),null;var v=yf(),g=kf();bp(n)?gp(n)&&Fp(n):n.stateNode=ks(h,v,g,n)}return null;case le:case se:case re:case oe:case ue:return null;case ee:return wf(n),Wp(n),null;case ie:return ff(n),null;case ae:return null;case X:t(!1,"An indeterminate component should have become determinate before completing. This error is likely caused by a bug in React. Please file an issue.");default:t(!1,"Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.")}}var Hp=y.invokeGuardedCallback,qp=y.hasCaughtError,$p=y.clearCaughtError,Yp=null;function Qp(e,t){var n=t.source,r=t.stack;null===r&&null!==n&&(r=Lr(n));var o={componentName:null!==n?Fr(n):null,componentStack:null!==r?r:"",error:t.value,errorBoundary:null,errorBoundaryName:null,errorBoundaryFound:!1,willRetry:!1};null!==e&&e.tag===Z&&(o.errorBoundary=e.stateNode,o.errorBoundaryName=Fr(e),o.errorBoundaryFound=!0,o.willRetry=!0);try{!function(e){var t=e.error;if(!t||!t.suppressReactErrorLogging){var n=e.componentName,r=e.componentStack,o=e.errorBoundaryName,a=e.errorBoundaryFound,i=e.willRetry,l=(n?"The above error occurred in the <"+n+"> component:":"The above error occurred in one of your React components:")+r+"\n\n"+(a&&o?i?"React will try to recreate this component tree from scratch using the error boundary you provided, "+o+".":"This error was initially handled by the error boundary "+o+".\nRecreating the tree from scratch failed so React will unmount the tree.":"Consider adding an error boundary to your tree to customize error handling behavior.\nVisit https://fb.me/react-error-boundaries to learn more about error boundaries.");console.error(l)}}(o)}catch(e){e&&e.suppressReactErrorLogging||console.error(e)}}Yp=new Set;var Kp=function(e,t){wc(e,"componentWillUnmount"),t.props=e.memoizedProps,t.state=e.memoizedState,t.componentWillUnmount(),kc()};function Xp(e){var t=e.ref;null!==t&&("function"==typeof t?(Hp(null,t,null,null),qp()&&tm(e,$p())):t.current=null)}function Gp(e,n){switch(n.tag){case Z:if(n.effectTag&da&&null!==e){var r=e.memoizedProps,a=e.memoizedState;wc(n,"getSnapshotBeforeUpdate");var i=n.stateNode;i.props=n.memoizedProps,i.state=n.memoizedState;var l=i.getSnapshotBeforeUpdate(r,a),u=Yp;void 0!==l||u.has(n.type)||(u.add(n.type),o(!1,"%s.getSnapshotBeforeUpdate(): A snapshot value (or null) must be returned. You have returned undefined.",Fr(n))),i.__reactInternalSnapshotBeforeUpdate=l,kc()}return;case J:case te:case ne:case ee:return;default:t(!1,"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.")}}function Zp(e,n,r,o,a){switch(r.tag){case Z:var i=r.stateNode;if(r.effectTag&oa)if(null===n)wc(r,"componentDidMount"),i.props=r.memoizedProps,i.state=r.memoizedState,i.componentDidMount(),kc();else{var l=n.memoizedProps,u=n.memoizedState;wc(r,"componentDidUpdate"),i.props=r.memoizedProps,i.state=r.memoizedState,i.componentDidUpdate(l,u,i.__reactInternalSnapshotBeforeUpdate),kc()}var s=r.updateQueue;return void(null!==s&&(i.props=r.memoizedProps,i.state=r.memoizedState,of(0,s,i)));case J:var c=r.updateQueue;if(null!==c){var d=null;if(null!==r.child)switch(r.child.tag){case te:d=vs(r.child.stateNode);break;case Z:d=r.child.stateNode}of(0,c,d)}return;case te:var f=r.stateNode;if(null===n&&r.effectTag&oa)!function(e,t,n,r){ms(t,n)&&e.focus()}(f,r.type,r.memoizedProps);return;case ne:case ee:case ue:case se:return;default:t(!1,"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.")}}function Jp(e){var t=e.ref;if(null!==t){var n=e.stateNode,r=void 0;switch(e.tag){case te:r=vs(n);break;default:r=n}"function"==typeof t?t(r):(t.hasOwnProperty("current")||o(!1,"Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().%s",Fr(e),Lr(e)),t.current=r)}}function eh(e){var t=e.ref;null!==t&&("function"==typeof t?t(null):t.current=null)}function th(e){switch(kd(e),e.tag){case Z:Xp(e);var t=e.stateNode;return void("function"==typeof t.componentWillUnmount&&function(e,t){Hp(null,Kp,null,e,t),qp()&&tm(e,$p())}(e,t));case te:return void Xp(e);case ee:return void(_s?ah(e):qu&&function(e){if(!qu)return;var t=e.stateNode.containerInfo,n=Yu(t);Xu(t,n)}(e))}}function nh(e){for(var t=e;;)if(th(t),null===t.child||_s&&t.tag===ee){if(t===e)return;for(;null===t.sibling;){if(null===t.return||t.return===e)return;t=t.return}t.sibling.return=t.return,t=t.sibling}else t.child.return=t,t=t.child}function rh(e){return e.tag===te||e.tag===J||e.tag===ee}function oh(e){if(_s){var n=function(e){for(var n=e.return;null!==n;){if(rh(n))return n;n=n.return}t(!1,"Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.")}(e),r=void 0,o=void 0;switch(n.tag){case te:r=n.stateNode,o=!1;break;case J:case ee:r=n.stateNode.containerInfo,o=!0;break;default:t(!1,"Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.")}n.effectTag&la&&(Es(r),n.effectTag&=~la);for(var a=function(e){var t=e;e:for(;;){for(;null===t.sibling;){if(null===t.return||rh(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==te&&t.tag!==ne;){if(t.effectTag&ra)continue e;if(null===t.child||t.tag===ee)continue e;t.child.return=t,t=t.child}if(!(t.effectTag&ra))return t.stateNode}}(e),i=e;;){if(i.tag===te||i.tag===ne)a?o?Os(r,i.stateNode,a):Ns(r,i.stateNode,a):o?Rs(r,i.stateNode):Ps(r,i.stateNode);else if(i.tag===ee);else if(null!==i.child){i.child.return=i,i=i.child;continue}if(i===e)return;for(;null===i.sibling;){if(null===i.return||i.return===e)return;i=i.return}i.sibling.return=i.return,i=i.sibling}}}function ah(e){for(var n=e,r=!1,o=void 0,a=void 0;;){if(!r){var i=n.return;e:for(;;){switch(null===i&&t(!1,"Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."),i.tag){case te:o=i.stateNode,a=!1;break e;case J:case ee:o=i.stateNode.containerInfo,a=!0;break e}i=i.return}r=!0}if(n.tag===te||n.tag===ne)nh(n),a?Us(o,n.stateNode):Is(o,n.stateNode);else if(n.tag===ee){if(o=n.stateNode.containerInfo,null!==n.child){n.child.return=n,n=n.child;continue}}else if(th(n),null!==n.child){n.child.return=n,n=n.child;continue}if(n===e)return;for(;null===n.sibling;){if(null===n.return||n.return===e)return;(n=n.return).tag===ee&&(r=!1)}n.sibling.return=n.return,n=n.sibling}}function ih(e){_s?ah(e):nh(e),function(e){e.return=null,e.child=null,e.alternate&&(e.alternate.child=null,e.alternate.return=null)}(e)}function lh(e,n){if(_s)switch(n.tag){case Z:return;case te:var r=n.stateNode;if(null!=r){var o=n.memoizedProps,a=null!==e?e.memoizedProps:o,i=n.type,l=n.updateQueue;n.updateQueue=null,null!==l&&function(e,t,n,r,o,a){ds(e,o),ts(e,t,n,r,o)}(r,l,i,a,o)}return;case ne:null===n.stateNode&&t(!1,"This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.");var u=n.stateNode,s=n.memoizedProps;null!==e&&e.memoizedProps;return void function(e,t,n){e.nodeValue=n}(u,0,s);case J:return;case ue:if(qs)(0,n.memoizedProps.onRender)(n.memoizedProps.id,null===e?"mount":"update",n.actualDuration,n.treeBaseTime,n.actualStartTime,Cf);return;case se:return;default:t(!1,"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.")}else!function(e){if(qu)switch(e.tag){case Z:case te:case ne:return;case J:case ee:var n=e.stateNode,r=n.containerInfo,o=n.pendingChildren;return void Xu(r,o);default:t(!1,"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.")}}(n)}function uh(e){_s&&Es(e.stateNode)}function sh(e,t,n){var r=Qd(n);r.tag=zd,r.payload={element:null};var o=t.value;return r.callback=function(){Wm(o),Qp(e,t)},r}function ch(e,t,n){var r=Qd(n);r.tag=zd;var o=e.type.getDerivedStateFromCatch;if(js&&"function"==typeof o){var a=t.value;r.payload=function(){return o(a)}}var i=e.stateNode;return null!==i&&"function"==typeof i.componentDidCatch&&(r.callback=function(){js&&"function"===o||function(e){null===Fh?Fh=new Set([e]):Fh.add(e)}(this);var n=t.value,r=t.stack;Qp(e,t),this.componentDidCatch(n,{componentStack:null!==r?r:""})}),r}function dh(e){var t=om(lm(),e);Xd(e,Qd(t),t),im(e,t)}function fh(e,t,n,r,o,a,i){if(n.effectTag|=pa,n.firstEffect=n.lastEffect=null,Ls&&null!==r&&"object"==typeof r&&"function"==typeof r.then){var l=r,u=Gc(a),s=i-(u-5e3);s<0&&(s=0);var c=u-i,d=t,f=-1;e:do{if(d.tag===se){var p=d.alternate;if(null!==p&&!0===p.memoizedState){f=0;break e}var h=d.pendingProps.ms;if("number"==typeof h){if(h<=0){f=0;break e}(-1===f||h<f)&&(f=h)}else-1===f&&(f=c)}d=d.return}while(null!==d);var m=f-s;if(a===Yc||m>0){!function(e,t,n,r){n>=0&&Ih<n&&(Ih=n)}(0,0,m);var v=function(){am(e,a)};return void l.then(v,v)}d=t;do{switch(d.tag){case J:r=new Error(a===$c?"A synchronous update was suspended, but no fallback UI was provided.":"An update was suspended for longer than the timeout, but no fallback UI was provided.");break;case se:if((d.effectTag&sa)===ta){d.effectTag|=ha;var g=dh.bind(null,d);return void l.then(g,g)}}d=d.return}while(null!==d)}r=af(r,n);var y=t;do{switch(y.tag){case J:var b=r;return y.effectTag|=ha,void Gd(y,sh(y,b,a),a);case Z:var w=r,k=y.type,x=y.stateNode;if((y.effectTag&sa)===ta&&("function"==typeof k.getDerivedStateFromCatch&&js||null!==x&&"function"==typeof x.componentDidCatch&&!Qh(x)))return y.effectTag|=ha,void Gd(y,ch(y,w,a),a)}y=y.return}while(null!==y)}function ph(e,t,n){switch(qs&&e.mode&nd&&Rf(e),e.tag){case Z:jc(e);var r=e.effectTag;return r&ha?(e.effectTag=r&~ha|sa,e):null;case J:wf(e),Lc(e);var o=e.effectTag;return o&ha?(e.effectTag=o&~ha|sa,e):null;case te:return Tf(e),null;case se:var a=e.effectTag;return a&ha?(e.effectTag=a&~ha|sa,e):null;case ee:return wf(e),null;case ie:return ff(e),null;default:return null}}function hh(e){switch(qs&&e.mode&nd&&(Nf(),Rf(e)),e.tag){case Z:jc(e);break;case J:wf(e),Lc(e);break;case te:Tf(e);break;case ee:wf(e);break;case ie:ff(e)}}var mh=y.invokeGuardedCallback,vh=y.hasCaughtError,gh=y.clearCaughtError,yh=void 0,bh=void 0,wh=void 0,kh=void 0;yh=!1,bh=!1;var xh={};wh=function(e){var t=Fr(e)||"ReactClass";xh[t]||(o(!1,"Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.%s",Lr(e)),xh[t]=!0)},kh=function(e){switch(zr.phase){case"getChildContext":if(bh)return;o(!1,"setState(...): Cannot call setState() inside getChildContext()"),bh=!0;break;case"render":if(yh)return;o(!1,"Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`."),yh=!0}};var Th=xs(),Ch=Xc(0),Sh=Th,_h=0,Eh=qc,Ph=!1,Rh=null,Nh=null,Oh=qc,Ih=-1,Uh=!1,Ah=null,Dh=!1,Mh=!1,Fh=null,jh=null,Lh=void 0,Wh=void 0,zh=void 0,Bh=void 0,Vh=void 0;function Hh(){if(null!==Rh)for(var e=Rh.return;null!==e;)hh(e),e=e.return;Td.discardPendingWarnings(),-1!==Sc&&o(!1,"Expected an empty stack. Something was not reset properly."),Nh=null,Oh=qc,Ih=-1,Uh=!1,Rh=null,Mh=!1}function qh(){for(;null!==Ah;){zr.setCurrentFiber(Ah),vc();var e=Ah.effectTag;if(e&la&&uh(Ah),e&ca){var t=Ah.alternate;null!==t&&eh(t)}switch(e&(ra|oa|ia)){case ra:oh(Ah),Ah.effectTag&=~ra;break;case aa:oh(Ah),Ah.effectTag&=~ra,lh(Ah.alternate,Ah);break;case oa:lh(Ah.alternate,Ah);break;case ia:ih(Ah)}Ah=Ah.nextEffect}zr.resetCurrentFiber()}function $h(){for(;null!==Ah;){if(Ah.effectTag&da)vc(),Gp(Ah.alternate,Ah);Ah=Ah.nextEffect}}function Yh(e,t,n){for(Td.flushPendingUnsafeLifecycleWarnings(),Vs&&Td.flushPendingDeprecationWarnings(),Hs&&Td.flushLegacyContextWarning();null!==Ah;){var r=Ah.effectTag;if(r&(oa|ua))vc(),Zp(0,Ah.alternate,Ah);r&ca&&(vc(),Jp(Ah));var o=Ah.nextEffect;Ah.nextEffect=null,Ah=o}}function Qh(e){return null!==Fh&&Fh.has(e)}function Kh(e){Ph=!0,Dh=!0,function(){if(Fs){if(!$s)return;Xs=!0,Gs=!1,nc.clear(),oc("(Committing Changes)")}}();var n=e.stateNode;n.current===e&&t(!1,"Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue.");var r=n.pendingCommitExpirationTime;r===qc&&t(!1,"Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue."),n.pendingCommitExpirationTime=qc;var a=lm();wr.current=null;var i=void 0;for(e.effectTag>na?null!==e.lastEffect?(e.lastEffect.nextEffect=e,i=e.firstEffect):i=e:i=e.firstEffect,n.containerInfo,ps=Ya(),hs=ui(),$a(!1),Ah=i,function(){if(Fs){if(!$s)return;ec=0,oc("(Committing Snapshot Effects)")}}();null!==Ah;){var l=!1,u=void 0;mh(null,$h,null),vh()&&(l=!0,u=gh()),l&&(null===Ah&&t(!1,"Should have next effect. This error is likely caused by a bug in React. Please file an issue."),tm(Ah,u),null!==Ah&&(Ah=Ah.nextEffect))}for(!function(){if(Fs){if(!$s)return;var e=ec;ec=0,ac("(Committing Snapshot Effects: "+e+" Total)","(Committing Snapshot Effects)",null)}}(),qs&&qs&&(Cf=xs()),Ah=i,function(){if(Fs){if(!$s)return;ec=0,oc("(Committing Host Effects)")}}();null!==Ah;){var s=!1,c=void 0;mh(null,qh,null),vh()&&(s=!0,c=gh()),s&&(null===Ah&&t(!1,"Should have next effect. This error is likely caused by a bug in React. Please file an issue."),tm(Ah,c),null!==Ah&&(Ah=Ah.nextEffect))}for(!function(){if(Fs){if(!$s)return;var e=ec;ec=0,ac("(Committing Host Effects: "+e+" Total)","(Committing Host Effects)",null)}}(),n.containerInfo,si(hs),hs=null,$a(ps),ps=null,n.current=e,Ah=i,function(){if(Fs){if(!$s)return;ec=0,oc("(Calling Lifecycle Methods)")}}();null!==Ah;){var d=!1,f=void 0;mh(null,Yh,null,n,a,r),vh()&&(d=!0,f=gh()),d&&(null===Ah&&t(!1,"Should have next effect. This error is likely caused by a bug in React. Please file an issue."),tm(Ah,f),null!==Ah&&(Ah=Ah.nextEffect))}qs&&(qs&&0!==Sf.length&&o(!1,"Expected an empty stack. Something was not reset properly."),qs&&(Ef=0)),Dh=!1,Ph=!1,function(){if(Fs){if(!$s)return;var e=ec;ec=0,ac("(Calling Lifecycle Methods: "+e+" Total)","(Calling Lifecycle Methods)",null)}}(),function(){if(Fs){if(!$s)return;var e=null;Gs?e="Lifecycle hook scheduled a cascading update":Js>0&&(e="Caused by a cascading update in earlier commit"),Gs=!1,Js++,Xs=!1,nc.clear(),ac("(Committing Changes)","(Committing Changes)",e)}}(),wd(e.stateNode),Dd.debugTool&&Dd.debugTool.onCommitWork(e),function(e,t,n){if(Ls){if(n===qc)return e.earliestPendingTime=qc,e.latestPendingTime=qc,e.earliestSuspendedTime=qc,e.latestSuspendedTime=qc,void(e.latestPingedTime=qc);var r=e.latestPendingTime;r!==qc&&(r<n?e.earliestPendingTime=e.latestPendingTime=qc:e.earliestPendingTime<n&&(e.earliestPendingTime=e.latestPendingTime));var o=e.earliestSuspendedTime;if(o===qc)return void Md(e,n);if(n>e.latestSuspendedTime)return e.earliestSuspendedTime=qc,e.latestSuspendedTime=qc,e.latestPingedTime=qc,void Md(e,n);if(n<o)Md(e,n)}}(n,0,n.current.expirationTime);var p=Fd(n);return p===qc&&(Fh=null),p}function Xh(e,t){if(t===Yc||e.expirationTime!==Yc){var n=qc;switch(e.tag){case J:case Z:var r=e.updateQueue;null!==r&&(n=r.expirationTime)}if(qs&&e.mode&nd){for(var o=e.selfBaseTime,a=e.child;null!==a;)o+=a.treeBaseTime,a.expirationTime!==qc&&(n===qc||n>a.expirationTime)&&(n=a.expirationTime),a=a.sibling;e.treeBaseTime=o}else for(var i=e.child;null!==i;)i.expirationTime!==qc&&(n===qc||n>i.expirationTime)&&(n=i.expirationTime),i=i.sibling;e.expirationTime=n}}function Gh(e){for(;;){var t=e.alternate;zr.setCurrentFiber(e);var n=e.return,r=e.sibling;if((e.effectTag&pa)===ta){var o=Vp(t,e);if(yc(e),Xh(e,Oh),zr.resetCurrentFiber(),null!==o)return yc(e),Dd.debugTool&&Dd.debugTool.onCompleteWork(e),o;if(null!==n&&(n.effectTag&pa)===ta)null===n.firstEffect&&(n.firstEffect=e.firstEffect),null!==e.lastEffect&&(null!==n.lastEffect&&(n.lastEffect.nextEffect=e.firstEffect),n.lastEffect=e.lastEffect),e.effectTag>na&&(null!==n.lastEffect?n.lastEffect.nextEffect=e:n.firstEffect=e,n.lastEffect=e);if(Dd.debugTool&&Dd.debugTool.onCompleteWork(e),null!==r)return r;if(null!==n){e=n;continue}return Mh=!0,null}var a=ph(e);if(e.effectTag&sa?bc(e):yc(e),zr.resetCurrentFiber(),null!==a)return yc(e),Dd.debugTool&&Dd.debugTool.onCompleteWork(e),a.effectTag&=fa,a;if(null!==n&&(n.firstEffect=n.lastEffect=null,n.effectTag|=pa),Dd.debugTool&&Dd.debugTool.onCompleteWork(e),null!==r)return r;if(null===n)return null;e=n}return null}function Zh(e){var t=e.alternate;!function(e){if(Fs){if(!$s||dc(e))return;if(Ys=e,!uc(e,null))return;e._debugIsCurrentlyTiming=!0}}(e),zr.setCurrentFiber(e),Bs&&(Lh=hd(Lh,e));var n=void 0;return qs?(e.mode&nd&&qs&&(-1!==Of&&o(!1,"Cannot start base timer that is already running. This error is likely caused by a bug in React. Please file an issue."),Of=xs()),n=Mp(t,e,Oh),e.mode&nd&&(!function(e){qs&&-1!==Of&&(e.selfBaseTime=xs()-Of)}(e),If())):n=Mp(t,e,Oh),zr.resetCurrentFiber(),zh&&Vh(),Dd.debugTool&&Dd.debugTool.onBeginWork(e),null===n&&(n=Gh(e)),wr.current=null,n}function Jh(e){if(e){for(;null!==Rh&&!Lm();)Rh=Zh(Rh);qs&&Pf()}else for(;null!==Rh;)Rh=Zh(Rh)}function em(e,n,r){Ph&&t(!1,"renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue."),Ph=!0,n===Oh&&e===Nh&&null!==Rh||(Hh(),Oh=n,Ih=-1,Rh=sd((Nh=e).current,null,Oh),e.pendingCommitExpirationTime=qc);var o=!1;for(Uh=!r||Oh<=Ch,function(e){if(Fs){if(Ys=e,!$s)return;Js=0,oc("(React Tree Reconciliation)"),mc()}}(Rh);;){try{Jh(r)}catch(n){if(qs&&If(),null===Rh)o=!0,Wm(n);else{qd(),Bs&&Wh(Rh,n,r),null===Rh&&t(!1,"Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it.");var a=Rh,i=a.return;if(null===i){o=!0,Wm(n);break}fh(e,i,a,n,0,Oh,Sh),Rh=Gh(a)}}break}var l=!1;return Ph=!1,o?(xc(jh,l),jh=null,Sc=-1,Tc.length=0,Cc.length=0,null):null===Rh?Mh?(xc(jh,l=!0),jh=null,e.pendingCommitExpirationTime=n,e.current.alternate):(xc(jh,l),jh=null,Uh&&t(!1,"Expired work should have completed. This error is likely caused by a bug in React. Please file an issue."),function(e,t){if(Ls){var n=e.earliestPendingTime,r=e.latestPendingTime;n===t?e.earliestPendingTime=r===t?e.latestPendingTime=qc:r:r===t&&(e.latestPendingTime=n);var o=e.latestSuspendedTime;o===t&&(e.latestPingedTime=qc);var a=e.earliestSuspendedTime;a===qc?e.earliestSuspendedTime=e.latestSuspendedTime=t:a>t?e.earliestSuspendedTime=t:o<t&&(e.latestSuspendedTime=t)}}(e,n),Ih>=0&&setTimeout(function(){am(e,n)},Ih),function(e){null===mm&&t(!1,"Should be working on a root. This error is likely caused by a bug in React. Please file an issue."),mm.remainingExpirationTime=e}(Fd(e)),null):(xc(jh,l),jh=null,null)}function tm(e,n){return function(e,n,r){Ph&&!Dh&&t(!1,"dispatch: Cannot dispatch during the render phase.");for(var o=e.return;null!==o;){switch(o.tag){case Z:var a=o.type,i=o.stateNode;if("function"==typeof a.getDerivedStateFromCatch||"function"==typeof i.componentDidCatch&&!Qh(i))return Xd(o,ch(o,af(n,e),r),r),void im(o,r);break;case J:return Xd(o,sh(o,af(n,e),r),r),void im(o,r)}o=o.return}if(e.tag===J){var l=e;Xd(l,sh(l,af(n,l),r),r),im(l,r)}}(e,n,$c)}function nm(e){return Zc(e,5e3,250)}function rm(){var e=nm(lm());return e<=_h&&(e=_h+1),_h=e}function om(e,t){var n=void 0;return n=Eh!==qc?Eh:Ph?Dh?$c:Oh:t.mode&ed?Cm?function(e){return Zc(e,500,100)}(e):nm(e):$c,Cm&&(gm===qc||n>gm)&&(gm=n),n}function am(e,t){!function(e,t){if(Ls){var n=e.latestSuspendedTime;if(n!==qc&&n<=t){var r=e.latestPingedTime;(r===qc||r<t)&&(e.latestPingedTime=t)}}}(e,t);var n=Fd(e);n!==qc&&function(e,t){(e.remainingExpirationTime===qc||e.remainingExpirationTime<t)&&Nm(e,t)}(e,n)}function im(e,n){if(Fs&&(Xs&&(Gs=!0),null!==Qs&&"componentWillMount"!==Qs&&"componentWillReceiveProps"!==Qs&&(Zs=!0)),e.tag===Z){var r=e.stateNode;kh(r)}for(var o=e;null!==o;){if((o.expirationTime===qc||o.expirationTime>n)&&(o.expirationTime=n),null!==o.alternate&&(o.alternate.expirationTime===qc||o.alternate.expirationTime>n)&&(o.alternate.expirationTime=n),null===o.return){if(o.tag!==J)return void(e.tag===Z&&wh(e));var a=o.stateNode;!Ph&&Oh!==qc&&n<Oh&&(jh=e,Hh()),Md(a,n);var i=Fd(a);Ph&&!Dh&&Nh===a||Nm(a,i),Em>_m&&t(!1,"Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.")}o=o.return}}function lm(){return Sh=xs()-Th,Ch=Xc(Sh)}function um(e){var t=Eh,n=lm();Eh=nm(n);try{return e()}finally{Eh=t}}function sm(e,t,n,r,o){var a=Eh;Eh=$c;try{return e(t,n,r,o)}finally{Eh=a}}Bs&&(Lh=null,zh=!1,Bh=null,Wh=function(e,t,n){if(null===t||"object"!=typeof t||"function"!=typeof t.then)if(null!==Lh){switch(hd(e,Lh),e.tag){case J:wf(e),Lc(e);break;case te:Tf(e);break;case Z:jc(e);break;case ee:wf(e);break;case ie:ff(e)}zh=!0,Bh=t,mh(null,Jh,null,n),zh=!1,Bh=null,vh()?(gh(),qs&&(e.mode&nd&&Rf(e),If())):Rh=e}else o(!1,"Could not replay rendering after an error. This is likely a bug in React. Please file an issue.")},Vh=function(){throw Bh});var cm=null,dm=null,fm=qc,pm=void 0,hm=!1,mm=null,vm=qc,gm=qc,ym=!1,bm=!1,wm=null,km=null,xm=!1,Tm=!1,Cm=!1,Sm=null,_m=1e3,Em=0,Pm=1;function Rm(e){if(fm!==qc){if(e>fm)return;null!==pm&&Ss(pm)}else Fs&&$s&&!tc&&(tc=!0,oc("(Waiting for async callback...)"));var t=xs()-Th,n=Gc(e);fm=e,pm=Cs(Im,{timeout:n-t})}function Nm(e,t){!function(e,t){if(null===e.nextScheduledRoot)e.remainingExpirationTime=t,null===dm?(cm=dm=e,e.nextScheduledRoot=e):(dm.nextScheduledRoot=e,(dm=e).nextScheduledRoot=cm);else{var n=e.remainingExpirationTime;(n===qc||t<n)&&(e.remainingExpirationTime=t)}}(e,t),hm||(xm?Tm&&(mm=e,vm=$c,Fm(e,$c,!1)):t===$c?Um():Rm(t))}function Om(){var e=qc,n=null;if(null!==dm)for(var r=dm,o=cm;null!==o;){var a=o.remainingExpirationTime;if(a===qc){if((null===r||null===dm)&&t(!1,"Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue."),o===o.nextScheduledRoot){o.nextScheduledRoot=null,cm=dm=null;break}if(o===cm){var i=o.nextScheduledRoot;cm=i,dm.nextScheduledRoot=i,o.nextScheduledRoot=null}else{if(o===dm){(dm=r).nextScheduledRoot=cm,o.nextScheduledRoot=null;break}r.nextScheduledRoot=o.nextScheduledRoot,o.nextScheduledRoot=null}o=r.nextScheduledRoot}else{if((e===qc||a<e)&&(e=a,n=o),o===dm)break;r=o,o=o.nextScheduledRoot}}null!==mm&&mm===n&&e===$c?Em++:Em=0,mm=n,vm=e}function Im(e){Am(qc,!0,e)}function Um(){Am($c,!1,null)}function Am(e,t,n){(km=n,Om(),qs&&Nf(),Fs&&null!==km)&&function(e,t){Fs&&$s&&(tc=!1,ac("(Waiting for async callback... will force flush in "+t+" ms)","(Waiting for async callback...)",e?"React was blocked by main thread":null))}(vm<lm(),Gc(vm));if(t)for(;null!==mm&&vm!==qc&&(e===qc||e>=vm)&&(!ym||lm()>=vm);)lm(),Fm(mm,vm,!ym),Om();else for(;null!==mm&&vm!==qc&&(e===qc||e>=vm);)Fm(mm,vm,!1),Om();null!==km&&(fm=qc,pm=null),vm!==qc&&Rm(vm),km=null,ym=!1,Mm()}function Dm(e,n){hm&&t(!1,"work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method."),mm=e,vm=n,Fm(e,n,!1),Um(),Mm()}function Mm(){if(Em=0,null!==Sm){var e=Sm;Sm=null;for(var t=0;t<e.length;t++){var n=e[t];try{n._onComplete()}catch(r){bm||(bm=!0,wm=r)}}}if(bm){var r=wm;throw wm=null,bm=!1,r}}function Fm(e,n,r){if(hm&&t(!1,"performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue."),hm=!0,r){var o=e.finishedWork;null!==o?jm(e,o,n):null!==(o=em(e,n,!0))&&(Lm()?(e.finishedWork=o,qs&&Pf()):jm(e,o,n))}else{var a=e.finishedWork;null!==a?jm(e,a,n):null!==(a=em(e,n,!1))&&jm(e,a,n)}hm=!1}function jm(e,t,n){var r=e.firstBatch;if(null!==r&&r._expirationTime<=n&&(null===Sm?Sm=[r]:Sm.push(r),r._defer))return e.finishedWork=t,void(e.remainingExpirationTime=qc);e.finishedWork=null,e.remainingExpirationTime=Kh(t)}function Lm(){return null!==km&&(!(km.timeRemaining()>Pm)&&(ym=!0,!0))}function Wm(e){null===mm&&t(!1,"Should be working on a root. This error is likely caused by a bug in React. Please file an issue."),mm.remainingExpirationTime=qc,bm||(bm=!0,wm=e)}function zm(e,t){var n=xm;xm=!0;try{return e(t)}finally{(xm=n)||hm||Um()}}function Bm(e,t){if(xm&&!Tm){Tm=!0;try{return e(t)}finally{Tm=!1}}return e(t)}function Vm(e,n){hm&&t(!1,"flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.");var r=xm;xm=!0;try{return sm(e,n)}finally{xm=r,Um()}}function Hm(e,t,n){if(Cm)return e(t,n);xm||hm||gm===qc||(Am(gm,!1,null),gm=qc);var r=Cm,o=xm;Cm=!0,xm=!0;try{return e(t,n)}finally{Cm=r,(xm=o)||hm||Um()}}function qm(e){var t=xm;xm=!0;try{sm(e)}finally{(xm=t)||hm||Am($c,!1,null)}}var $m=void 0;function Ym(e){if(!e)return f;var n=ea(e),r=function(e){ba(e)&&e.tag===Z||t(!1,"Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.");for(var n=e;n.tag!==J;){if(Fc(n))return n.stateNode.__reactInternalMemoizedMergedChildContext;var r=n.return;r||t(!1,"Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue."),n=r}return n.stateNode.context}(n);return Fc(n)?zc(n,r):r}function Qm(e,t,n,r,a){var i=t.current;Dd.debugTool&&(null===i.alternate?Dd.debugTool.onMountContainer(t):null===e?Dd.debugTool.onUnmountContainer(t):Dd.debugTool.onUpdateContainer(t));var l=Ym(n);return null===t.context?t.context=l:t.pendingContext=l,function(e,t,n,r){"render"!==zr.phase||null===zr.current||$m||($m=!0,o(!1,"Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.\n\nCheck the render method of %s.",Fr(zr.current)||"Unknown"));var a=Qd(n);return a.payload={element:t},null!==(r=void 0===r?null:r)&&("function"!=typeof r&&o(!1,"render(...): Expected the last optional `callback` argument to be a function. Instead received: %s.",r),a.callback=r),Xd(e,a,n),im(e,n),n}(i,e,r,a)}function Km(e){var n=ea(e);void 0===n&&("function"==typeof e.render?t(!1,"Unable to find node on an unmounted component."):t(!1,"Argument appears to not be a ReactComponent. Keys: %s",Object.keys(e)));var r=xa(n);return null===r?null:r.stateNode}function Xm(e,t,n){return md(e,t,n)}function Gm(e,t,n,r){var o=t.current;return Qm(e,t,n,om(lm(),o),r)}function Zm(e){var t=e.current;if(!t.child)return null;switch(t.child.tag){case te:return vs(t.child.stateNode);default:return t.child.stateNode}}function Jm(e){var t=function(e){var t=ka(e);if(!t)return null;for(var n=t;;){if(n.tag===te||n.tag===ne)return n;if(n.child&&n.tag!==ee)n.child.return=n,n=n.child;else{if(n===t)return null;for(;!n.sibling;){if(!n.return||n.return===t)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}}return null}(e);return null===t?null:t.stateNode}function ev(e){var t=e.findFiberByHostInstance;return function(e){if("undefined"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var t=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(t.isDisabled)return!0;if(!t.supportsFiber)return o(!1,"The installed version of React DevTools is too old and will not work with the current version of React. Please update React DevTools. https://fb.me/react-devtools"),!0;try{var n=t.inject(e);vd=bd(function(e){return t.onCommitFiberRoot(n,e)}),gd=bd(function(e){return t.onCommitFiberUnmount(n,e)})}catch(e){o(!1,"React DevTools encountered an error: %s.",e)}return!0}(i({},e,{findHostInstanceByFiber:function(e){var t=xa(e);return null===t?null:t.stateNode},findFiberByHostInstance:function(e){return t?t(e):null}}))}$m=!1;var tv=Object.freeze({updateContainerAtExpirationTime:Qm,createContainer:Xm,updateContainer:Gm,flushRoot:Dm,requestWork:Nm,computeUniqueAsyncExpiration:rm,batchedUpdates:zm,unbatchedUpdates:Bm,deferredUpdates:um,syncUpdates:sm,interactiveUpdates:Hm,flushInteractiveUpdates:function(){hm||gm===qc||(Am(gm,!1,null),gm=qc)},flushControlled:qm,flushSync:Vm,getPublicRootInstance:Zm,findHostInstance:Km,findHostInstanceWithNoPortals:Jm,injectIntoDevTools:ev});var nv,rv=void 0,ov=!1;function av(e){var t=rm();this._expirationTime=t,this._root=e,this._next=null,this._callbacks=null,this._didComplete=!1,this._hasChildren=!1,this._children=null,this._defer=!0}function iv(){this._callbacks=null,this._didCommit=!1,this._onCommit=this._onCommit.bind(this)}function lv(e,t,n){var r=Xm(e,t,n);this._internalRoot=r}function uv(e){return!(!e||e.nodeType!==ur&&e.nodeType!==dr&&e.nodeType!==fr&&(e.nodeType!==cr||" react-mount-point-unstable "!==e.nodeValue))}function sv(e){return e?e.nodeType===dr?e.documentElement:e.firstChild:null}"function"==typeof Map&&null!=Map.prototype&&"function"==typeof Map.prototype.forEach&&"function"==typeof Set&&null!=Set.prototype&&"function"==typeof Set.prototype.clear&&"function"==typeof Set.prototype.forEach||o(!1,"React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"),rv=function(e){if(e._reactRootContainer&&e.nodeType!==cr){var t=Jm(e._reactRootContainer._internalRoot.current);t&&t.parentNode!==e&&o(!1,"render(...): It looks like the React-rendered content of this container was removed without using React. This is not supported and will cause errors. Instead, call ReactDOM.unmountComponentAtNode to empty a container.")}var n=!!e._reactRootContainer,r=sv(e);!(!r||!me(r))&&!n&&o(!1,"render(...): Replacing React-rendered children with a new root component. If you intended to update the children of this node, you should instead have the existing children update their state and render the new components instead of calling ReactDOM.render."),e.nodeType===ur&&e.tagName&&"BODY"===e.tagName.toUpperCase()&&o(!1,"render(): Rendering components directly into document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. Try rendering into a container element created for your app.")},nv=function(e,t){null!==e&&"function"!=typeof e&&o(!1,"%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.",t,e)},Kn.injectFiberControlledHostComponent(Du),av.prototype.render=function(e){this._defer||t(!1,"batch.render: Cannot render a batch that already committed."),this._hasChildren=!0,this._children=e;var n=this._root._internalRoot,r=this._expirationTime,o=new iv;return Qm(e,n,null,r,o._onCommit),o},av.prototype.then=function(e){if(this._didComplete)e();else{var t=this._callbacks;null===t&&(t=this._callbacks=[]),t.push(e)}},av.prototype.commit=function(){var e=this._root._internalRoot,n=e.firstBatch;if(this._defer&&null!==n||t(!1,"batch.commit: Cannot commit a batch multiple times."),!this._hasChildren)return this._next=null,void(this._defer=!1);var r=this._expirationTime;if(n!==this){this._hasChildren&&(r=this._expirationTime=n._expirationTime,this.render(this._children));for(var o=null,a=n;a!==this;)o=a,a=a._next;null===o&&t(!1,"batch.commit: Cannot commit a batch multiple times."),o._next=a._next,this._next=n,n=e.firstBatch=this}this._defer=!1,Dm(e,r);var i=this._next;this._next=null,null!==(n=e.firstBatch=i)&&n._hasChildren&&n.render(n._children)},av.prototype._onComplete=function(){if(!this._didComplete){this._didComplete=!0;var e=this._callbacks;if(null!==e)for(var t=0;t<e.length;t++){(0,e[t])()}}},iv.prototype.then=function(e){if(this._didCommit)e();else{var t=this._callbacks;null===t&&(t=this._callbacks=[]),t.push(e)}},iv.prototype._onCommit=function(){if(!this._didCommit){this._didCommit=!0;var e=this._callbacks;if(null!==e)for(var n=0;n<e.length;n++){var r=e[n];"function"!=typeof r&&t(!1,"Invalid argument passed as callback. Expected a function. Instead received: %s",r),r()}}},lv.prototype.render=function(e,t){var n=this._internalRoot,r=new iv;return nv(t=void 0===t?null:t,"render"),null!==t&&r.then(t),Gm(e,n,null,r._onCommit),r},lv.prototype.unmount=function(e){var t=this._internalRoot,n=new iv;return nv(e=void 0===e?null:e,"render"),null!==e&&n.then(e),Gm(null,t,null,n._onCommit),n},lv.prototype.legacy_renderSubtreeIntoContainer=function(e,t,n){var r=this._internalRoot,o=new iv;return nv(n=void 0===n?null:n,"render"),null!==n&&o.then(n),Gm(t,r,e,o._onCommit),o},lv.prototype.createBatch=function(){var e=new av(this),t=e._expirationTime,n=this._internalRoot,r=n.firstBatch;if(null===r)n.firstBatch=e,e._next=null;else{for(var o=null,a=r;null!==a&&a._expirationTime<=t;)o=a,a=a._next;e._next=a,null!==o&&(o._next=e)}return e},ar(tv);var cv=!1;function dv(e,t){var n=t||function(e){var t=sv(e);return!(!t||t.nodeType!==ur||!t.hasAttribute(Xr))}(e);if(!n)for(var r=!1,a=void 0;a=e.lastChild;)!r&&a.nodeType===ur&&a.hasAttribute(Xr)&&(r=!0,o(!1,"render(): Target node has markup rendered by React, but there are unrelated nodes as well. This is most commonly caused by white-space inserted around server-rendered markup.")),e.removeChild(a);!n||t||cv||(cv=!0,xd(!1,"render(): Calling ReactDOM.render() to hydrate server-rendered markup will stop working in React v17. Replace the ReactDOM.render() call with ReactDOM.hydrate() if you want React to attach to the server HTML."));return new lv(e,!1,n)}function fv(e,n,r,o,a){uv(r)||t(!1,"Target container is not a DOM element."),rv(r);var i=r._reactRootContainer;if(i){if("function"==typeof a){var l=a;a=function(){var e=Zm(i._internalRoot);l.call(e)}}null!=e?i.legacy_renderSubtreeIntoContainer(e,n,a):i.render(n,a)}else{if(i=r._reactRootContainer=dv(r,o),"function"==typeof a){var u=a;a=function(){var e=Zm(i._internalRoot);u.call(e)}}Bm(function(){null!=e?i.legacy_renderSubtreeIntoContainer(e,n,a):i.render(n,a)})}return Zm(i._internalRoot)}function pv(e,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return uv(n)||t(!1,"Target container is not a DOM element."),function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:Sr,key:null==r?null:""+r,children:e,containerInfo:t,implementation:n}}(e,n,null,r)}var hv={createPortal:pv,findDOMNode:function(e){var t=wr.current;null!==t&&null!==t.stateNode&&(t.stateNode._warnedAboutRefsInRender||o(!1,"%s is accessing findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.",Fr(t)||"A component"),t.stateNode._warnedAboutRefsInRender=!0);return null==e?null:e.nodeType===ur?e:Km(e)},hydrate:function(e,t,n){return fv(null,e,t,!0,n)},render:function(e,t,n){return fv(null,e,t,!1,n)},unstable_renderSubtreeIntoContainer:function(e,n,r,o){return null!=e&&function(e){return void 0!==e._reactInternalFiber}(e)||t(!1,"parentComponent must be a valid React Component"),fv(e,n,r,!1,o)},unmountComponentAtNode:function(e){if(uv(e)||t(!1,"unmountComponentAtNode(...): Target container is not a DOM element."),e._reactRootContainer){var n=sv(e);return n&&!me(n)&&o(!1,"unmountComponentAtNode(): The node you're attempting to unmount was rendered by another copy of React."),Bm(function(){fv(null,null,e,!1,function(){e._reactRootContainer=null})}),!0}var r=sv(e),a=!(!r||!me(r)),i=1===e.nodeType&&uv(e.parentNode)&&!!e.parentNode._reactRootContainer;return a&&o(!1,"unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. %s",i?"You may have accidentally passed in a React root node instead of its container.":"Instead, have the parent component update its state and rerender in order to remove this component."),!1},unstable_createPortal:function(){return ov||(ov=!0,xd(!1,'The ReactDOM.unstable_createPortal() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactDOM.createPortal() instead. It has the exact same API, but without the "unstable_" prefix.')),pv.apply(void 0,arguments)},unstable_batchedUpdates:zm,unstable_deferredUpdates:um,unstable_interactiveUpdates:Hm,flushSync:Vm,unstable_flushControlled:qm,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{EventPluginHub:K,EventPluginRegistry:I,EventPropagators:Ne,ReactControlledComponent:Jn,ReactDOMComponentTree:be,ReactDOMEventListener:Za},unstable_createRoot:function(e,t){return new lv(e,!0,null!=t&&!0===t.hydrate)}};if(!ev({findFiberByHostInstance:he,bundleType:1,version:"16.4.1",rendererPackageName:"react-dom"})&&a.canUseDOM&&window.top===window.self&&(navigator.userAgent.indexOf("Chrome")>-1&&-1===navigator.userAgent.indexOf("Edge")||navigator.userAgent.indexOf("Firefox")>-1)){var mv=window.location.protocol;/^(https?|file):$/.test(mv)&&console.info("%cDownload the React DevTools for a better development experience: https://fb.me/react-devtools"+("file:"===mv?"\nYou might need to use a local HTTP server (instead of file://): https://fb.me/react-devtools-faq":""),"font-weight:bold")}var vv=Object.freeze({default:hv}),gv=vv&&hv||vv,yv=gv.default?gv.default:gv;e.exports=yv})()},function(e,t,n){"use strict";e.exports=n(24)},function(e,t,n){"use strict";var r=l(n(25)),o=l(n(1)),a=l(n(11)),i=l(n(7));function l(e){return e&&e.__esModule?e:{default:e}}InboxSDK.load("2",i.default).then(function(e){e.Compose.registerComposeViewHandler(function(e){e.addButton({title:"Add recipients",iconUrl:chrome.runtime.getURL("assets/add_friends.png"),hasDropdown:!0,onClick:function(e){e.dropdown.el.innerHTML="<div id='gmail_lists_content'> </div>",r.default.render(o.default.createElement(a.default,{event:e}),document.getElementById("gmail_lists_content"))}})})})}]);
src/components/VideoPlayer/HLS/Track.js
matmoi/react-adaptive-streaming
import React from 'react' import PropTypes from 'prop-types' import DropdownPanel from '../../utils/DropdownPanel.js' import Hls from 'hls.js' export default class HLSTrack extends React.Component { componentDidMount() { this.listenToChanges() } componentWillUpdate() { this.listenToChanges() } listenToChanges() { const { mediaPlayer, type } = this.props let switchEvent = null switch (type) { case "audio": switchEvent = Hls.Events.AUDIO_TRACK_SWITCHED break case "subtitle": switchEvent = Hls.Events.SUBTITLE_TRACK_SWITCH break default: switchEvent = Hls.Events.LEVEL_SWITCHED } mediaPlayer.on(switchEvent, () => { this.forceUpdate() }) } render() { const { mediaPlayer, type } = this.props let track = null if (type === "audio") { if (mediaPlayer.audioTrack !== -1) { track = mediaPlayer.audioTracks[mediaPlayer.audioTrack] } } else if (type === "subtitle") { if (mediaPlayer.subtitleTrack !== -1) { track = mediaPlayer.subtitleTracks[mediaPlayer.subtitleTrack] } } else { //video if (mediaPlayer.currentLevel !== -1) { track = mediaPlayer.levels[mediaPlayer.currentLevel] } } return ( <DropdownPanel title={`HLS ${type} track`} data={ track !== null ? {...track} : null} /> ) } } HLSTrack.propTypes = { mediaPlayer: PropTypes.object.isRequired, type: PropTypes.oneOf(['audio', 'video', 'subtitle']) }; HLSTrack.defaultProps = { type: 'audio' }
app/components/Header.js
whisher/requiz
import React, { Component } from 'react'; import styles from '../styles/header.css'; class Header extends Component { constructor(props) { super(props); } render() { return ( <h1 className={styles.header}>Question</h1> ); } } export default Header;
resources/assets/js/components/teacher/responses/CompletedReviewItem.js
jrm2k6/i-heart-reading
import React, { Component } from 'react'; import { StudentSection, BookSection, ResponseSection, ReviewStatusSection } from './ReviewSections'; class CompletedReviewItem extends Component { constructor(props) { super(props); this.state = { isHovered: false }; } render() { const { completedReview } = this.props; const student = completedReview.user; const book = completedReview.book; const response = completedReview.response; const review = completedReview.current_review; const linkContent = `/app/responses/student-response-accepted/${response.id}`; return ( <div className='completed-review-item' onMouseEnter={ () => { this.setState({isHovered: true}); }} onMouseLeave={ () => { this.setState({isHovered: false}); }} > <StudentSection student={student} /> <BookSection book={book} /> <ResponseSection response={response} /> <ReviewStatusSection review={review} showIcon={!this.state.isHovered} linkContent={linkContent} /> </div> ); } } export default CompletedReviewItem;
src/components/smart/AppContainer/AppContainer.js
arfianadam/react-swapi
import React from 'react' import Helmet from 'react-helmet' import styles from './AppContainer.scss' import HeaderContainer from '../HeaderContainer' class AppContainer extends React.Component { constructor(props) { super(props) this.displayName = 'AppContainer' } render() { return ( <div className={ styles.AppContainer }> <Helmet defaultTitle='React SWAPI' titleTemplate='%s - React SWAPI' /> <HeaderContainer/> { this.props.children } </div> ) } } export default AppContainer
packages/material-ui-icons/src/ReorderSharp.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M3 15h18v-2H3v2zm0 4h18v-2H3v2zm0-8h18V9H3v2zm0-6v2h18V5H3z" /></React.Fragment> , 'ReorderSharp');
react-flux-mui/js/material-ui/docs/src/app/components/pages/components/DatePicker/Page.js
pbogdan/react-flux-mui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import datePickerReadmeText from './README'; import DatePickerExampleSimple from './ExampleSimple'; import datePickerExampleSimpleCode from '!raw!./ExampleSimple'; import DatePickerExampleInline from './ExampleInline'; import datePickerExampleInlineCode from '!raw!./ExampleInline'; import DatePickerExampleToggle from './ExampleToggle'; import datePickerExampleToggleCode from '!raw!./ExampleToggle'; import DatePickerExampleControlled from './ExampleControlled'; import datePickerExampleControlledCode from '!raw!./ExampleControlled'; import DatePickerExampleDisableDates from './ExampleDisableDates'; import datePickerExampleDisableDatesCode from '!raw!./ExampleDisableDates'; import DatePickerExampleInternational from './ExampleInternational'; import datePickerExampleInternationalCode from '!raw!./ExampleInternational'; import datePickerCode from '!raw!material-ui/DatePicker/DatePicker'; const DatePickerPage = () => ( <div> <Title render={(previousTitle) => `Date Picker - ${previousTitle}`} /> <MarkdownElement text={datePickerReadmeText} /> <CodeExample title="Simple examples" code={datePickerExampleSimpleCode} > <DatePickerExampleSimple /> </CodeExample> <CodeExample title="Inline examples" code={datePickerExampleInlineCode} > <DatePickerExampleInline /> </CodeExample> <CodeExample title="Ranged example" code={datePickerExampleToggleCode} > <DatePickerExampleToggle /> </CodeExample> <CodeExample title="Controlled example" code={datePickerExampleControlledCode} > <DatePickerExampleControlled /> </CodeExample> <CodeExample title="Disabled dates example" code={datePickerExampleDisableDatesCode} > <DatePickerExampleDisableDates /> </CodeExample> <CodeExample title="Localised example" code={datePickerExampleInternationalCode} > <DatePickerExampleInternational /> </CodeExample> <PropTypeDescription code={datePickerCode} /> </div> ); export default DatePickerPage;
ajax/libs/forerunnerdb/1.3.830/fdb-core.min.js
sreym/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":6,"../lib/Shim.IE8":30}],2:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c,d){var e=this._compareFunc(this._data,a);return d=d||[],0===e&&(this._left&&this._left.lookup(a,b,c,d),d.push(this._data),this._right&&this._right.lookup(a,b,c,d)),-1===e&&this._right&&this._right.lookup(a,b,c,d),1===e&&this._left&&this._left.lookup(a,b,c,d),d},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return d=d||[],void 0===d._visitedCount&&(d._visitedCount=0),d._visitedCount++,d._visitedNodes=d._visitedNodes||[],d._visitedNodes.push(h),g=this.sortAsc(i,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":26,"./Shared":29}],3:[function(a,b,c){"use strict";var d,e;d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),e=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0},b.exports=e},{}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a,b){this.init.apply(this,arguments)};p.prototype.init=function(a,b){this.sharedPathSolver=o,this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),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=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=a("./Condition"),o=new h,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!1,!0),!0;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],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),p.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw 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: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b.call(this),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b.call(this),{}},p.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},p.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},p.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},p.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,d),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length?(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length?(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this,f||[]),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f})):d&&d.call(this,f||[])):d&&d.call(this,f||[]),h.stop(),f||[]},p.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},p.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":a[s]instanceof Object&&!(a[s]instanceof Array)||(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$splicePull":if(void 0!==a[s]){if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePull from a key that is not an array! ("+s+")";if(l=b[s].$index,void 0===l)throw this.logIdentifier()+" Cannot splicePull without a $index integer value!";l<a[s].length&&(this._updateSplicePull(a[s],l),t=!0)}break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c.call(this,!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c.call(this,!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i,failed:j}),this.deferEmit("change",{type:"insert",data:i,failed:j}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},p.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new p,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=c.indexMatch[0].lookup||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&-1===D.indexOf(o)&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),b.$groupBy&&(x.data("flag.group",!0),x.time("group"),e=this.group(b.$groupBy,e),x.time("group")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},p.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},p.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):-1===f.value&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype.group=function(a,b){var c,d,e,f=o.parse(a,!0),g=new h,i={};if(f.length)for(d=0;d<f.length;d++)for(g.path(f[d].path),e=0;e<b.length;e++)c=g.get(b[e]),i[c]=i[c]||[],i[c].push(b[e]);return i},p.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},p.prototype._analyseQuery=function(a,b,c){ var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=this._primaryIndex.lookup(a,b,c),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=m.lookup(a,b,c),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},p.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},p.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new p("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else c=new i(a,b,this);else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},p.prototype.when=function(a){var b=this.objectId();return this._when=this._when||{},this._when[b]=this._when[b]||new n(this,b,a),this._when[b]},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Condition":5,"./Index2d":9,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":25,"./Path":26,"./ReactorIO":27,"./Shared":29}],5:[function(a,b,c){"use strict";var d,e;d=a("./Shared"),e=function(){this.init.apply(this,arguments)},e.prototype.init=function(a,b,c){this._dataSource=a,this._id=b,this._query=[c],this._started=!1,this._state=[!1],this._satisfied=!1,this.earlyExit(!0)},d.addModule("Condition",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"id"),d.synthesize(e.prototype,"then"),d.synthesize(e.prototype,"else"),d.synthesize(e.prototype,"earlyExit"),d.synthesize(e.prototype,"debug"),e.prototype.and=function(a){return this._query.push(a),this._state.push(!1),this},e.prototype.start=function(a){if(!this._started){var b=this;0!==arguments.length&&(this._satisfied=a),this._updateStates(),b._onChange=function(){b._updateStates()},this._dataSource.on("change",b._onChange),this._started=!0}return this},e.prototype._updateStates=function(){var a,b=!0;for(a=0;a<this._query.length&&(this._state[a]=this._dataSource.count(this._query[a])>0,this._debug&&console.log(this.logIdentifier()+" Evaluating",this._query[a],"=",this._query[a]),this._state[a]||(b=!1,!this._earlyExit));a++);this._satisfied!==b&&(b?this._then&&this._then():this._else&&this._else(),this._satisfied=b)},e.prototype.stop=function(){return this._started&&(this._dataSource.off("change",this._onChange),delete this._onChange,this._started=!1),this},e.prototype.drop=function(){return this.stop(),delete this._dataSource.when[this._id],this},d.finishModule("Condition"),b.exports=e},{"./Shared":29}],6:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":7,"./Metrics.js":13,"./Overload":25,"./Shared":29}],7:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Checksum.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.Checksum=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":13,"./Overload":25,"./Shared":29}],8:[function(a,b,c){"use strict";var d,e,f,g,h=Math.PI/180,i=180/Math.PI,j=6371;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var k=function(){};k.prototype.radians=function(a){return a*h},k.prototype.degrees=function(a){return a*i},k.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},k.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},k.prototype.calculateLatLngByDistanceBearing=function(a,b,c){var d=a[1],e=a[0],f=Math.asin(Math.sin(this.radians(e))*Math.cos(b/j)+Math.cos(this.radians(e))*Math.sin(b/j)*Math.cos(this.radians(c))),g=this.radians(d)+Math.atan2(Math.sin(this.radians(c))*Math.sin(b/j)*Math.cos(this.radians(e)),Math.cos(b/j)-Math.sin(this.radians(e))*Math.sin(f)),h=(g+3*Math.PI)%(2*Math.PI)-Math.PI;return{lat:this.degrees(f),lng:this.degrees(h)}},k.prototype.calculateExtentByRadius=function(a,b){var c,d,e,f,g=[],h=[];return e=this.calculateLatLngByDistanceBearing(a,b,0),d=this.calculateLatLngByDistanceBearing(a,b,90),f=this.calculateLatLngByDistanceBearing(a,b,180),c=this.calculateLatLngByDistanceBearing(a,b,270),g[0]=e.lat,g[1]=f.lat,h[0]=c.lng,h[1]=d.lng,{lat:g,lng:h}},k.prototype.calculateHashArrayByRadius=function(a,b,c){var d,e,f,g=this.calculateExtentByRadius(a,b),h=[g.lat[0],g.lng[0]],i=[g.lat[0],g.lng[1]],j=[g.lat[1],g.lng[0]],k=this.encode(h[0],h[1],c),l=this.encode(i[0],i[1],c),m=this.encode(j[0],j[1],c),n=0,o=0,p=[];for(d=k,p.push(d);d!==l;)d=this.calculateAdjacent(d,"right"),n++,p.push(d);for(d=k;d!==m;)d=this.calculateAdjacent(d,"bottom"),o++;for(e=0;n>=e;e++)for(d=p[e],f=0;o>f;f++)d=this.calculateAdjacent(d,"bottom"),p.push(d);return p},k.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},k.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{lat:l,lng:m}},k.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},"undefined"!=typeof b&&(b.exports=k)},{}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b,c){var d,e,f,g,i=this._btree.keys();for(g=0;g<i.length;g++)if(d=i[g].path,e=h.get(a,d),"object"==typeof e)return e.$near&&(f=[],f=f.concat(this.near(d,e.$near,b,c))),e.$geoWithin&&(f=[],f=f.concat(this.geoWithin(d,e.$geoWithin,b,c))),f;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c,d){var e,f,g,k,l,m,n,o,p,q,r,s,t=this,u=[],v=this._collection.primaryKey();if("km"===b.$distanceUnits){for(o=b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}}else if("miles"===b.$distanceUnits)for(o=1.60934*b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}for(0===n&&(n=1),d&&d.time("index2d.calculateHashArea"),e=i.calculateHashArrayByRadius(b.$point,o,n),d&&d.time("index2d.calculateHashArea"),d&&(d.data("index2d.near.precision",n),d.data("index2d.near.hashArea",e),d.data("index2d.near.maxDistanceKm",o),d.data("index2d.near.centerPointCoords",[b.$point[0],b.$point[1]])),m=[],f=0,k={},g=[],d&&d.time("index2d.near.getDocsInsideHashArea"),s=0;s<e.length;s++)l=this._btree.startsWith(a,e[s]),k[e[s]]=l,f+=l._visitedCount,g=g.concat(l._visitedNodes),m=m.concat(l);if(d&&(d.time("index2d.near.getDocsInsideHashArea"),d.data("index2d.near.startsWith",k),d.data("index2d.near.visitedTreeNodes",g)),d&&d.time("index2d.near.lookupDocsById"),m=this._collection._primaryIndex.lookup(m),d&&d.time("index2d.near.lookupDocsById"),b.$distanceField&&(m=this.decouple(m)),m.length){for(p={},d&&d.time("index2d.near.calculateDistanceFromCenter"),s=0;s<m.length;s++)r=h.get(m[s],a),q=p[m[s][v]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],r[0],r[1]),o>=q&&(b.$distanceField&&h.set(m[s],b.$distanceField,"km"===b.$distanceUnits?q:Math.round(.621371*q)),b.$geoHashField&&h.set(m[s],b.$geoHashField,i.encode(r[0],r[1],n)),u.push(m[s]));d&&d.time("index2d.near.calculateDistanceFromCenter"),d&&d.time("index2d.near.sortResultsByDistance"),u.sort(function(a,b){return t.sortAsc(p[a[v]],p[b[v]])}),d&&d.time("index2d.near.sortResultsByDistance")}return u},k.prototype.geoWithin=function(a,b,c){return console.log("geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array."),[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index["2d"]=k,d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":2,"./GeoHash":8,"./Path":26,"./Shared":29}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b,c){return this._btree.lookup(a,b,c)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.btree=g,d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":2,"./Path":26,"./Shared":29}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){ var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":26,"./Shared":29}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(void 0!==a[e]&&null!==a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":29}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":24,"./Shared":29}],14:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],15:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainEnabled:function(a){return void 0!==a?(this._chainDisabled=!a,this):!this._chainDisabled},chainWillSend:function(){return Boolean(this._chain&&!this._chainDisabled)},chainSend:function(a,b,c){if(this._chain&&!this._chainDisabled){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],16:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.convert(a)},store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":25,"./Serialiser":28}],17:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],18:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=!1,e=function(){d||(c.off(a,e),b.apply(c,arguments),d=!0)};return this.on(a,e)},"string, *, function":function(a,b,c){var d=this,e=!1,f=function(){e||(d.off(a,b,f),c.apply(d,arguments),e=!0)};return this.on(a,b,f)}}),off:new d({string:function(a){var b=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){b.off(a)})):this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d,e=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){e.off(a,b)})):"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){var d=this;if(this._emitting)this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){d.off(a,b,c)});else if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var e=this._listeners[a][b],f=e.indexOf(c);f>-1&&e.splice(f,1)}},"string, *":function(a,b){var c=this;this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){c.off(a,b)})):this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},this._emitting=!0,a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this._emitting=!1,this._processRemovalQueue(),this},_processRemovalQueue:function(){var a;if(this._eventRemovalQueue&&this._eventRemovalQueue.length){for(a=0;a<this._eventRemovalQueue.length;a++)this._eventRemovalQueue[a]();this._eventRemovalQueue=[]}},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":25}],19:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if("object"===m&&null===a&&(m="null"),"object"===n&&null===b&&(n="null"),e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m&&"null"!==m||"string"!==n&&"number"!==n&&"null"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m||"null"===m||"null"===n?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$fastIn":return c instanceof Array?-1!==c.indexOf(b):(console.log(this.logIdentifier()+" Cannot use an $fastIn operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],21:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],22:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f.triggerStack={},f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},ignoreTriggers:function(a){return void 0!==a?(this._ignoreTriggers=a,this):this._ignoreTriggers},addLinkIO:function(a,b){var c,d,e,f,g,h,i,j,k,l=this;if(l._linkIO=l._linkIO||{},l._linkIO[a]=b,d=b["export"],e=b["import"],d&&(h=l.db().collection(d.to)),e&&(i=l.db().collection(e.from)),j=[l.TYPE_INSERT,l.TYPE_UPDATE,l.TYPE_REMOVE],c=function(a,b){b(!1,!0)},d&&(d.match||(d.match=c),d.types||(d.types=j),f=function(a,b,c){d.match(c,function(b,e){!b&&e&&d.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?h.upsert(c,d):h.remove(c,d),h.ignoreTriggers(!1))})})}),e&&(e.match||(e.match=c),e.types||(e.types=j),g=function(a,b,c){e.match(c,function(b,d){!b&&d&&e.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?l.upsert(c,d):l.remove(c,d),h.ignoreTriggers(!1))})})}),d)for(k=0;k<d.types.length;k++)l.addTrigger(a+"export"+d.types[k],d.types[k],l.PHASE_AFTER,f);if(e)for(k=0;k<e.types.length;k++)i.addTrigger(a+"import"+e.types[k],e.types[k],l.PHASE_AFTER,g)},removeLinkIO:function(a){var b,c,d,e,f=this,g=f._linkIO[a];if(g){if(b=g["export"],c=g["import"],b)for(e=0;e<b.types.length;e++)f.removeTrigger(a+"export"+b.types[e],b.types[e],f.db.PHASE_AFTER);if(c)for(d=f.db().collection(c.from),e=0;e<c.types.length;e++)d.removeTrigger(a+"import"+c.types[e],c.types[e],f.db.PHASE_AFTER);return delete f._linkIO[a],!0}return!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(!this._ignoreTriggers&&this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this;if(!m._ignoreTriggers&&m._trigger&&m._trigger[b]&&m._trigger[b][c]){for(f=m._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(m.debug()){switch(b){case this.TYPE_INSERT:k="insert";break;case this.TYPE_UPDATE:k="update";break;case this.TYPE_REMOVE:k="remove";break;default:k=""}switch(c){case this.PHASE_BEFORE:l="before";break;case this.PHASE_AFTER:l="after";break;default:l=""}console.log('Triggers: Processing trigger "'+i.id+'" for '+k+' in phase "'+l+'"')}if(m.triggerStack&&m.triggerStack[b]&&m.triggerStack[b][c]&&m.triggerStack[b][c][i.id]){m.debug()&&console.log('Triggers: Will not run trigger "'+i.id+'" for '+k+' in phase "'+l+'" as it is already in the stack!');continue}if(m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!0,j=i.method.call(m,a,d,e),m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!1,j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":25}],23:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updateSplicePull:function(a,b,c){c||(c=1),a.splice(b,c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],24:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":26,"./Shared":29}],25:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),-1===f.indexOf("*"))e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;d>c;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":29}],27:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":29}],28:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date?(a.toJSON=function(){return"$date:"+this.toISOString()},!0):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),this.registerHandler("$regexp",function(a){return a instanceof RegExp?(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0):!1},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],29:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.830",modules:{},plugins:{},index:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){ var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./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(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}]},{},[1]);
blueprints/smart/files/__root__/containers/__name__.js
ashelkov/hexa
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' type Props = { } export class <%= pascalEntityName %> extends React.Component { props: Props; render() { return ( <div></div> ) } } const mapStateToProps = (state) => { return {} } const mapDispatchToProps = (dispatch) => { return {} } export default connect( mapStateToProps, mapDispatchToProps )(<%= pascalEntityName %>)
src/main/resources/static/bower_components/jqwidgets/demos/react/app/chart/polarseries/app.js
dhawal9035/WebPLP
import React from 'react'; import ReactDOM from 'react-dom'; import JqxChart from '../../../jqwidgets-react/react_jqxchart.js'; import JqxDropDownList from '../../../jqwidgets-react/react_jqxdropdownlist.js'; import JqxSlider from '../../../jqwidgets-react/react_jqxslider.js'; class App extends React.Component { componentDidMount() { this.refs.sliderStartAngle.on('change',(event) => { let value = event.args.value; this.refs.myChart.seriesGroups()[0].startAngle = value; this.refs.myChart.seriesGroups()[0].endAngle = value + 360; this.refs.myChart.update(); }); this.refs.sliderRadius.on('change', (event) => { let value = event.args.value; this.refs.myChart.seriesGroups()[0].radius = value; this.refs.myChart.update(); }); this.refs.dropDownListColor.on('change', (event) => { let value = event.args.item.value; this.refs.myChart.colorScheme(value); }); this.refs.dropDownListSeries.on('select', (event) => { let value = event.args.item.value; this.refs.myChart.seriesGroups()[0].type = value; this.refs.myChart.update(); }); } render () { let source = { datatype: "tab", datafields: [ { name: 'Year' }, { name: 'HPI' }, { name: 'BuildCost' }, { name: 'Population' }, { name: 'Rate' } ], url: '../sampledata/homeprices.txt' }; let dataAdapter = new $.jqx.dataAdapter(source, { async: false, autoBind: true, loadError: (xhr, status, error) => { alert('Error loading "' + source.url + '" : ' + error); } }); let padding = { left: 5, top: 5, right: 5, bottom: 5 }; let titlePadding = { left: 0, top: 0, right: 0, bottom: 5 }; let xAxis = { dataField: 'Year', unitInterval: 10, maxValue: 2010, valuesOnTicks: true, labels: { autoRotate: true } }; let seriesGroups = [ { polar: true, radius: 120, type: 'splinearea', valueAxis: { labels: { formatSettings: { decimalPlaces: 0 }, autoRotate: true } }, series: [ { dataField: 'HPI', displayText: 'Real Home Price Index', opacity: 0.7, lineWidth: 1, radius: 2, lineWidth: 2 }, { dataField: 'BuildCost', displayText: 'Building Cost Index', opacity: 0.7, lineWidth: 1, radius: 2, lineWidth: 2 } ] } ]; let colorsSchemesList = ["scheme01", "scheme02", "scheme03", "scheme04", "scheme05", "scheme06", "scheme07", "scheme08"]; let seriesList = ["splinearea", "spline", "column", "scatter", "stackedcolumn", "stackedsplinearea", "stackedspline"]; let chartCSS = { width:850, height:500, marginBottom: 1 }; let pCSS = { fontFamily: 'Verdana', fontSize: 12 }; return ( <div> <JqxChart ref='myChart' style={{ width:850, height:500 }} title={"U.S. Real Home Price vs Building Cost Indeces (1950-2010)"} description={"Source: http://www.econ.yale.edu/~shiller/data.htm"} showLegend={true} enableAnimations={true} padding={padding} titlePadding={titlePadding} source={dataAdapter} xAxis={xAxis} colorScheme={'scheme01'} seriesGroups={seriesGroups} /> <table style={{ width: 850 }}> <tbody> <tr> <td style={{ paddingLeft:50 }}> <p style={pCSS}>Move the slider to rotate:</p> <JqxSlider ref='sliderStartAngle' width={240} min={0} max={360} step={1} ticksFrequency={20} mode={'fixed'} /> </td> <td> <p style={pCSS}>Select the series type:</p> <JqxDropDownList ref='dropDownListColor' width={200} height={25} source={colorsSchemesList} selectedIndex={2} dropDownHeight={100} /> </td> </tr> <tr> <td style={{ paddingLeft:50 }}> <p style={pCSS}>Move the slider to change the radius:</p> <JqxSlider ref='sliderRadius' width={240} min={80} max={140} step={1} ticksFrequency={20} mode={'fixed'} /> </td> <td> <p style={pCSS}>Select color scheme:</p> <JqxDropDownList ref='dropDownListSeries' width={200} height={25} source={seriesList} selectedIndex={0} dropDownHeight={100} /> </td> </tr> </tbody> </table> </div> ) } } //Render our App Component to the desirable element ReactDOM.render(<App />, document.getElementById('app'));
src/components/common/UtilityIcon.js
Gisto/Gisto
import React from 'react'; import PropTypes from 'prop-types'; import styled, { css, withTheme } from 'styled-components'; import Icon from 'components/common/Icon'; const DropdownMixin = css` position: absolute; background: ${(props) => props.theme.lightText}; right: 0; top: 51px; border: 1px solid ${(props) => props.theme.borderColor}; line-height: 21px; list-style-type: none; margin: 0; padding: 0; box-shadow: 0 5px 10px ${(props) => props.theme.borderColor}; z-index: 4; overflow: auto; max-height: 65vh; color: ${(props) => props.theme.baseAppColor}; cursor: default; `; const Util = styled.span` border-left: 1px solid ${(props) => props.theme.borderColor}; height: 50px; display: inline-block; text-align: center; line-height: 50px; color: ${(props) => (props.color ? props.color : 'inherit')}; cursor: pointer; position: relative; background: ${(props) => (props.background ? props.background : 'inherit')}; ${(props) => (props.text ? 'padding: 0 15px;' : '')} ${(props) => (props.text ? '' : 'width: 50px;')} &:hover { background: ${(props) => (props.background ? props.background : props.theme.lightBorderColor)}; } div.list { ${DropdownMixin}; padding: 10px 20px; } ul { ${DropdownMixin} li { border-bottom: 1px dotted ${(props) => props.theme.orderColor}; margin: 0; white-space: nowrap; text-align: left; > * { padding: 5px 20px; display: block; } &:hover { background: ${(props) => props.theme.lightBorderColor}; cursor: pointer; } &:last-child { border: none; } } } `; export class UtilityIcon extends React.Component { childrenDropdown = React.createRef(); state = { childrenShown: false }; toggleChildren = () => { if (!this.state.childrenShown) { document.addEventListener('click', this.handleOutsideClick, false); } else { document.removeEventListener('click', this.handleOutsideClick, false); } this.setState((prevState) => ({ childrenShown: !prevState.childrenShown })); }; handleOutsideClick = (e) => { if ( this.childrenDropdown && e.target && this.childrenDropdown.current.contains(e.target) === false ) { this.toggleChildren(); } }; render() { const { lightText, colorDanger } = this.props.theme; const { children, size = 22, type, color = lightText, onClick = null, dropdown = false, title, className, background, text, spin } = this.props; const { childrenShown } = this.state; return ( <Util className={ className } background={ background } onClick={ () => (dropdown ? this.toggleChildren() : onClick()) } title={ title } text={ text } color={ childrenShown ? colorDanger : color }> <Icon size={ size } spin={ spin } type={ childrenShown ? 'close' : type } color={ childrenShown ? colorDanger : color }/>{' '} {text && text} {dropdown && childrenShown && <span ref={ this.childrenDropdown }>{children}</span>} </Util> ); } } UtilityIcon.propTypes = { children: PropTypes.node, size: PropTypes.number, type: PropTypes.string, color: PropTypes.string, onClick: PropTypes.func, dropdown: PropTypes.bool, spin: PropTypes.bool, title: PropTypes.string, className: PropTypes.string, background: PropTypes.string, text: PropTypes.string, theme: PropTypes.object }; export default withTheme(UtilityIcon);
pages/api/card-header.js
Kagami/material-ui
import 'docs/src/modules/components/bootstrap'; // --- Post bootstrap ----- import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './card-header.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default Page;
ajax/libs/yui/3.7.0/event-custom-base/event-custom-base.js
hare1039/cdnjs
YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { this._kds = Y.CustomEvent.keepDeprecatedSubs; o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ if (this._kds) { this.subscribers = {}; } /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ this._subscribers = []; /** * 'After' subscribers * @property afters * @type Subscriber {} */ if (this._kds) { this.afters = {}; } /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ this._afters = []; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; // this.subCount = 0; // this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this._subscribers.length, a = this._afters.length, sib = this.sibling; if (sib) { s += sib._subscribers.length; a += sib._afters.length; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = this._subscribers, a = this._afters, sib = this.sibling; s = (sib) ? s.concat(sib._subscribers) : s.concat(); a = (sib) ? a.concat(sib._afters) : a.concat(); return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this._afters.push(s); } else { this._subscribers.push(s); } if (this._kds) { if (when == AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { return true; } else { var args = nativeSlice.call(arguments, 0); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; i = YArray.indexOf(subs, s, 0); } if (s && subs[i] === s) { subs.splice(i, 1); } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; events = edata.events; ce = events[type]; this._monitor('publish', type, { args: arguments }); if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // TODO: Lazy publish goes here. defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, defaults); if (opts) { ce.applyConfig(opts, true); } events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), yuievt = this._yuievt, pre = yuievt.config.prefix, ce, ret, ce2, args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments; t = (pre) ? _getType(t, pre) : t; ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } this._monitor('fire', (ce || t), { args: args }); // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]});
app/javascript/mastodon/components/media_gallery.js
palon7/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import IconButton from './icon_button'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { isIOS } from '../is_mobile'; const messages = defineMessages({ toggle_visible: { id: 'media_gallery.toggle_visible', defaultMessage: 'Toggle visibility' }, }); class Item extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { attachment: ImmutablePropTypes.map.isRequired, index: PropTypes.number.isRequired, size: PropTypes.number.isRequired, onClick: PropTypes.func.isRequired, autoPlayGif: PropTypes.bool, }; static defaultProps = { autoPlayGif: false, }; handleMouseEnter = (e) => { if (this.hoverToPlay()) { e.target.play(); } } handleMouseLeave = (e) => { if (this.hoverToPlay()) { e.target.pause(); e.target.currentTime = 0; } } hoverToPlay () { const { attachment, autoPlayGif } = this.props; return !autoPlayGif && attachment.get('type') === 'gifv'; } handleClick = (e) => { const { index, onClick } = this.props; if (this.context.router && e.button === 0) { e.preventDefault(); onClick(index); } e.stopPropagation(); } render () { const { attachment, index, size } = this.props; let width = 50; let height = 100; let top = 'auto'; let left = 'auto'; let bottom = 'auto'; let right = 'auto'; if (size === 1) { width = 100; } if (size === 4 || (size === 3 && index > 0)) { height = 50; } if (size === 2) { if (index === 0) { right = '2px'; } else { left = '2px'; } } else if (size === 3) { if (index === 0) { right = '2px'; } else if (index > 0) { left = '2px'; } if (index === 1) { bottom = '2px'; } else if (index > 1) { top = '2px'; } } else if (size === 4) { if (index === 0 || index === 2) { right = '2px'; } if (index === 1 || index === 3) { left = '2px'; } if (index < 2) { bottom = '2px'; } else { top = '2px'; } } let thumbnail = ''; if (attachment.get('type') === 'image') { const previewUrl = attachment.get('preview_url'); const previewWidth = attachment.getIn(['meta', 'small', 'width']); const originalUrl = attachment.get('url'); const originalWidth = attachment.getIn(['meta', 'original', 'width']); const hasSize = typeof originalWidth === 'number' && typeof previewWidth === 'number'; const srcSet = hasSize && `${originalUrl} ${originalWidth}w, ${previewUrl} ${previewWidth}w`; const sizes = hasSize && `(min-width: 1025px) ${320 * (width / 100)}px, ${width}vw`; thumbnail = ( <a className='media-gallery__item-thumbnail' href={attachment.get('remote_url') || originalUrl} onClick={this.handleClick} target='_blank' > <img src={previewUrl} srcSet={srcSet} sizes={sizes} alt='' /> </a> ); } else if (attachment.get('type') === 'gifv') { const autoPlay = !isIOS() && this.props.autoPlayGif; thumbnail = ( <div className={`media-gallery__gifv ${autoPlay ? 'autoplay' : ''}`}> <video className='media-gallery__item-gifv-thumbnail' role='application' src={attachment.get('url')} onClick={this.handleClick} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} autoPlay={autoPlay} loop muted /> <span className='media-gallery__gifv__label'>GIF</span> </div> ); } return ( <div className='media-gallery__item' key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}> {thumbnail} </div> ); } } @injectIntl export default class MediaGallery extends React.PureComponent { static propTypes = { sensitive: PropTypes.bool, media: ImmutablePropTypes.list.isRequired, height: PropTypes.number.isRequired, onOpenMedia: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, autoPlayGif: PropTypes.bool, }; static defaultProps = { autoPlayGif: false, }; state = { visible: !this.props.sensitive, }; componentWillReceiveProps (nextProps) { if (nextProps.sensitive !== this.props.sensitive) { this.setState({ visible: !nextProps.sensitive }); } } handleOpen = () => { this.setState({ visible: !this.state.visible }); } handleClick = (index) => { this.props.onOpenMedia(this.props.media, index); } render () { const { media, intl, sensitive } = this.props; let children; if (!this.state.visible) { let warning; if (sensitive) { warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />; } else { warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />; } children = ( <button className='media-spoiler' onClick={this.handleOpen}> <span className='media-spoiler__warning'>{warning}</span> <span className='media-spoiler__trigger'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span> </button> ); } else { const size = media.take(4).size; children = media.take(4).map((attachment, i) => <Item key={attachment.get('id')} onClick={this.handleClick} attachment={attachment} autoPlayGif={this.props.autoPlayGif} index={i} size={size} />); } return ( <div className='media-gallery' style={{ height: `${this.props.height}px` }}> <div className={`spoiler-button ${this.state.visible ? 'spoiler-button--visible' : ''}`}> <IconButton title={intl.formatMessage(messages.toggle_visible)} icon={this.state.visible ? 'eye' : 'eye-slash'} overlay onClick={this.handleOpen} /> </div> {children} </div> ); } }
src/containers/waiter/orders.js
batusai513/client-side-restaurant-app
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { fetchOrders, listenOrders, stopListenningOrders, editOrder, updateOrderState, newOrder} from 'actions/orders'; import { WaiterOrders } from 'components/waiter'; import { objectToArray } from 'helpers/format-helpers'; function mapStateToProps(state, props){ return { waiterId: state.staff.authedId, orders: objectToArray(state.orders.list || {}), restaurantId: props.restaurantId }; } function mapDispatchToProps(dispatch){ return bindActionCreators({ fetchOrders, editOrder, updateOrderState, newOrder, listenOrders, stopListenningOrders }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(WaiterOrders);
gatsby-strapi-tutorial/cms/admin/admin/src/components/SupportUsTitle/index.js
strapi/strapi-examples
/** * * SupportUsTitle */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import styles from './styles.scss'; function SupportUsTitle() { return ( <FormattedMessage id="app.components.HomePage.support"> {message => <span className={styles.supportUsTitle}>{message}</span>} </FormattedMessage> ); } export default SupportUsTitle;
src/pages/ShoutemUI.js
marktani/react-native-express-1
import React from 'react' import markdown from 'markdown-in-js' import markdownOptions from '../utils/MarkdownOptions' import DefaultPage from './DefaultPage' import { WebPlayer, GithubRepositoryLink } from '../components' const code = `import React, { Component } from 'react' import { AppRegistry, ScrollView } from 'react-native' import { View, Text, Image, Tile, Heading, Title, Subtitle, Caption, Divider, Card, Button, TextInput, } from '@shoutem/ui' const imageSources = [ {uri: 'http://shoutem.github.io/img/ui-toolkit/examples/image-3.png'}, {uri: 'http://shoutem.github.io/img/ui-toolkit/examples/image-4.png'}, ] class App extends Component { render() { return ( <ScrollView style={styles.container}> <Tile styleName={'text-centric inflexible'}> <Title> Shoutem UI </Title> </Tile> <Divider styleName={'section-header'}> <Caption>INPUTS</Caption> </Divider> <TextInput placeholder={'Type here'} /> <Divider styleName={'section-header'}> <Caption>BUTTONS</Caption> </Divider> <View style={styles.row} styleName={'md-gutter'} > <Button styleName={'dark'}> <Text>Button 1</Text> </Button> <Button styleName={'md-gutter-left'}> <Text>Button 2</Text> </Button> </View> <Divider styleName={'section-header'}> <Caption>CARDS</Caption> </Divider> <Tile styleName={'stretch'}> <Image styleName={'large'} source={imageSources[0]} /> <View styleName={'content'}> <Subtitle>Large Card with Image and Caption</Subtitle> <Caption>21 hours ago</Caption> </View> </Tile> <Divider styleName={'section-header'}> <Caption>...AND MORE!</Caption> </Divider> </ScrollView> ) } } const styles = { container: { flex: 1, }, row: { flexDirection: 'row', }, } AppRegistry.registerComponent('App', () => App) ` const vendorComponents = [ ['@shoutem/theme', 'https://cdn.rawgit.com/dabbott/theme/f94c5c8c27fbdd673e3c0730730f8ab61d39613f/dist/shoutem-theme.js'], ['@shoutem/animation', 'https://cdn.rawgit.com/dabbott/animation/496810888db6cc0bc19c0d3abbcc9a4de8e8a0dc/dist/shoutem-animation.js'], ['@shoutem/ui', 'https://cdn.rawgit.com/dabbott/ui/4b7e380626c8beb0f4fb199078d40ef2da7e702a/dist/shoutem-ui.js'], ] const content = markdown(markdownOptions)` Shoutem UI is a themable, animatable component collection. Of the common component libraries available today, Shoutem likely prioritizes design the most. Apps built with these components tend to look beautiful and consistent without too much time spent pixel-pushing. The components available thus far are more presentational than navigational. Shoutem focuses on cards with text, buttons, and rich media, which can then be combined into lists and grids. Shoutem doesn't provide drawers, tab bars, modals, etc. You would still want to use a navigation library for those components. There are three distinct libraries: - ${<GithubRepositoryLink user={'shoutem'} repo={'ui'} title={'Shoutem Components'} />}\\ A collection of ~100 UI components, including typography, buttons, lists, grids, etc. - ${<GithubRepositoryLink user={'shoutem'} repo={'animation'} title={'Shoutem Animation'} />}\\ Declarative animations to apply to your components - ${<GithubRepositoryLink user={'shoutem'} repo={'theme'} title={'Shoutem Themes'} />}\\ CSS-like theming for components # Component Sandbox Consider the following example a sandbox for testing the various <code>@shoutem/ui</code> components. Getting started with Shoutem can be a little slow at first, because it introduces many new components and predefined styles (which are different for each component). However, once you get the hang of it, you'll find you can put together new screens extremely quickly. You'll likely want these pages open for reference: - [Shoutem UI Components](http://shoutem.github.io/docs/ui-toolkit/components/typography)\\ The list of components and how to use them. - [Shoutem UI Introduction](http://shoutem.github.io/docs/ui-toolkit/introduction)\\ This page describes the common <code>styleName</code>s for manipulating dimensions and margins. - [Default theme file](https://github.com/shoutem/ui/blob/develop/theme.js)\\ This is the list of default styles applied to components. You may override these defaults using the <code>style</code> prop on a component. This will make more sense after reading the [Shoutem Themes](shoutem_ui_theme) section. Some components won't display 100% accurately in the web simulator, so when you've decided to use Shoutem, it's best to get started with a real React Native app in your local development environment. ${ <WebPlayer title={'Shoutem UI'} code={code} vendorComponents={vendorComponents} /> } Let's take a look at how we can apply themes and animations to these components. ` export default props => <DefaultPage {...props}>{content}</DefaultPage>
tests/routes/Counter/components/Counter.spec.js
ShantanuShirpure/Portfolio
import React from 'react' import { bindActionCreators } from 'redux' import { Counter } from 'routes/Counter/components/Counter' import { shallow } from 'enzyme' describe('(Component) Counter', () => { let _props, _spies, _wrapper beforeEach(() => { _spies = {} _props = { counter : 5, ...bindActionCreators({ doubleAsync : (_spies.doubleAsync = sinon.spy()), increment : (_spies.increment = sinon.spy()) }, _spies.dispatch = sinon.spy()) } _wrapper = shallow(<Counter {..._props} />) }) it('Should render as a <div>.', () => { expect(_wrapper.is('div')).to.equal(true) }) it('Should render with an <h2> that includes Sample Counter text.', () => { expect(_wrapper.find('h2').text()).to.match(/Counter:/) }) it('Should render props.counter at the end of the sample counter <h2>.', () => { expect(_wrapper.find('h2').text()).to.match(/5$/) _wrapper.setProps({ counter: 8 }) expect(_wrapper.find('h2').text()).to.match(/8$/) }) it('Should render exactly two buttons.', () => { expect(_wrapper.find('button')).to.have.length(2) }) describe('An increment button...', () => { let _button beforeEach(() => { _button = _wrapper.find('button').filterWhere(a => a.text() === 'Increment') }) it('has bootstrap classes', () => { expect(_button.hasClass('btn btn-default')).to.be.true }) it('Should dispatch a `increment` action when clicked', () => { _spies.dispatch.should.have.not.been.called _button.simulate('click') _spies.dispatch.should.have.been.called _spies.increment.should.have.been.called }) }) describe('A Double (Async) button...', () => { let _button beforeEach(() => { _button = _wrapper.find('button').filterWhere(a => a.text() === 'Double (Async)') }) it('has bootstrap classes', () => { expect(_button.hasClass('btn btn-default')).to.be.true }) it('Should dispatch a `doubleAsync` action when clicked', () => { _spies.dispatch.should.have.not.been.called _button.simulate('click') _spies.dispatch.should.have.been.called _spies.doubleAsync.should.have.been.called }) }) })
app/components/shared/Popover/index.js
fotinakis/buildkite-frontend
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; const NIB_WIDTH = 32; const ScrollZone = styled.div` max-height: 80vh; overflow-y: auto; -webkit-overflow-scrolling: touch; `; const Nib = styled.img.attrs({ className: 'absolute pointer-events-none' })` top: -20px; width: ${NIB_WIDTH}px; height: 20px; z-index: 3; `; export default class Popover extends React.PureComponent { static propTypes = { children: PropTypes.node.isRequired, nibOffsetX: PropTypes.number.isRequired, offsetX: PropTypes.number.isRequired, offsetY: PropTypes.number.isRequired, style: PropTypes.object.isRequired, innerRef: PropTypes.func.isRequired, width: PropTypes.number.isRequired }; static defaultProps = { nibOffsetX: 0, offsetX: 0, offsetY: 45, style: {}, innerRef() {}, width: 250 }; render() { const { children, innerRef, nibOffsetX, offsetX, offsetY: top, style, width } = this.props; const offset = (width / 2) - offsetX; const popoverStyles = { left: `calc(50% - ${offset}px)`, top, transformOrigin: `${offset + nibOffsetX}px -15px`, width, zIndex: 3 }; return ( <div className="absolute mt1 bg-white rounded-2 shadow border border-gray block py1 transition-popup" ref={innerRef} style={Object.assign(popoverStyles, style)} > <Nib src={require('../../../images/up-pointing-white-nib.svg')} style={{ left: '50%', marginLeft: -(NIB_WIDTH / 2) - offsetX + nibOffsetX }} alt="" /> <ScrollZone> {children} </ScrollZone> </div> ); } } export AnchoredPopover from './anchored'; export calculateViewportOffsets from './calculate-viewport-offsets';
src/Welcome/index.js
techmsi/mental-health-app
// Stateless Component: Welcome Page import React from 'react'; import { Header } from 'styles/Layout'; import { WelcomeShell, WelcomeText, WelcomeButton } from 'Welcome/ui/styles-Welcome'; const Welcome = props => ( <WelcomeShell className='introduction'> <Header> <h1>Paitent Health Questionnaire (PHQ-9)</h1> </Header> <WelcomeText> This easy to use patient questionnaire is a self-administered version of the PRIME-MD diagnostic instrument for common mental disorders. The PHQ-9 is the depression module, which scores each of the nine DSM-IV criteria as "0" (not at all) to "3" (nearly every day). It has been validated for use in primary care. It is not a screening tool for depression but it is used to monitor the severity of depression and response to treatment. However, it can be used to make a tentative diagnosis of depression in at-risk populations - eg, those with coronary heart disease or after stroke. </WelcomeText> <WelcomeButton to='/questionnaire'> Begin Questionnaire</WelcomeButton> </WelcomeShell> ); export default Welcome;
src/panels/ItemEditor/index.js
Kitware/HPCCloud
import React from 'react'; import PropTypes from 'prop-types'; import style from 'HPCCloudStyle/ItemEditor.mcss'; import Toolbar from '../Toolbar'; import ButtonBar from '../ButtonBar'; function NoOp() {} /* eslint-disable react/no-multi-comp */ // ---------------------------------------------------------------------------- // FileUploadEntry // ---------------------------------------------------------------------------- class FileUploadEntry extends React.Component { constructor(props) { super(props); this.processFile = this.processFile.bind(this); } componentWillUnmount() { if (this.props.owner()) { this.props.owner().removeMetadata(); this.props.owner().removeAttachments(); } } processFile(event) { let file; if (event.target.files.length) { file = event.target.files[0]; } else if (event.dataTransfer.files.length) { file = event.dataTransfer.files[0]; } event.preventDefault(); event.stopPropagation(); if (!file) { return; } // Let's record attachment const name = event.target.dataset.name; if (this.props.owner && name) { this.props.owner().addAttachment(name, file); } // Let's post process it if (this.props.owner && this.props.postProcess) { this.props .postProcess(file, this.props.owner) .then((metadata) => { Object.keys(metadata).forEach((key) => { this.props.owner().addMetadata(key, metadata[key]); }); }) .catch((err) => { this.input.value = ''; }); } } render() { return ( <div className={style.group}> <label className={style.label}>{this.props.label}</label> <input ref={(c) => { this.input = c; }} className={style.input} data-name={this.props.name} accept={this.props.accept} type="file" onChange={this.processFile} /> </div> ); } } FileUploadEntry.propTypes = { accept: PropTypes.string, label: PropTypes.string, name: PropTypes.string, owner: PropTypes.func, postProcess: PropTypes.func, }; FileUploadEntry.defaultProps = { accept: '*', label: undefined, name: undefined, owner: undefined, postProcess: undefined, }; // ---------------------------------------------------------------------------- // TextEntry // ---------------------------------------------------------------------------- class TextEntry extends React.Component { constructor(props) { super(props); this.state = { [props.name]: props.default || '', }; this.updateMetadata = this.updateMetadata.bind(this); } updateMetadata(event) { const name = event.target.dataset.name; const value = event.target.value; this.setState({ [name]: value }); if (this.props.owner && name) { this.props.owner().addMetadata(name, value); } } render() { return ( <div className={style.group}> <label className={style.label}>{this.props.label}</label> <input className={style.input} data-name={this.props.name} type="text" value={this.state[this.props.name]} onChange={this.updateMetadata} /> </div> ); } } TextEntry.propTypes = { default: PropTypes.string, label: PropTypes.string, name: PropTypes.string, owner: PropTypes.func, }; TextEntry.defaultProps = { default: undefined, label: undefined, name: undefined, owner: undefined, }; // ---------------------------------------------------------------------------- // ItemEditor // ---------------------------------------------------------------------------- export { FileUploadEntry, TextEntry }; export default class ItemEditor extends React.Component { constructor(props) { super(props); this.state = { name: props.name, description: props.description, }; this.onAction = this.onAction.bind(this); this.addAttachment = this.addAttachment.bind(this); this.addMetadata = this.addMetadata.bind(this); this.removeAttachments = this.removeAttachments.bind(this); this.removeMetadata = this.removeMetadata.bind(this); this.updateForm = this.updateForm.bind(this); } componentDidMount() { this.attachment = {}; } onAction(action) { if (this.props.onAction) { this.props.onAction(action, this.state, this.attachment); } } addAttachment(name, file) { const attachment = this.attachment || {}; attachment[name] = file; this.attachment = attachment; } addMetadata(name, value) { const metadata = Object.assign({}, this.state.metadata); metadata[name] = value; this.setState({ metadata }); } removeAttachments() { this.attachment = {}; } removeMetadata(key = null) { if (key) { const metadata = Object.assign({}, this.state.metadata); delete metadata[key]; if (this.attachment[key]) { delete this.attachment[key]; } this.setState({ metadata }); return; } const metadata = Object.assign({}, this.state.metadata); if (this.attachment) { Object.keys(this.attachment).forEach((el) => { delete metadata[el]; }); } this.setState({ metadata }); } updateForm(e) { const key = e.target.dataset.name; const value = e.target.value; this.setState({ [key]: value }); } render() { return ( <div className={style.container}> <Toolbar breadcrumb={ this.props.breadcrumb || { paths: ['/'], icons: [style.listIcon] } } title={this.props.title} /> <div className={style.group}> <div className={style.label}> Name </div> <input className={style.input} type="text" value={this.state.name} data-name="name" onChange={this.updateForm} autoFocus /> </div> <div className={style.group}> <div className={style.label}> Description </div> <textarea className={style.input} data-name="description" rows="5" onChange={this.updateForm} value={this.state.description} /> </div> {this.props.children} <ButtonBar error={this.props.error} actions={this.props.actions} onAction={this.onAction} /> </div> ); } } ItemEditor.propTypes = { actions: PropTypes.array, breadcrumb: PropTypes.object, children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), description: PropTypes.string, error: PropTypes.string, name: PropTypes.string, onAction: PropTypes.func, title: PropTypes.oneOfType([PropTypes.object, PropTypes.string]), }; ItemEditor.defaultProps = { actions: [], description: '', error: '', name: '', onAction: NoOp, title: 'Item editor', children: undefined, breadcrumb: undefined, }; /* eslint-enable react/no-multi-comp */
docs/app/Examples/elements/Label/Types/LabelExampleImageColored.js
ben174/Semantic-UI-React
import React from 'react' import { Label } from 'semantic-ui-react' const LabelExampleImage = () => ( <div> <Label as='a' color='blue' image> <img src='http://semantic-ui.com/images/avatar/small/veronika.jpg' /> Veronika <Label.Detail>Friend</Label.Detail> </Label> <Label as='a' color='teal' image> <img src='http://semantic-ui.com/images/avatar/small/jenny.jpg' /> Veronika <Label.Detail>Friend</Label.Detail> </Label> <Label as='a' color='yellow' image> <img src='http://semantic-ui.com/images/avatar/small/christian.jpg' /> Helen <Label.Detail>Co-worker</Label.Detail> </Label> </div> ) export default LabelExampleImage
packages/react-scripts/fixtures/kitchensink/src/features/webpack/CssInclusion.js
prometheusresearch/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React from 'react' import './assets/style.css' export default () => ( <p id="feature-css-inclusion">We love useless text.</p> )
client/app/scripts/charts/node-shape-cloud.js
paulbellamy/scope
import React from 'react'; import { NODE_SHAPE_HIGHLIGHT_RADIUS, NODE_SHAPE_BORDER_RADIUS, NODE_SHAPE_SHADOW_RADIUS, NODE_SHAPE_DOT_RADIUS, NODE_BASE_SIZE, } from '../constants/styles'; // This path is already normalized so no dynamic rescaling is needed. const CLOUD_PATH = 'M-125 23.333Q-125 44.036-110.352 58.685-95.703 73.333-75 73.333H66.667Q90.755 ' + '73.333 107.878 56.211 125 39.089 125 15 125-2.188 115.755-16.445 106.51-30.703 91.406-37.734q' + '0.26-3.646 0.261-5.599 0-27.604-19.532-47.136-19.531-19.531-47.135-19.531-20.573 0-37.305 ' + '11.458-16.732 11.458-24.414 29.948-9.115-8.073-21.614-8.073-13.802 0-23.568 9.766-9.766 9.766-' + '9.766 23.568 0 9.766 5.339 17.968-16.797 3.906-27.735 17.513-10.938 13.607-10.937 31.185z'; export default function NodeShapeCloud({ highlighted, color }) { const pathProps = r => ({ d: CLOUD_PATH, transform: `scale(${r / NODE_BASE_SIZE})` }); return ( <g className="shape shape-cloud"> {highlighted && <path className="highlighted" {...pathProps(NODE_SHAPE_HIGHLIGHT_RADIUS)} />} <path className="border" stroke={color} {...pathProps(NODE_SHAPE_BORDER_RADIUS)} /> <path className="shadow" {...pathProps(NODE_SHAPE_SHADOW_RADIUS)} /> <circle className="node" r={NODE_SHAPE_DOT_RADIUS} /> </g> ); }
test/ButtonGroupSpec.js
bvasko/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import ButtonGroup from '../src/ButtonGroup'; import Button from '../src/Button'; import { shouldWarn } from './helpers'; describe('ButtonGroup', () => { it('Should output a button group', () => { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup> <Button> Title </Button> </ButtonGroup> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group\b/)); }); it('Should add size', () => { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup bsSize='large'> <Button> Title </Button> </ButtonGroup> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-lg\b/)); }); it('Should add vertical variation', () => { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup vertical> <Button> Title </Button> </ButtonGroup> ); assert.equal(React.findDOMNode(instance).className.trim(), 'btn-group-vertical'); }); it('Should add block variation', () => { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup vertical block> <Button> Title </Button> </ButtonGroup> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-block\b/)); }); it('Should warn about block without vertical', () => { ReactTestUtils.renderIntoDocument( <ButtonGroup block> <Button> Title </Button> </ButtonGroup> ); shouldWarn('The block property requires the vertical property to be set to have any effect'); }); it('Should add justified variation', () => { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup justified> <Button> Title </Button> </ButtonGroup> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-justified\b/)); }); });
components/Header/index.js
incodeit/incodeit.github.io
import React from 'react' import Logo from '-!svg-react-loader!./incode-logo.svg' import { Link } from 'react-router' import { prefixLink } from 'gatsby-helpers' import style from './Header.module.css' const Header = () => ( <header className={style.mainHeader}> <Link to={prefixLink('/')}> <Logo /> </Link> </header> ) export default Header
definitions/npm/react-splitter-layout_v3.x.x/test_splitter-layout.js
splodingsocks/FlowTyped
import { describe, it } from 'flow-typed-test'; import React from 'react'; import SplitterLayout from 'react-splitter-layout'; it('checks it takes at least 1 pane', () => { /* react-splitter-layout accepts several children but will render only the * first 2. When there's only one child it will render this child without the * splitter element. It also accepts `undefined` or `null` as child, and in * this case it will render only the other child. Because this is a licit * usage we test it here to prevent future regressions, even if the libdef as * it's currently defined doesn't special-case these values. * * In the future we might want to stricten the libdef to accept only 2 * children as it's likely a mistake to accept more than 2. */ let element = ( <SplitterLayout> <div>pane 1</div> <div>pane 2</div> </SplitterLayout> ); element = ( <SplitterLayout> <div>pane 1</div> </SplitterLayout> ); element = ( <SplitterLayout> <div>pane 1</div> {undefined} </SplitterLayout> ) element = ( <SplitterLayout> {null} <div>pane 1</div> </SplitterLayout> ) element = ( <SplitterLayout> <div>pane 1</div> <div>pane 2</div> <div>pane 3</div> </SplitterLayout> ); // $FlowExpectedError[prop-missing] element = <SplitterLayout/>; }); it('checks various props', () => { let element = ( <SplitterLayout customClassName="classname" vertical={true} percentage primaryIndex={1} primaryMinSize={50} secondaryMinSize={25} secondaryInitialSize={25} onDragStart={() => {}} onDragEnd={() => {}} onSecondaryPaneSizeChange={(size: number) => {}} > <div>pane 1</div> <div>pane 2</div> </SplitterLayout> ); element = ( <SplitterLayout onSecondaryPaneSizeChange={() => {}} > <div>pane 1</div> <div>pane 2</div> </SplitterLayout> ); element = ( <SplitterLayout // $FlowExpectedError[incompatible-type] onSecondaryPaneSizeChange={(size: string) => {}} > <div>pane 1</div> <div>pane 2</div> </SplitterLayout> ); element = ( <SplitterLayout // $FlowExpectedError[incompatible-type] primaryIndex={2} > <div>pane 1</div> <div>pane 2</div> </SplitterLayout> ); });
examples/typescript-react/node_modules/react/dist/react-with-addons.js
santhoshi-viriventi/todomvc
/** * React (with addons) v0.13.3 */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.React = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactWithAddons */ /** * This module exists purely in the open source project, and is meant as a way * to create a separate standalone build of React. This build has "addons", or * functionality we've built and think might be useful but doesn't have a good * place to live inside React core. */ 'use strict'; var LinkedStateMixin = _dereq_(25); var React = _dereq_(31); var ReactComponentWithPureRenderMixin = _dereq_(42); var ReactCSSTransitionGroup = _dereq_(34); var ReactFragment = _dereq_(69); var ReactTransitionGroup = _dereq_(98); var ReactUpdates = _dereq_(100); var cx = _dereq_(127); var cloneWithProps = _dereq_(122); var update = _dereq_(170); React.addons = { CSSTransitionGroup: ReactCSSTransitionGroup, LinkedStateMixin: LinkedStateMixin, PureRenderMixin: ReactComponentWithPureRenderMixin, TransitionGroup: ReactTransitionGroup, batchedUpdates: ReactUpdates.batchedUpdates, classSet: cx, cloneWithProps: cloneWithProps, createFragment: ReactFragment.create, update: update }; if ("production" !== "development") { React.addons.Perf = _dereq_(61); React.addons.TestUtils = _dereq_(95); } module.exports = React; },{"100":100,"122":122,"127":127,"170":170,"25":25,"31":31,"34":34,"42":42,"61":61,"69":69,"95":95,"98":98}],2:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AutoFocusMixin * @typechecks static-only */ 'use strict'; var focusNode = _dereq_(134); var AutoFocusMixin = { componentDidMount: function() { if (this.props.autoFocus) { focusNode(this.getDOMNode()); } } }; module.exports = AutoFocusMixin; },{"134":134}],3:[function(_dereq_,module,exports){ /** * Copyright 2013-2015 Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BeforeInputEventPlugin * @typechecks static-only */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(21); var ExecutionEnvironment = _dereq_(22); var FallbackCompositionState = _dereq_(23); var SyntheticCompositionEvent = _dereq_(106); var SyntheticInputEvent = _dereq_(110); var keyOf = _dereq_(157); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ( ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window ); var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ( ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto() ); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ( ExecutionEnvironment.canUseDOM && ( (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11) ) ); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return ( typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12 ); } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); var topLevelTypes = EventConstants.topLevelTypes; // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: keyOf({onBeforeInput: null}), captured: keyOf({onBeforeInputCapture: null}) }, dependencies: [ topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste ] }, compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({onCompositionEnd: null}), captured: keyOf({onCompositionEndCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({onCompositionStart: null}), captured: keyOf({onCompositionStartCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({onCompositionUpdate: null}), captured: keyOf({onCompositionUpdateCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return ( (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey) ); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.topCompositionUpdate: return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return ( topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE ); } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return (END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1); case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return (nativeEvent.keyCode !== START_KEYCODE); case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(topLevelTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled( eventType, topLevelTargetID, nativeEvent ); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topCompositionEnd: return getDataFromCustomEvent(nativeEvent); case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. if (currentComposition) { if ( topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent) ) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case topLevelTypes.topCompositionEnd: return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled( eventTypes.beforeInput, topLevelTargetID, nativeEvent ); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ) { return [ extractCompositionEvent( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ), extractBeforeInputEvent( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ) ]; } }; module.exports = BeforeInputEventPlugin; },{"106":106,"110":110,"157":157,"16":16,"21":21,"22":22,"23":23}],4:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSCore * @typechecks */ var invariant = _dereq_(150); /** * The CSSCore module specifies the API (and implements most of the methods) * that should be used when dealing with the display of elements (via their * CSS classes and visibility on screen. It is an API focused on mutating the * display and not reading it as no logical state should be encoded in the * display of elements. */ var CSSCore = { /** * Adds the class passed in to the element if it doesn't already have it. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ addClass: function(element, className) { ("production" !== "development" ? invariant( !/\s/.test(className), 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ) : invariant(!/\s/.test(className))); if (className) { if (element.classList) { element.classList.add(className); } else if (!CSSCore.hasClass(element, className)) { element.className = element.className + ' ' + className; } } return element; }, /** * Removes the class passed in from the element * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ removeClass: function(element, className) { ("production" !== "development" ? invariant( !/\s/.test(className), 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ) : invariant(!/\s/.test(className))); if (className) { if (element.classList) { element.classList.remove(className); } else if (CSSCore.hasClass(element, className)) { element.className = element.className .replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1') .replace(/\s+/g, ' ') // multiple spaces to one .replace(/^\s*|\s*$/g, ''); // trim the ends } } return element; }, /** * Helper to add or remove a class from an element based on a condition. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @param {*} bool condition to whether to add or remove the class * @return {DOMElement} the element passed in */ conditionClass: function(element, className, bool) { return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); }, /** * Tests whether the element has the class specified. * * @param {DOMNode|DOMWindow} element the element to set the class on * @param {string} className the CSS className * @return {boolean} true if the element has the class, false if not */ hasClass: function(element, className) { ("production" !== "development" ? invariant( !/\s/.test(className), 'CSS.hasClass takes only a single class name.' ) : invariant(!/\s/.test(className))); if (element.classList) { return !!className && element.classList.contains(className); } return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; } }; module.exports = CSSCore; },{"150":150}],5:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { boxFlex: true, boxFlexGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, strokeDashoffset: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function(prop) { prefixes.forEach(function(prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundImage: true, backgroundPosition: true, backgroundRepeat: true, backgroundColor: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; },{}],6:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSPropertyOperations * @typechecks static-only */ 'use strict'; var CSSProperty = _dereq_(5); var ExecutionEnvironment = _dereq_(22); var camelizeStyleName = _dereq_(121); var dangerousStyleValue = _dereq_(128); var hyphenateStyleName = _dereq_(148); var memoizeStringOnly = _dereq_(159); var warning = _dereq_(171); var processStyleName = memoizeStringOnly(function(styleName) { return hyphenateStyleName(styleName); }); var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if ("production" !== "development") { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnHyphenatedStyleName = function(name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; ("production" !== "development" ? warning( false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name) ) : null); }; var warnBadVendoredStyleName = function(name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; ("production" !== "development" ? warning( false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1) ) : null); }; var warnStyleValueWithSemicolon = function(name, value) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; ("production" !== "development" ? warning( false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '') ) : null); }; /** * @param {string} name * @param {*} value */ var warnValidStyle = function(name, value) { if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @return {?string} */ createMarkupForStyles: function(styles) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if ("production" !== "development") { warnValidStyle(styleName, styleValue); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles */ setValueForStyles: function(node, styles) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if ("production" !== "development") { warnValidStyle(styleName, styles[styleName]); } var styleValue = dangerousStyleValue(styleName, styles[styleName]); if (styleName === 'float') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; module.exports = CSSPropertyOperations; },{"121":121,"128":128,"148":148,"159":159,"171":171,"22":22,"5":5}],7:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CallbackQueue */ 'use strict'; var PooledClass = _dereq_(30); var assign = _dereq_(29); var invariant = _dereq_(150); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ function CallbackQueue() { this._callbacks = null; this._contexts = null; } assign(CallbackQueue.prototype, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ enqueue: function(callback, context) { this._callbacks = this._callbacks || []; this._contexts = this._contexts || []; this._callbacks.push(callback); this._contexts.push(context); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function() { var callbacks = this._callbacks; var contexts = this._contexts; if (callbacks) { ("production" !== "development" ? invariant( callbacks.length === contexts.length, 'Mismatched list of contexts in callback queue' ) : invariant(callbacks.length === contexts.length)); this._callbacks = null; this._contexts = null; for (var i = 0, l = callbacks.length; i < l; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, /** * Resets the internal queue. * * @internal */ reset: function() { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; },{"150":150,"29":29,"30":30}],8:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ChangeEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(18); var EventPropagators = _dereq_(21); var ExecutionEnvironment = _dereq_(22); var ReactUpdates = _dereq_(100); var SyntheticEvent = _dereq_(108); var isEventSupported = _dereq_(151); var isTextInputElement = _dereq_(153); var keyOf = _dereq_(157); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({onChange: null}), captured: keyOf({onChangeCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange ] } }; /** * For IE shims */ var activeElement = null; var activeElementID = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { return ( elem.nodeName === 'SELECT' || (elem.nodeName === 'INPUT' && elem.type === 'file') ); } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && ( (!('documentMode' in document) || document.documentMode > 8) ); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled( eventTypes.change, activeElementID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(); } function startWatchingForChangeEventIE8(target, targetID) { activeElement = target; activeElementID = targetID; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementID = null; } function getTargetIDForChangeEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topChange) { return topLevelTargetID; } } function handleEventsForChangeEventIE8( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events isInputEventSupported = isEventSupported('input') && ( (!('documentMode' in document) || document.documentMode > 9) ); } /** * (For old IE.) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function() { return activeElementValueProp.get.call(this); }, set: function(val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For old IE.) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetID) { activeElement = target; activeElementID = targetID; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor( target.constructor.prototype, 'value' ); Object.defineProperty(activeElement, 'value', newValueProp); activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For old IE.) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementID = null; activeElementValue = null; activeElementValueProp = null; } /** * (For old IE.) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetIDForInputEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return topLevelTargetID; } } // For IE8 and IE9. function handleEventsForInputEventIE( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetIDForInputEventIE( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementID; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return ( elem.nodeName === 'INPUT' && (elem.type === 'checkbox' || elem.type === 'radio') ); } function getTargetIDForClickEvent( topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topClick) { return topLevelTargetID; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var getTargetIDFunc, handleEventFunc; if (shouldUseChangeEvent(topLevelTarget)) { if (doesChangeEventBubble) { getTargetIDFunc = getTargetIDForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(topLevelTarget)) { if (isInputEventSupported) { getTargetIDFunc = getTargetIDForInputEvent; } else { getTargetIDFunc = getTargetIDForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(topLevelTarget)) { getTargetIDFunc = getTargetIDForClickEvent; } if (getTargetIDFunc) { var targetID = getTargetIDFunc( topLevelType, topLevelTarget, topLevelTargetID ); if (targetID) { var event = SyntheticEvent.getPooled( eventTypes.change, targetID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc( topLevelType, topLevelTarget, topLevelTargetID ); } } }; module.exports = ChangeEventPlugin; },{"100":100,"108":108,"151":151,"153":153,"157":157,"16":16,"18":18,"21":21,"22":22}],9:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ClientReactRootIndex * @typechecks */ 'use strict'; var nextReactRootIndex = 0; var ClientReactRootIndex = { createReactRootIndex: function() { return nextReactRootIndex++; } }; module.exports = ClientReactRootIndex; },{}],10:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMChildrenOperations * @typechecks static-only */ 'use strict'; var Danger = _dereq_(13); var ReactMultiChildUpdateTypes = _dereq_(79); var setTextContent = _dereq_(165); var invariant = _dereq_(150); /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ function insertChildAt(parentNode, childNode, index) { // By exploiting arrays returning `undefined` for an undefined index, we can // rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. However, using `undefined` is not allowed by all // browsers so we must replace it with `null`. parentNode.insertBefore( childNode, parentNode.childNodes[index] || null ); } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, updateTextContent: setTextContent, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markupList List of markup strings. * @internal */ processUpdates: function(updates, markupList) { var update; // Mapping from parent IDs to initial child orderings. var initialChildren = null; // List of children that will be moved or removed. var updatedChildren = null; for (var i = 0; i < updates.length; i++) { update = updates[i]; if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { var updatedIndex = update.fromIndex; var updatedChild = update.parentNode.childNodes[updatedIndex]; var parentID = update.parentID; ("production" !== "development" ? invariant( updatedChild, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID ) : invariant(updatedChild)); initialChildren = initialChildren || {}; initialChildren[parentID] = initialChildren[parentID] || []; initialChildren[parentID][updatedIndex] = updatedChild; updatedChildren = updatedChildren || []; updatedChildren.push(updatedChild); } } var renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); // Remove updated children first so that `toIndex` is consistent. if (updatedChildren) { for (var j = 0; j < updatedChildren.length; j++) { updatedChildren[j].parentNode.removeChild(updatedChildren[j]); } } for (var k = 0; k < updates.length; k++) { update = updates[k]; switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertChildAt( update.parentNode, renderedMarkup[update.markupIndex], update.toIndex ); break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: insertChildAt( update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex ); break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: setTextContent( update.parentNode, update.textContent ); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: // Already removed by the for-loop above. break; } } } }; module.exports = DOMChildrenOperations; },{"13":13,"150":150,"165":165,"79":79}],11:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty * @typechecks static-only */ /*jslint bitwise: true */ 'use strict'; var invariant = _dereq_(150); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_ATTRIBUTE: 0x1, MUST_USE_PROPERTY: 0x2, HAS_SIDE_EFFECTS: 0x4, HAS_BOOLEAN_VALUE: 0x8, HAS_NUMERIC_VALUE: 0x10, HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10, HAS_OVERLOADED_BOOLEAN_VALUE: 0x40, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function(domPropertyConfig) { var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push( domPropertyConfig.isCustomAttribute ); } for (var propName in Properties) { ("production" !== "development" ? invariant( !DOMProperty.isStandardName.hasOwnProperty(propName), 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName ) : invariant(!DOMProperty.isStandardName.hasOwnProperty(propName))); DOMProperty.isStandardName[propName] = true; var lowerCased = propName.toLowerCase(); DOMProperty.getPossibleStandardName[lowerCased] = propName; if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; DOMProperty.getPossibleStandardName[attributeName] = propName; DOMProperty.getAttributeName[propName] = attributeName; } else { DOMProperty.getAttributeName[propName] = lowerCased; } DOMProperty.getPropertyName[propName] = DOMPropertyNames.hasOwnProperty(propName) ? DOMPropertyNames[propName] : propName; if (DOMMutationMethods.hasOwnProperty(propName)) { DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName]; } else { DOMProperty.getMutationMethod[propName] = null; } var propConfig = Properties[propName]; DOMProperty.mustUseAttribute[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_ATTRIBUTE); DOMProperty.mustUseProperty[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_PROPERTY); DOMProperty.hasSideEffects[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_SIDE_EFFECTS); DOMProperty.hasBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_BOOLEAN_VALUE); DOMProperty.hasNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_NUMERIC_VALUE); DOMProperty.hasPositiveNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE); DOMProperty.hasOverloadedBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_VALUE); ("production" !== "development" ? invariant( !DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName], 'DOMProperty: Cannot require using both attribute and property: %s', propName ) : invariant(!DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName])); ("production" !== "development" ? invariant( DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName], 'DOMProperty: Properties that have side effects must use property: %s', propName ) : invariant(DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName])); ("production" !== "development" ? invariant( !!DOMProperty.hasBooleanValue[propName] + !!DOMProperty.hasNumericValue[propName] + !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName ) : invariant(!!DOMProperty.hasBooleanValue[propName] + !!DOMProperty.hasNumericValue[propName] + !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1)); } } }; var defaultValueCache = {}; /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', /** * Checks whether a property name is a standard property. * @type {Object} */ isStandardName: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. * @type {Object} */ getPossibleStandardName: {}, /** * Mapping from normalized names to attribute names that differ. Attribute * names are used when rendering markup or with `*Attribute()`. * @type {Object} */ getAttributeName: {}, /** * Mapping from normalized names to properties on DOM node instances. * (This includes properties that mutate due to external factors.) * @type {Object} */ getPropertyName: {}, /** * Mapping from normalized names to mutation methods. This will only exist if * mutation cannot be set simply by the property or `setAttribute()`. * @type {Object} */ getMutationMethod: {}, /** * Whether the property must be accessed and mutated as an object property. * @type {Object} */ mustUseAttribute: {}, /** * Whether the property must be accessed and mutated using `*Attribute()`. * (This includes anything that fails `<propName> in <element>`.) * @type {Object} */ mustUseProperty: {}, /** * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. We must ensure that * the value is only set if it has changed. * @type {Object} */ hasSideEffects: {}, /** * Whether the property should be removed when set to a falsey value. * @type {Object} */ hasBooleanValue: {}, /** * Whether the property must be numeric or parse as a * numeric and should be removed when set to a falsey value. * @type {Object} */ hasNumericValue: {}, /** * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * @type {Object} */ hasPositiveNumericValue: {}, /** * Whether the property can be used as a flag as well as with a value. Removed * when strictly equal to false; present without a value when strictly equal * to true; present with a value otherwise. * @type {Object} */ hasOverloadedBooleanValue: {}, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function(attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, /** * Returns the default property value for a DOM property (i.e., not an * attribute). Most default values are '' or false, but not all. Worse yet, * some (in particular, `type`) vary depending on the type of element. * * TODO: Is it better to grab all the possible properties when creating an * element to avoid having to create the same element twice? */ getDefaultValueForProperty: function(nodeName, prop) { var nodeDefaults = defaultValueCache[nodeName]; var testElement; if (!nodeDefaults) { defaultValueCache[nodeName] = nodeDefaults = {}; } if (!(prop in nodeDefaults)) { testElement = document.createElement(nodeName); nodeDefaults[prop] = testElement[prop]; } return nodeDefaults[prop]; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; },{"150":150}],12:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMPropertyOperations * @typechecks static-only */ 'use strict'; var DOMProperty = _dereq_(11); var quoteAttributeValueForBrowser = _dereq_(163); var warning = _dereq_(171); function shouldIgnoreValue(name, value) { return value == null || (DOMProperty.hasBooleanValue[name] && !value) || (DOMProperty.hasNumericValue[name] && isNaN(value)) || (DOMProperty.hasPositiveNumericValue[name] && (value < 1)) || (DOMProperty.hasOverloadedBooleanValue[name] && value === false); } if ("production" !== "development") { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true }; var warnedProperties = {}; var warnUnknownProperty = function(name) { if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = ( DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null ); // For now, only warn when we have a suggested correction. This prevents // logging too much when using transferPropsTo. ("production" !== "development" ? warning( standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName ) : null); }; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function(id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function(name, value) { if (DOMProperty.isStandardName.hasOwnProperty(name) && DOMProperty.isStandardName[name]) { if (shouldIgnoreValue(name, value)) { return ''; } var attributeName = DOMProperty.getAttributeName[name]; if (DOMProperty.hasBooleanValue[name] || (DOMProperty.hasOverloadedBooleanValue[name] && value === true)) { return attributeName; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } else if ("production" !== "development") { warnUnknownProperty(name); } return null; }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function(node, name, value) { if (DOMProperty.isStandardName.hasOwnProperty(name) && DOMProperty.isStandardName[name]) { var mutationMethod = DOMProperty.getMutationMethod[name]; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(name, value)) { this.deleteValueForProperty(node, name); } else if (DOMProperty.mustUseAttribute[name]) { // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. node.setAttribute(DOMProperty.getAttributeName[name], '' + value); } else { var propName = DOMProperty.getPropertyName[name]; // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the // property type before comparing; only `value` does and is string. if (!DOMProperty.hasSideEffects[name] || ('' + node[propName]) !== ('' + value)) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propName] = value; } } } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } } else if ("production" !== "development") { warnUnknownProperty(name); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function(node, name) { if (DOMProperty.isStandardName.hasOwnProperty(name) && DOMProperty.isStandardName[name]) { var mutationMethod = DOMProperty.getMutationMethod[name]; if (mutationMethod) { mutationMethod(node, undefined); } else if (DOMProperty.mustUseAttribute[name]) { node.removeAttribute(DOMProperty.getAttributeName[name]); } else { var propName = DOMProperty.getPropertyName[name]; var defaultValue = DOMProperty.getDefaultValueForProperty( node.nodeName, propName ); if (!DOMProperty.hasSideEffects[name] || ('' + node[propName]) !== defaultValue) { node[propName] = defaultValue; } } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } else if ("production" !== "development") { warnUnknownProperty(name); } } }; module.exports = DOMPropertyOperations; },{"11":11,"163":163,"171":171}],13:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Danger * @typechecks static-only */ /*jslint evil: true, sub: true */ 'use strict'; var ExecutionEnvironment = _dereq_(22); var createNodesFromMarkup = _dereq_(126); var emptyFunction = _dereq_(129); var getMarkupWrap = _dereq_(142); var invariant = _dereq_(150); var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/; var RESULT_INDEX_ATTR = 'data-danger-index'; /** * Extracts the `nodeName` from a string of markup. * * NOTE: Extracting the `nodeName` does not require a regular expression match * because we make assumptions about React-generated markup (i.e. there are no * spaces surrounding the opening tag and there is at least one attribute). * * @param {string} markup String of markup. * @return {string} Node name of the supplied markup. * @see http://jsperf.com/extract-nodename */ function getNodeName(markup) { return markup.substring(1, markup.indexOf(' ')); } var Danger = { /** * Renders markup into an array of nodes. The markup is expected to render * into a list of root nodes. Also, the length of `resultList` and * `markupList` should be the same. * * @param {array<string>} markupList List of markup strings to render. * @return {array<DOMElement>} List of rendered nodes. * @internal */ dangerouslyRenderMarkup: function(markupList) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'React.renderToString for server rendering.' ) : invariant(ExecutionEnvironment.canUseDOM)); var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { ("production" !== "development" ? invariant( markupList[i], 'dangerouslyRenderMarkup(...): Missing markup.' ) : invariant(markupList[i])); nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. var resultIndex; for (resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace( OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ' ); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup( markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (var j = 0; j < renderNodes.length; ++j) { var renderNode = renderNodes[j]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); ("production" !== "development" ? invariant( !resultList.hasOwnProperty(resultIndex), 'Danger: Assigning to an already-occupied result index.' ) : invariant(!resultList.hasOwnProperty(resultIndex))); resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if ("production" !== "development") { console.error( 'Danger: Discarding unexpected node:', renderNode ); } } } // Although resultList was populated out of order, it should now be a dense // array. ("production" !== "development" ? invariant( resultListAssignmentCount === resultList.length, 'Danger: Did not assign to every index of resultList.' ) : invariant(resultListAssignmentCount === resultList.length)); ("production" !== "development" ? invariant( resultList.length === markupList.length, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length ) : invariant(resultList.length === markupList.length)); return resultList; }, /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function(oldChild, markup) { ("production" !== "development" ? invariant( ExecutionEnvironment.canUseDOM, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'React.renderToString for server rendering.' ) : invariant(ExecutionEnvironment.canUseDOM)); ("production" !== "development" ? invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(markup)); ("production" !== "development" ? invariant( oldChild.tagName.toLowerCase() !== 'html', 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See React.renderToString().' ) : invariant(oldChild.tagName.toLowerCase() !== 'html')); var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } }; module.exports = Danger; },{"126":126,"129":129,"142":142,"150":150,"22":22}],14:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DefaultEventPluginOrder */ 'use strict'; var keyOf = _dereq_(157); /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = [ keyOf({ResponderEventPlugin: null}), keyOf({SimpleEventPlugin: null}), keyOf({TapEventPlugin: null}), keyOf({EnterLeaveEventPlugin: null}), keyOf({ChangeEventPlugin: null}), keyOf({SelectEventPlugin: null}), keyOf({BeforeInputEventPlugin: null}), keyOf({AnalyticsEventPlugin: null}), keyOf({MobileSafariClickEventPlugin: null}) ]; module.exports = DefaultEventPluginOrder; },{"157":157}],15:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EnterLeaveEventPlugin * @typechecks static-only */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(21); var SyntheticMouseEvent = _dereq_(112); var ReactMount = _dereq_(77); var keyOf = _dereq_(157); var topLevelTypes = EventConstants.topLevelTypes; var getFirstReactDOM = ReactMount.getFirstReactDOM; var eventTypes = { mouseEnter: { registrationName: keyOf({onMouseEnter: null}), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] }, mouseLeave: { registrationName: keyOf({onMouseLeave: null}), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] } }; var extractedEvents = [null, null]; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (topLevelTarget.window === topLevelTarget) { // `topLevelTarget` is probably a window object. win = topLevelTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = topLevelTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from, to; if (topLevelType === topLevelTypes.topMouseOut) { from = topLevelTarget; to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) || win; } else { from = win; to = topLevelTarget; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromID = from ? ReactMount.getID(from) : ''; var toID = to ? ReactMount.getID(to) : ''; var leave = SyntheticMouseEvent.getPooled( eventTypes.mouseLeave, fromID, nativeEvent ); leave.type = 'mouseleave'; leave.target = from; leave.relatedTarget = to; var enter = SyntheticMouseEvent.getPooled( eventTypes.mouseEnter, toID, nativeEvent ); enter.type = 'mouseenter'; enter.target = to; enter.relatedTarget = from; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID); extractedEvents[0] = leave; extractedEvents[1] = enter; return extractedEvents; } }; module.exports = EnterLeaveEventPlugin; },{"112":112,"157":157,"16":16,"21":21,"77":77}],16:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventConstants */ 'use strict'; var keyMirror = _dereq_(156); var PropagationPhases = keyMirror({bubbled: null, captured: null}); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topBlur: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topError: null, topFocus: null, topInput: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topReset: null, topScroll: null, topSelectionChange: null, topSubmit: null, topTextInput: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; },{"156":156}],17:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule EventListener * @typechecks */ var emptyFunction = _dereq_(129); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function() { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function(target, eventType, callback) { if (!target.addEventListener) { if ("production" !== "development") { console.error( 'Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.' ); } return { remove: emptyFunction }; } else { target.addEventListener(eventType, callback, true); return { remove: function() { target.removeEventListener(eventType, callback, true); } }; } }, registerDefault: function() {} }; module.exports = EventListener; },{"129":129}],18:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginHub */ 'use strict'; var EventPluginRegistry = _dereq_(19); var EventPluginUtils = _dereq_(20); var accumulateInto = _dereq_(118); var forEachAccumulated = _dereq_(135); var invariant = _dereq_(150); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @private */ var executeDispatchesAndRelease = function(event) { if (event) { var executeDispatch = EventPluginUtils.executeDispatch; // Plugins can provide custom behavior when dispatching events. var PluginModule = EventPluginRegistry.getPluginModuleForEvent(event); if (PluginModule && PluginModule.executeDispatch) { executeDispatch = PluginModule.executeDispatch; } EventPluginUtils.executeDispatchesInOrder(event, executeDispatch); if (!event.isPersistent()) { event.constructor.release(event); } } }; /** * - `InstanceHandle`: [required] Module that performs logical traversals of DOM * hierarchy given ids of the logical DOM elements involved. */ var InstanceHandle = null; function validateInstanceHandle() { var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave; ("production" !== "development" ? invariant( valid, 'InstanceHandle not injected before use!' ) : invariant(valid)); } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {object} InjectedMount * @public */ injectMount: EventPluginUtils.injection.injectMount, /** * @param {object} InjectedInstanceHandle * @public */ injectInstanceHandle: function(InjectedInstanceHandle) { InstanceHandle = InjectedInstanceHandle; if ("production" !== "development") { validateInstanceHandle(); } }, getInstanceHandle: function() { if ("production" !== "development") { validateInstanceHandle(); } return InstanceHandle; }, /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs, registrationNameModules: EventPluginRegistry.registrationNameModules, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {?function} listener The callback to store. */ putListener: function(id, registrationName, listener) { ("production" !== "development" ? invariant( !listener || typeof listener === 'function', 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener ) : invariant(!listener || typeof listener === 'function')); var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[id] = listener; }, /** * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[id]; }, /** * Deletes a listener from the registration bank. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; if (bankForRegistrationName) { delete bankForRegistrationName[id]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {string} id ID of the DOM element. */ deleteAllListeners: function(id) { for (var registrationName in listenerBank) { delete listenerBank[registrationName][id]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0, l = plugins.length; i < l; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function(events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function() { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; forEachAccumulated(processingEventQueue, executeDispatchesAndRelease); ("production" !== "development" ? invariant( !eventQueue, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.' ) : invariant(!eventQueue)); }, /** * These are needed for tests only. Do not use! */ __purge: function() { listenerBank = {}; }, __getListenerBank: function() { return listenerBank; } }; module.exports = EventPluginHub; },{"118":118,"135":135,"150":150,"19":19,"20":20}],19:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginRegistry * @typechecks static-only */ 'use strict'; var invariant = _dereq_(150); /** * Injectable ordering of event plugins. */ var EventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!EventPluginOrder) { // Wait until an `EventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName]; var pluginIndex = EventPluginOrder.indexOf(pluginName); ("production" !== "development" ? invariant( pluginIndex > -1, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName ) : invariant(pluginIndex > -1)); if (EventPluginRegistry.plugins[pluginIndex]) { continue; } ("production" !== "development" ? invariant( PluginModule.extractEvents, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName ) : invariant(PluginModule.extractEvents)); EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { ("production" !== "development" ? invariant( publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ), 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName ) : invariant(publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ))); } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { ("production" !== "development" ? invariant( !EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName ) : invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName))); EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName( phasedRegistrationName, PluginModule, eventName ); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName( dispatchConfig.registrationName, PluginModule, eventName ); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { ("production" !== "development" ? invariant( !EventPluginRegistry.registrationNameModules[registrationName], 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName ) : invariant(!EventPluginRegistry.registrationNameModules[registrationName])); EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function(InjectedEventPluginOrder) { ("production" !== "development" ? invariant( !EventPluginOrder, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.' ) : invariant(!EventPluginOrder)); // Clone the ordering so it cannot be dynamically mutated. EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function(injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var PluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) { ("production" !== "development" ? invariant( !namesToPlugins[pluginName], 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName ) : invariant(!namesToPlugins[pluginName])); namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function(event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[ dispatchConfig.registrationName ] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[ dispatchConfig.phasedRegistrationNames[phase] ]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function() { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } } }; module.exports = EventPluginRegistry; },{"150":150}],20:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginUtils */ 'use strict'; var EventConstants = _dereq_(16); var invariant = _dereq_(150); /** * Injected dependencies: */ /** * - `Mount`: [required] Module that can convert between React dom IDs and * actual node references. */ var injection = { Mount: null, injectMount: function(InjectedMount) { injection.Mount = InjectedMount; if ("production" !== "development") { ("production" !== "development" ? invariant( InjectedMount && InjectedMount.getNode, 'EventPluginUtils.injection.injectMount(...): Injected Mount module ' + 'is missing getNode.' ) : invariant(InjectedMount && InjectedMount.getNode)); } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if ("production" !== "development") { validateEventDispatches = function(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; var listenersIsArr = Array.isArray(dispatchListeners); var idsIsArr = Array.isArray(dispatchIDs); var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0; var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; ("production" !== "development" ? invariant( idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.' ) : invariant(idsIsArr === listenersIsArr && IDsLen === listenersLen)); }; } /** * Invokes `cb(event, listener, id)`. Avoids using call if no scope is * provided. The `(listener,id)` pair effectively forms the "dispatch" but are * kept separate to conserve memory. */ function forEachEventDispatch(event, cb) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== "development") { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. cb(event, dispatchListeners[i], dispatchIDs[i]); } } else if (dispatchListeners) { cb(event, dispatchListeners, dispatchIDs); } } /** * Default implementation of PluginModule.executeDispatch(). * @param {SyntheticEvent} SyntheticEvent to handle * @param {function} Application-level callback * @param {string} domID DOM id to pass to the callback. */ function executeDispatch(event, listener, domID) { event.currentTarget = injection.Mount.getNode(domID); var returnValue = listener(event, domID); event.currentTarget = null; return returnValue; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, cb) { forEachEventDispatch(event, cb); event._dispatchListeners = null; event._dispatchIDs = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return id of the first dispatch execution who's listener returns true, or * null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== "development") { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchIDs[i])) { return dispatchIDs[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchIDs)) { return dispatchIDs; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchIDs = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if ("production" !== "development") { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchID = event._dispatchIDs; ("production" !== "development" ? invariant( !Array.isArray(dispatchListener), 'executeDirectDispatch(...): Invalid `event`.' ) : invariant(!Array.isArray(dispatchListener))); var res = dispatchListener ? dispatchListener(event, dispatchID) : null; event._dispatchListeners = null; event._dispatchIDs = null; return res; } /** * @param {SyntheticEvent} event * @return {bool} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatch: executeDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, injection: injection, useTouchEvents: false }; module.exports = EventPluginUtils; },{"150":150,"16":16}],21:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPropagators */ 'use strict'; var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(18); var accumulateInto = _dereq_(118); var forEachAccumulated = _dereq_(135); var PropagationPhases = EventConstants.PropagationPhases; var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(id, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(id, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(domID, upwards, event) { if ("production" !== "development") { if (!domID) { throw new Error('Dispatching id must not be null'); } } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(domID, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, domID); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We can not perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginHub.injection.getInstanceHandle().traverseTwoPhase( event.dispatchMarker, accumulateDirectionalDispatches, event ); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(id, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(id, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, id); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event.dispatchMarker, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) { EventPluginHub.injection.getInstanceHandle().traverseEnterLeave( fromID, toID, accumulateDispatches, leave, enter ); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; },{"118":118,"135":135,"16":16,"18":18}],22:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ /*jslint evil: true */ "use strict"; var canUseDOM = !!( (typeof window !== 'undefined' && window.document && window.document.createElement) ); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],23:[function(_dereq_,module,exports){ /** * Copyright 2013-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 FallbackCompositionState * @typechecks static-only */ 'use strict'; var PooledClass = _dereq_(30); var assign = _dereq_(29); var getTextContentAccessor = _dereq_(145); /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } assign(FallbackCompositionState.prototype, { /** * Get current text of input. * * @return {string} */ getText: function() { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function() { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; },{"145":145,"29":29,"30":30}],24:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule HTMLDOMPropertyConfig */ /*jslint bitwise: true*/ 'use strict'; var DOMProperty = _dereq_(11); var ExecutionEnvironment = _dereq_(22); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var hasSVG; if (ExecutionEnvironment.canUseDOM) { var implementation = document.implementation; hasSVG = ( implementation && implementation.hasFeature && implementation.hasFeature( 'http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1' ) ); } var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind( /^(data|aria)-[a-z_][a-z\d_.\-]*$/ ), Properties: { /** * Standard Properties */ accept: null, acceptCharset: null, accessKey: null, action: null, allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, allowTransparency: MUST_USE_ATTRIBUTE, alt: null, async: HAS_BOOLEAN_VALUE, autoComplete: null, // autoFocus is polyfilled/normalized by AutoFocusMixin // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, cellPadding: null, cellSpacing: null, charSet: MUST_USE_ATTRIBUTE, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, classID: MUST_USE_ATTRIBUTE, // To set className on SVG elements, it's necessary to use .setAttribute; // this works on HTML elements too in all browsers except IE8. Conveniently, // IE8 doesn't support SVG and so we can simply use the attribute in // browsers that support SVG and the property in browsers that don't, // regardless of whether the element is HTML or SVG. className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY, cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, colSpan: null, content: null, contentEditable: null, contextMenu: MUST_USE_ATTRIBUTE, controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, coords: null, crossOrigin: null, data: null, // For `<object />` acts as `src`. dateTime: MUST_USE_ATTRIBUTE, defer: HAS_BOOLEAN_VALUE, dir: null, disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: null, encType: null, form: MUST_USE_ATTRIBUTE, formAction: MUST_USE_ATTRIBUTE, formEncType: MUST_USE_ATTRIBUTE, formMethod: MUST_USE_ATTRIBUTE, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: MUST_USE_ATTRIBUTE, frameBorder: MUST_USE_ATTRIBUTE, headers: null, height: MUST_USE_ATTRIBUTE, hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, high: null, href: null, hrefLang: null, htmlFor: null, httpEquiv: null, icon: null, id: MUST_USE_PROPERTY, label: null, lang: null, list: MUST_USE_ATTRIBUTE, loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, low: null, manifest: MUST_USE_ATTRIBUTE, marginHeight: null, marginWidth: null, max: null, maxLength: MUST_USE_ATTRIBUTE, media: MUST_USE_ATTRIBUTE, mediaGroup: null, method: null, min: null, multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: null, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: null, pattern: null, placeholder: null, poster: null, preload: null, radioGroup: null, readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, rel: null, required: HAS_BOOLEAN_VALUE, role: MUST_USE_ATTRIBUTE, rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, rowSpan: null, sandbox: null, scope: null, scoped: HAS_BOOLEAN_VALUE, scrolling: null, seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: null, size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, sizes: MUST_USE_ATTRIBUTE, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: null, src: null, srcDoc: MUST_USE_PROPERTY, srcSet: MUST_USE_ATTRIBUTE, start: HAS_NUMERIC_VALUE, step: null, style: null, tabIndex: null, target: null, title: null, type: null, useMap: null, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: MUST_USE_ATTRIBUTE, wmode: MUST_USE_ATTRIBUTE, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: null, autoCorrect: null, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: MUST_USE_ATTRIBUTE, itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, itemType: MUST_USE_ATTRIBUTE, // itemID and itemRef are for Microdata support as well but // only specified in the the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: MUST_USE_ATTRIBUTE, itemRef: MUST_USE_ATTRIBUTE, // property is supported for OpenGraph in meta tags. property: null, // IE-only attribute that controls focus behavior unselectable: MUST_USE_ATTRIBUTE }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: { autoCapitalize: 'autocapitalize', autoComplete: 'autocomplete', autoCorrect: 'autocorrect', autoFocus: 'autofocus', autoPlay: 'autoplay', // `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter. // http://www.w3.org/TR/html5/forms.html#dom-fs-encoding encType: 'encoding', hrefLang: 'hreflang', radioGroup: 'radiogroup', spellCheck: 'spellcheck', srcDoc: 'srcdoc', srcSet: 'srcset' } }; module.exports = HTMLDOMPropertyConfig; },{"11":11,"22":22}],25:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedStateMixin * @typechecks static-only */ 'use strict'; var ReactLink = _dereq_(75); var ReactStateSetters = _dereq_(94); /** * A simple mixin around ReactLink.forState(). */ var LinkedStateMixin = { /** * Create a ReactLink that's linked to part of this component's state. The * ReactLink will have the current value of this.state[key] and will call * setState() when a change is requested. * * @param {string} key state key to update. Note: you may want to use keyOf() * if you're using Google Closure Compiler advanced mode. * @return {ReactLink} ReactLink instance linking to the state. */ linkState: function(key) { return new ReactLink( this.state[key], ReactStateSetters.createStateKeySetter(this, key) ); } }; module.exports = LinkedStateMixin; },{"75":75,"94":94}],26:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedValueUtils * @typechecks static-only */ 'use strict'; var ReactPropTypes = _dereq_(86); var invariant = _dereq_(150); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(input) { ("production" !== "development" ? invariant( input.props.checkedLink == null || input.props.valueLink == null, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.' ) : invariant(input.props.checkedLink == null || input.props.valueLink == null)); } function _assertValueLink(input) { _assertSingleLink(input); ("production" !== "development" ? invariant( input.props.value == null && input.props.onChange == null, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.' ) : invariant(input.props.value == null && input.props.onChange == null)); } function _assertCheckedLink(input) { _assertSingleLink(input); ("production" !== "development" ? invariant( input.props.checked == null && input.props.onChange == null, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink' ) : invariant(input.props.checked == null && input.props.onChange == null)); } /** * @param {SyntheticEvent} e change event to handle */ function _handleLinkedValueChange(e) { /*jshint validthis:true */ this.props.valueLink.requestChange(e.target.value); } /** * @param {SyntheticEvent} e change event to handle */ function _handleLinkedCheckChange(e) { /*jshint validthis:true */ this.props.checkedLink.requestChange(e.target.checked); } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { Mixin: { propTypes: { value: function(props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error( 'You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.' ); }, checked: function(props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error( 'You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.' ); }, onChange: ReactPropTypes.func } }, /** * @param {ReactComponent} input Form component * @return {*} current value of the input either from value prop or link. */ getValue: function(input) { if (input.props.valueLink) { _assertValueLink(input); return input.props.valueLink.value; } return input.props.value; }, /** * @param {ReactComponent} input Form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function(input) { if (input.props.checkedLink) { _assertCheckedLink(input); return input.props.checkedLink.value; } return input.props.checked; }, /** * @param {ReactComponent} input Form component * @return {function} change callback either from onChange prop or link. */ getOnChange: function(input) { if (input.props.valueLink) { _assertValueLink(input); return _handleLinkedValueChange; } else if (input.props.checkedLink) { _assertCheckedLink(input); return _handleLinkedCheckChange; } return input.props.onChange; } }; module.exports = LinkedValueUtils; },{"150":150,"86":86}],27:[function(_dereq_,module,exports){ /** * 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 LocalEventTrapMixin */ 'use strict'; var ReactBrowserEventEmitter = _dereq_(33); var accumulateInto = _dereq_(118); var forEachAccumulated = _dereq_(135); var invariant = _dereq_(150); function remove(event) { event.remove(); } var LocalEventTrapMixin = { trapBubbledEvent:function(topLevelType, handlerBaseName) { ("production" !== "development" ? invariant(this.isMounted(), 'Must be mounted to trap events') : invariant(this.isMounted())); // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. var node = this.getDOMNode(); ("production" !== "development" ? invariant( node, 'LocalEventTrapMixin.trapBubbledEvent(...): Requires node to be rendered.' ) : invariant(node)); var listener = ReactBrowserEventEmitter.trapBubbledEvent( topLevelType, handlerBaseName, node ); this._localEventListeners = accumulateInto(this._localEventListeners, listener); }, // trapCapturedEvent would look nearly identical. We don't implement that // method because it isn't currently needed. componentWillUnmount:function() { if (this._localEventListeners) { forEachAccumulated(this._localEventListeners, remove); } } }; module.exports = LocalEventTrapMixin; },{"118":118,"135":135,"150":150,"33":33}],28:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule MobileSafariClickEventPlugin * @typechecks static-only */ 'use strict'; var EventConstants = _dereq_(16); var emptyFunction = _dereq_(129); var topLevelTypes = EventConstants.topLevelTypes; /** * Mobile Safari does not fire properly bubble click events on non-interactive * elements, which means delegated click listeners do not fire. The workaround * for this bug involves attaching an empty click listener on the target node. * * This particular plugin works around the bug by attaching an empty click * listener on `touchstart` (which does fire on every element). */ var MobileSafariClickEventPlugin = { eventTypes: null, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { if (topLevelType === topLevelTypes.topTouchStart) { var target = nativeEvent.target; if (target && !target.onclick) { target.onclick = emptyFunction; } } } }; module.exports = MobileSafariClickEventPlugin; },{"129":129,"16":16}],29:[function(_dereq_,module,exports){ /** * 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 Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; },{}],30:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PooledClass */ 'use strict'; var invariant = _dereq_(150); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function(copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function(a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function(a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fiveArgumentPooler = function(a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function(instance) { var Klass = this; ("production" !== "development" ? invariant( instance instanceof Klass, 'Trying to release an instance into a pool of a different type.' ) : invariant(instance instanceof Klass)); if (instance.destructor) { instance.destructor(); } if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances (optional). * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function(CopyConstructor, pooler) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; },{"150":150}],31:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule React */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var EventPluginUtils = _dereq_(20); var ReactChildren = _dereq_(37); var ReactComponent = _dereq_(39); var ReactClass = _dereq_(38); var ReactContext = _dereq_(44); var ReactCurrentOwner = _dereq_(45); var ReactElement = _dereq_(63); var ReactElementValidator = _dereq_(64); var ReactDOM = _dereq_(46); var ReactDOMTextComponent = _dereq_(57); var ReactDefaultInjection = _dereq_(60); var ReactInstanceHandles = _dereq_(72); var ReactMount = _dereq_(77); var ReactPerf = _dereq_(82); var ReactPropTypes = _dereq_(86); var ReactReconciler = _dereq_(89); var ReactServerRendering = _dereq_(92); var assign = _dereq_(29); var findDOMNode = _dereq_(132); var onlyChild = _dereq_(160); ReactDefaultInjection.inject(); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if ("production" !== "development") { createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var render = ReactPerf.measure('React', 'render', ReactMount.render); var React = { Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, only: onlyChild }, Component: ReactComponent, DOM: ReactDOM, PropTypes: ReactPropTypes, initializeTouchEvents: function(shouldUseTouch) { EventPluginUtils.useTouchEvents = shouldUseTouch; }, createClass: ReactClass.createClass, createElement: createElement, cloneElement: cloneElement, createFactory: createFactory, createMixin: function(mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, constructAndRenderComponent: ReactMount.constructAndRenderComponent, constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID, findDOMNode: findDOMNode, render: render, renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, unmountComponentAtNode: ReactMount.unmountComponentAtNode, isValidElement: ReactElement.isValidElement, withContext: ReactContext.withContext, // Hook for JSX spread, don't use this for anything else. __spread: assign }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ CurrentOwner: ReactCurrentOwner, InstanceHandles: ReactInstanceHandles, Mount: ReactMount, Reconciler: ReactReconciler, TextComponent: ReactDOMTextComponent }); } if ("production" !== "development") { var ExecutionEnvironment = _dereq_(22); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // If we're in Chrome, look for the devtools marker and provide a download // link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1) { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { console.debug( 'Download the React DevTools for a better development experience: ' + 'https://fb.me/react-devtools' ); } } var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim, // shams Object.create, Object.freeze ]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { console.error( 'One or more ES5 shim/shams expected by React are not available: ' + 'https://fb.me/react-warning-polyfills' ); break; } } } } React.version = '0.13.3'; module.exports = React; },{"132":132,"160":160,"20":20,"22":22,"29":29,"37":37,"38":38,"39":39,"44":44,"45":45,"46":46,"57":57,"60":60,"63":63,"64":64,"72":72,"77":77,"82":82,"86":86,"89":89,"92":92}],32:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserComponentMixin */ 'use strict'; var findDOMNode = _dereq_(132); var ReactBrowserComponentMixin = { /** * Returns the DOM node rendered by this component. * * @return {DOMElement} The root node of this component. * @final * @protected */ getDOMNode: function() { return findDOMNode(this); } }; module.exports = ReactBrowserComponentMixin; },{"132":132}],33:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserEventEmitter * @typechecks static-only */ 'use strict'; var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(18); var EventPluginRegistry = _dereq_(19); var ReactEventEmitterMixin = _dereq_(67); var ViewportMetrics = _dereq_(117); var assign = _dereq_(29); var isEventSupported = _dereq_(151); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topBlur: 'blur', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topScroll: 'scroll', topSelectionChange: 'selectionchange', topTextInput: 'textInput', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function(ReactEventListener) { ReactEventListener.setHandleTopLevel( ReactBrowserEventEmitter.handleTopLevel ); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return !!( (ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()) ); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function(registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry. registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0, l = dependencies.length; i < l; i++) { var dependency = dependencies[i]; if (!( (isListening.hasOwnProperty(dependency) && isListening[dependency]) )) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'wheel', mountAt ); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'mousewheel', mountAt ); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'DOMMouseScroll', mountAt ); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topScroll, 'scroll', mountAt ); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE ); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topFocus, 'focus', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topBlur, 'blur', mountAt ); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topFocus, 'focusin', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topBlur, 'focusout', mountAt ); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( dependency, topEventMapping[dependency], mountAt ); } isListening[dependency] = true; } } }, trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelType, handlerBaseName, handle ); }, trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelType, handlerBaseName, handle ); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function() { if (!isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners }); module.exports = ReactBrowserEventEmitter; },{"117":117,"151":151,"16":16,"18":18,"19":19,"29":29,"67":67}],34:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * @providesModule ReactCSSTransitionGroup */ 'use strict'; var React = _dereq_(31); var assign = _dereq_(29); var ReactTransitionGroup = React.createFactory( _dereq_(98) ); var ReactCSSTransitionGroupChild = React.createFactory( _dereq_(35) ); var ReactCSSTransitionGroup = React.createClass({ displayName: 'ReactCSSTransitionGroup', propTypes: { transitionName: React.PropTypes.string.isRequired, transitionAppear: React.PropTypes.bool, transitionEnter: React.PropTypes.bool, transitionLeave: React.PropTypes.bool }, getDefaultProps: function() { return { transitionAppear: false, transitionEnter: true, transitionLeave: true }; }, _wrapChild: function(child) { // We need to provide this childFactory so that // ReactCSSTransitionGroupChild can receive updates to name, enter, and // leave while it is leaving. return ReactCSSTransitionGroupChild( { name: this.props.transitionName, appear: this.props.transitionAppear, enter: this.props.transitionEnter, leave: this.props.transitionLeave }, child ); }, render: function() { return ( ReactTransitionGroup( assign({}, this.props, {childFactory: this._wrapChild}) ) ); } }); module.exports = ReactCSSTransitionGroup; },{"29":29,"31":31,"35":35,"98":98}],35:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * @providesModule ReactCSSTransitionGroupChild */ 'use strict'; var React = _dereq_(31); var CSSCore = _dereq_(4); var ReactTransitionEvents = _dereq_(97); var onlyChild = _dereq_(160); var warning = _dereq_(171); // We don't remove the element from the DOM until we receive an animationend or // transitionend event. If the user screws up and forgets to add an animation // their node will be stuck in the DOM forever, so we detect if an animation // does not start and if it doesn't, we just call the end listener immediately. var TICK = 17; var NO_EVENT_TIMEOUT = 5000; var noEventListener = null; if ("production" !== "development") { noEventListener = function() { ("production" !== "development" ? warning( false, 'transition(): tried to perform an animation without ' + 'an animationend or transitionend event after timeout (' + '%sms). You should either disable this ' + 'transition in JS or add a CSS animation/transition.', NO_EVENT_TIMEOUT ) : null); }; } var ReactCSSTransitionGroupChild = React.createClass({ displayName: 'ReactCSSTransitionGroupChild', transition: function(animationType, finishCallback) { var node = this.getDOMNode(); var className = this.props.name + '-' + animationType; var activeClassName = className + '-active'; var noEventTimeout = null; var endListener = function(e) { if (e && e.target !== node) { return; } if ("production" !== "development") { clearTimeout(noEventTimeout); } CSSCore.removeClass(node, className); CSSCore.removeClass(node, activeClassName); ReactTransitionEvents.removeEndEventListener(node, endListener); // Usually this optional callback is used for informing an owner of // a leave animation and telling it to remove the child. if (finishCallback) { finishCallback(); } }; ReactTransitionEvents.addEndEventListener(node, endListener); CSSCore.addClass(node, className); // Need to do this to actually trigger a transition. this.queueClass(activeClassName); if ("production" !== "development") { noEventTimeout = setTimeout(noEventListener, NO_EVENT_TIMEOUT); } }, queueClass: function(className) { this.classNameQueue.push(className); if (!this.timeout) { this.timeout = setTimeout(this.flushClassNameQueue, TICK); } }, flushClassNameQueue: function() { if (this.isMounted()) { this.classNameQueue.forEach( CSSCore.addClass.bind(CSSCore, this.getDOMNode()) ); } this.classNameQueue.length = 0; this.timeout = null; }, componentWillMount: function() { this.classNameQueue = []; }, componentWillUnmount: function() { if (this.timeout) { clearTimeout(this.timeout); } }, componentWillAppear: function(done) { if (this.props.appear) { this.transition('appear', done); } else { done(); } }, componentWillEnter: function(done) { if (this.props.enter) { this.transition('enter', done); } else { done(); } }, componentWillLeave: function(done) { if (this.props.leave) { this.transition('leave', done); } else { done(); } }, render: function() { return onlyChild(this.props.children); } }); module.exports = ReactCSSTransitionGroupChild; },{"160":160,"171":171,"31":31,"4":4,"97":97}],36:[function(_dereq_,module,exports){ /** * 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 ReactChildReconciler * @typechecks static-only */ 'use strict'; var ReactReconciler = _dereq_(89); var flattenChildren = _dereq_(133); var instantiateReactComponent = _dereq_(149); var shouldUpdateReactComponent = _dereq_(167); /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function(nestedChildNodes, transaction, context) { var children = flattenChildren(nestedChildNodes); for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; // The rendered children must be turned into instances as they're // mounted. var childInstance = instantiateReactComponent(child, null); children[name] = childInstance; } } return children; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextNestedChildNodes Nested child maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function( prevChildren, nextNestedChildNodes, transaction, context) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. var nextChildren = flattenChildren(nextNestedChildNodes); if (!nextChildren && !prevChildren) { return null; } var name; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent( prevChild, nextElement, transaction, context ); nextChildren[name] = prevChild; } else { if (prevChild) { ReactReconciler.unmountComponent(prevChild, name); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent( nextElement, null ); nextChildren[name] = nextChildInstance; } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { ReactReconciler.unmountComponent(prevChildren[name]); } } return nextChildren; }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function(renderedChildren) { for (var name in renderedChildren) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild); } } }; module.exports = ReactChildReconciler; },{"133":133,"149":149,"167":167,"89":89}],37:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildren */ 'use strict'; var PooledClass = _dereq_(30); var ReactFragment = _dereq_(69); var traverseAllChildren = _dereq_(169); var warning = _dereq_(171); var twoArgumentPooler = PooledClass.twoArgumentPooler; var threeArgumentPooler = PooledClass.threeArgumentPooler; /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.forEachFunction = forEachFunction; this.forEachContext = forEachContext; } PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(traverseContext, child, name, i) { var forEachBookKeeping = traverseContext; forEachBookKeeping.forEachFunction.call( forEachBookKeeping.forEachContext, child, i); } /** * Iterates through children that are typically specified as `props.children`. * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, mapFunction, mapContext) { this.mapResult = mapResult; this.mapFunction = mapFunction; this.mapContext = mapContext; } PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler); function mapSingleChildIntoContext(traverseContext, child, name, i) { var mapBookKeeping = traverseContext; var mapResult = mapBookKeeping.mapResult; var keyUnique = !mapResult.hasOwnProperty(name); if ("production" !== "development") { ("production" !== "development" ? warning( keyUnique, 'ReactChildren.map(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name ) : null); } if (keyUnique) { var mappedChild = mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i); mapResult[name] = mappedChild; } } /** * Maps children that are typically specified as `props.children`. * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * TODO: This may likely break any calls to `ReactChildren.map` that were * previously relying on the fact that we guarded against null children. * * @param {?*} children Children tree container. * @param {function(*, int)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var mapResult = {}; var traverseContext = MapBookKeeping.getPooled(mapResult, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); return ReactFragment.create(mapResult); } function forEachSingleChildDummy(traverseContext, child, name, i) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } var ReactChildren = { forEach: forEachChildren, map: mapChildren, count: countChildren }; module.exports = ReactChildren; },{"169":169,"171":171,"30":30,"69":69}],38:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactClass */ 'use strict'; var ReactComponent = _dereq_(39); var ReactCurrentOwner = _dereq_(45); var ReactElement = _dereq_(63); var ReactErrorUtils = _dereq_(66); var ReactInstanceMap = _dereq_(73); var ReactLifeCycle = _dereq_(74); var ReactPropTypeLocations = _dereq_(85); var ReactPropTypeLocationNames = _dereq_(84); var ReactUpdateQueue = _dereq_(99); var assign = _dereq_(29); var invariant = _dereq_(150); var keyMirror = _dereq_(156); var keyOf = _dereq_(157); var warning = _dereq_(171); var MIXINS_KEY = keyOf({mixins: null}); /** * Policies that describe methods in `ReactClassInterface`. */ var SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }); var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or native components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function(Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function(Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function(Constructor, childContextTypes) { if ("production" !== "development") { validateTypeDef( Constructor, childContextTypes, ReactPropTypeLocations.childContext ); } Constructor.childContextTypes = assign( {}, Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(Constructor, contextTypes) { if ("production" !== "development") { validateTypeDef( Constructor, contextTypes, ReactPropTypeLocations.context ); } Constructor.contextTypes = assign( {}, Constructor.contextTypes, contextTypes ); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function(Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction( Constructor.getDefaultProps, getDefaultProps ); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function(Constructor, propTypes) { if ("production" !== "development") { validateTypeDef( Constructor, propTypes, ReactPropTypeLocations.prop ); } Constructor.propTypes = assign( {}, Constructor.propTypes, propTypes ); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); } }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but not in __DEV__ ("production" !== "development" ? warning( typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName ) : null); } } } function validateMethodOverride(proto, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { ("production" !== "development" ? invariant( specPolicy === SpecPolicy.OVERRIDE_BASE, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE)); } // Disallow defining methods more than once unless explicitly allowed. if (proto.hasOwnProperty(name)) { ("production" !== "development" ? invariant( specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ) : invariant(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED)); } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classses. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { return; } ("production" !== "development" ? invariant( typeof spec !== 'function', 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.' ) : invariant(typeof spec !== 'function')); ("production" !== "development" ? invariant( !ReactElement.isValidElement(spec), 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.' ) : invariant(!ReactElement.isValidElement(spec))); var proto = Constructor.prototype; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above continue; } var property = spec[name]; validateMethodOverride(proto, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isAlreadyDefined = proto.hasOwnProperty(name); var markedDontBind = property && property.__reactDontBind; var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && !markedDontBind; if (shouldAutoBind) { if (!proto.__reactAutoBindMap) { proto.__reactAutoBindMap = {}; } proto.__reactAutoBindMap[name] = property; proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride ("production" !== "development" ? invariant( isReactClassMethod && ( (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY) ), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ) : invariant(isReactClassMethod && ( (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY) ))); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === SpecPolicy.DEFINE_MANY) { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if ("production" !== "development") { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; ("production" !== "development" ? invariant( !isReserved, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name ) : invariant(!isReserved)); var isInherited = name in Constructor; ("production" !== "development" ? invariant( !isInherited, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name ) : invariant(!isInherited)); Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { ("production" !== "development" ? invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.' ) : invariant(one && two && typeof one === 'object' && typeof two === 'object')); for (var key in two) { if (two.hasOwnProperty(key)) { ("production" !== "development" ? invariant( one[key] === undefined, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ) : invariant(one[key] === undefined)); one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if ("production" !== "development") { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; /* eslint-disable block-scoped-var, no-undef */ boundMethod.bind = function(newThis ) {for (var args=[],$__0=1,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { ("production" !== "development" ? warning( false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName ) : null); } else if (!args.length) { ("production" !== "development" ? warning( false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName ) : null); return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; /* eslint-enable */ }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { for (var autoBindKey in component.__reactAutoBindMap) { if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { var method = component.__reactAutoBindMap[autoBindKey]; component[autoBindKey] = bindAutoBindMethod( component, ReactErrorUtils.guard( method, component.constructor.displayName + '.' + autoBindKey ) ); } } } var typeDeprecationDescriptor = { enumerable: false, get: function() { var displayName = this.displayName || this.name || 'Component'; ("production" !== "development" ? warning( false, '%s.type is deprecated. Use %s directly to access the class.', displayName, displayName ) : null); Object.defineProperty(this, 'type', { value: this }); return this; } }; /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function(newState, callback) { ReactUpdateQueue.enqueueReplaceState(this, newState); if (callback) { ReactUpdateQueue.enqueueCallback(this, callback); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { if ("production" !== "development") { var owner = ReactCurrentOwner.current; if (owner !== null) { ("production" !== "development" ? warning( owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component' ) : null); owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(this); return ( internalInstance && internalInstance !== ReactLifeCycle.currentlyMountingInstance ); }, /** * Sets a subset of the props. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public * @deprecated */ setProps: function(partialProps, callback) { ReactUpdateQueue.enqueueSetProps(this, partialProps); if (callback) { ReactUpdateQueue.enqueueCallback(this, callback); } }, /** * Replace all the props. * * @param {object} newProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public * @deprecated */ replaceProps: function(newProps, callback) { ReactUpdateQueue.enqueueReplaceProps(this, newProps); if (callback) { ReactUpdateQueue.enqueueCallback(this, callback); } } }; var ReactClassComponent = function() {}; assign( ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin ); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function(spec) { var Constructor = function(props, context) { // This constructor is overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if ("production" !== "development") { ("production" !== "development" ? warning( this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory' ) : null); } // Wire up auto-binding if (this.__reactAutoBindMap) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if ("production" !== "development") { // We allow auto-mocks to proceed as if they're returning null. if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } ("production" !== "development" ? invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent' ) : invariant(typeof initialState === 'object' && !Array.isArray(initialState))); this.state = initialState; }; Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; injectedMixins.forEach( mixSpecIntoComponent.bind(null, Constructor) ); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if ("production" !== "development") { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } ("production" !== "development" ? invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ) : invariant(Constructor.prototype.render)); if ("production" !== "development") { ("production" !== "development" ? warning( !Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component' ) : null); } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } // Legacy hook Constructor.type = Constructor; if ("production" !== "development") { try { Object.defineProperty(Constructor, 'type', typeDeprecationDescriptor); } catch (x) { // IE will fail on defineProperty (es5-shim/sham too) } } return Constructor; }, injection: { injectMixin: function(mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; },{"150":150,"156":156,"157":157,"171":171,"29":29,"39":39,"45":45,"63":63,"66":66,"73":73,"74":74,"84":84,"85":85,"99":99}],39:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponent */ 'use strict'; var ReactUpdateQueue = _dereq_(99); var invariant = _dereq_(150); var warning = _dereq_(171); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context) { this.props = props; this.context = context; } /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function(partialState, callback) { ("production" !== "development" ? invariant( typeof partialState === 'object' || typeof partialState === 'function' || partialState == null, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.' ) : invariant(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)); if ("production" !== "development") { ("production" !== "development" ? warning( partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().' ) : null); } ReactUpdateQueue.enqueueSetState(this, partialState); if (callback) { ReactUpdateQueue.enqueueCallback(this, callback); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function(callback) { ReactUpdateQueue.enqueueForceUpdate(this); if (callback) { ReactUpdateQueue.enqueueCallback(this, callback); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if ("production" !== "development") { var deprecatedAPIs = { getDOMNode: [ 'getDOMNode', 'Use React.findDOMNode(component) instead.' ], isMounted: [ 'isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.' ], replaceProps: [ 'replaceProps', 'Instead call React.render again at the top level.' ], replaceState: [ 'replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).' ], setProps: [ 'setProps', 'Instead call React.render again at the top level.' ] }; var defineDeprecationWarning = function(methodName, info) { try { Object.defineProperty(ReactComponent.prototype, methodName, { get: function() { ("production" !== "development" ? warning( false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1] ) : null); return undefined; } }); } catch (x) { // IE will fail on defineProperty (es5-shim/sham too) } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; },{"150":150,"171":171,"99":99}],40:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentBrowserEnvironment */ /*jslint evil: true */ 'use strict'; var ReactDOMIDOperations = _dereq_(50); var ReactMount = _dereq_(77); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkupByID: ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID, /** * If a particular environment requires that some resources be cleaned up, * specify this in the injected Mixin. In the DOM, we would likely want to * purge any cached node ID lookups. * * @private */ unmountIDFromEnvironment: function(rootNodeID) { ReactMount.purgeID(rootNodeID); } }; module.exports = ReactComponentBrowserEnvironment; },{"50":50,"77":77}],41:[function(_dereq_,module,exports){ /** * 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 ReactComponentEnvironment */ 'use strict'; var invariant = _dereq_(150); var injected = false; var ReactComponentEnvironment = { /** * Optionally injectable environment dependent cleanup hook. (server vs. * browser etc). Example: A browser system caches DOM nodes based on component * ID and must remove that cache entry when this instance is unmounted. */ unmountIDFromEnvironment: null, /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkupByID: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function(environment) { ("production" !== "development" ? invariant( !injected, 'ReactCompositeComponent: injectEnvironment() can only be called once.' ) : invariant(!injected)); ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment; ReactComponentEnvironment.replaceNodeWithMarkupByID = environment.replaceNodeWithMarkupByID; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; },{"150":150}],42:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentWithPureRenderMixin */ 'use strict'; var shallowEqual = _dereq_(166); /** * If your React component's render function is "pure", e.g. it will render the * same result given the same props and state, provide this Mixin for a * considerable performance boost. * * Most React components have pure render functions. * * Example: * * var ReactComponentWithPureRenderMixin = * require('ReactComponentWithPureRenderMixin'); * React.createClass({ * mixins: [ReactComponentWithPureRenderMixin], * * render: function() { * return <div className={this.props.className}>foo</div>; * } * }); * * Note: This only checks shallow equality for props and state. If these contain * complex data structures this mixin may have false-negatives for deeper * differences. Only mixin to components which have simple props and state, or * use `forceUpdate()` when you know deep data structures have changed. */ var ReactComponentWithPureRenderMixin = { shouldComponentUpdate: function(nextProps, nextState) { return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); } }; module.exports = ReactComponentWithPureRenderMixin; },{"166":166}],43:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCompositeComponent */ 'use strict'; var ReactComponentEnvironment = _dereq_(41); var ReactContext = _dereq_(44); var ReactCurrentOwner = _dereq_(45); var ReactElement = _dereq_(63); var ReactElementValidator = _dereq_(64); var ReactInstanceMap = _dereq_(73); var ReactLifeCycle = _dereq_(74); var ReactNativeComponent = _dereq_(80); var ReactPerf = _dereq_(82); var ReactPropTypeLocations = _dereq_(85); var ReactPropTypeLocationNames = _dereq_(84); var ReactReconciler = _dereq_(89); var ReactUpdates = _dereq_(100); var assign = _dereq_(29); var emptyObject = _dereq_(130); var invariant = _dereq_(150); var shouldUpdateReactComponent = _dereq_(167); var warning = _dereq_(171); function getDeclarationErrorAddendum(component) { var owner = component._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function(element) { this._currentElement = element; this._rootNodeID = null; this._instance = null; // See ReactUpdateQueue this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._isTopLevel = false; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function(rootID, transaction, context) { this._context = context; this._mountOrder = nextMountID++; this._rootNodeID = rootID; var publicProps = this._processProps(this._currentElement.props); var publicContext = this._processContext(this._currentElement._context); var Component = ReactNativeComponent.getComponentClassForElement( this._currentElement ); // Initialize the public class var inst = new Component(publicProps, publicContext); if ("production" !== "development") { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging ("production" !== "development" ? warning( inst.render != null, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render` in your ' + 'component or you may have accidentally tried to render an element ' + 'whose type is a function that isn\'t a React component.', Component.displayName || Component.name || 'Component' ) : null); } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if ("production" !== "development") { this._warnIfContextsDiffer(this._currentElement._context, context); } if ("production" !== "development") { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. ("production" !== "development" ? warning( !inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component' ) : null); ("production" !== "development" ? warning( !inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component' ) : null); ("production" !== "development" ? warning( !inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component' ) : null); ("production" !== "development" ? warning( !inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component' ) : null); ("production" !== "development" ? warning( typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', (this.getName() || 'A component') ) : null); } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } ("production" !== "development" ? invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent' ) : invariant(typeof initialState === 'object' && !Array.isArray(initialState))); this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; var childContext; var renderedElement; var previouslyMounting = ReactLifeCycle.currentlyMountingInstance; ReactLifeCycle.currentlyMountingInstance = this; try { if (inst.componentWillMount) { inst.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } childContext = this._getValidatedChildContext(context); renderedElement = this._renderValidatedComponent(childContext); } finally { ReactLifeCycle.currentlyMountingInstance = previouslyMounting; } this._renderedComponent = this._instantiateReactComponent( renderedElement, this._currentElement.type // The wrapping type ); var markup = ReactReconciler.mountComponent( this._renderedComponent, rootID, transaction, this._mergeChildContext(context, childContext) ); if (inst.componentDidMount) { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } return markup; }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function() { var inst = this._instance; if (inst.componentWillUnmount) { var previouslyUnmounting = ReactLifeCycle.currentlyUnmountingInstance; ReactLifeCycle.currentlyUnmountingInstance = this; try { inst.componentWillUnmount(); } finally { ReactLifeCycle.currentlyUnmountingInstance = previouslyUnmounting; } } ReactReconciler.unmountComponent(this._renderedComponent); this._renderedComponent = null; // Reset pending fields this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Schedule a partial update to the props. Only used for internal testing. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @internal */ _setPropsInternal: function(partialProps, callback) { // This is a deoptimized path. We optimize for always having an element. // This creates an extra internal element. var element = this._pendingElement || this._currentElement; this._pendingElement = ReactElement.cloneAndReplaceProps( element, assign({}, element.props, partialProps) ); ReactUpdates.enqueueUpdate(this, callback); }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function(context) { var maskedContext = null; // This really should be getting the component class for the element, // but we know that we're not going to need it for built-ins. if (typeof this._currentElement.type === 'string') { return emptyObject; } var contextTypes = this._currentElement.type.contextTypes; if (!contextTypes) { return emptyObject; } maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function(context) { var maskedContext = this._maskContext(context); if ("production" !== "development") { var Component = ReactNativeComponent.getComponentClassForElement( this._currentElement ); if (Component.contextTypes) { this._checkPropTypes( Component.contextTypes, maskedContext, ReactPropTypeLocations.context ); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _getValidatedChildContext: function(currentContext) { var inst = this._instance; var childContext = inst.getChildContext && inst.getChildContext(); if (childContext) { ("production" !== "development" ? invariant( typeof inst.constructor.childContextTypes === 'object', '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent' ) : invariant(typeof inst.constructor.childContextTypes === 'object')); if ("production" !== "development") { this._checkPropTypes( inst.constructor.childContextTypes, childContext, ReactPropTypeLocations.childContext ); } for (var name in childContext) { ("production" !== "development" ? invariant( name in inst.constructor.childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name ) : invariant(name in inst.constructor.childContextTypes)); } return childContext; } return null; }, _mergeChildContext: function(currentContext, childContext) { if (childContext) { return assign({}, currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function(newProps) { if ("production" !== "development") { var Component = ReactNativeComponent.getComponentClassForElement( this._currentElement ); if (Component.propTypes) { this._checkPropTypes( Component.propTypes, newProps, ReactPropTypeLocations.prop ); } } return newProps; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function(propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.getName(); for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. ("production" !== "development" ? invariant( typeof propTypes[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName ) : invariant(typeof propTypes[propName] === 'function')); error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error) { // We may want to extend this logic for similar errors in // React.render calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); if (location === ReactPropTypeLocations.prop) { // Preface gives us something to blacklist in warning module ("production" !== "development" ? warning( false, 'Failed Composite propType: %s%s', error.message, addendum ) : null); } else { ("production" !== "development" ? warning( false, 'Failed Context Types: %s%s', error.message, addendum ) : null); } } } } }, receiveComponent: function(nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent( transaction, prevElement, nextElement, prevContext, nextContext ); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function(transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent( this, this._pendingElement || this._currentElement, transaction, this._context ); } if (this._pendingStateQueue !== null || this._pendingForceUpdate) { if ("production" !== "development") { ReactElementValidator.checkAndWarnForMutatedProps( this._currentElement ); } this.updateComponent( transaction, this._currentElement, this._currentElement, this._context, this._context ); } }, /** * Compare two contexts, warning if they are different * TODO: Remove this check when owner-context is removed */ _warnIfContextsDiffer: function(ownerBasedContext, parentBasedContext) { ownerBasedContext = this._maskContext(ownerBasedContext); parentBasedContext = this._maskContext(parentBasedContext); var parentKeys = Object.keys(parentBasedContext).sort(); var displayName = this.getName() || 'ReactCompositeComponent'; for (var i = 0; i < parentKeys.length; i++) { var key = parentKeys[i]; ("production" !== "development" ? warning( ownerBasedContext[key] === parentBasedContext[key], 'owner-based and parent-based contexts differ ' + '(values: `%s` vs `%s`) for key (%s) while mounting %s ' + '(see: http://fb.me/react-context-by-parent)', ownerBasedContext[key], parentBasedContext[key], key, displayName ) : null); } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function( transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext ) { var inst = this._instance; var nextContext = inst.context; var nextProps = inst.props; // Distinguish between a props update versus a simple state update if (prevParentElement !== nextParentElement) { nextContext = this._processContext(nextParentElement._context); nextProps = this._processProps(nextParentElement.props); if ("production" !== "development") { if (nextUnmaskedContext != null) { this._warnIfContextsDiffer( nextParentElement._context, nextUnmaskedContext ); } } // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (inst.componentWillReceiveProps) { inst.componentWillReceiveProps(nextProps, nextContext); } } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext); if ("production" !== "development") { ("production" !== "development" ? warning( typeof shouldUpdate !== 'undefined', '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent' ) : null); } if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate( nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext ); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } }, _processPendingState: function(props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; assign( nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial ); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function( nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext ) { var inst = this._instance; var prevProps = inst.props; var prevState = inst.state; var prevContext = inst.context; if (inst.componentWillUpdate) { inst.componentWillUpdate(nextProps, nextState, nextContext); } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (inst.componentDidUpdate) { transaction.getReactMountReady().enqueue( inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst ); } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function(transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var childContext = this._getValidatedChildContext(); var nextRenderedElement = this._renderValidatedComponent(childContext); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent( prevComponentInstance, nextRenderedElement, transaction, this._mergeChildContext(context, childContext) ); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponentInstance._rootNodeID; ReactReconciler.unmountComponent(prevComponentInstance); this._renderedComponent = this._instantiateReactComponent( nextRenderedElement, this._currentElement.type ); var nextMarkup = ReactReconciler.mountComponent( this._renderedComponent, thisID, transaction, this._mergeChildContext(context, childContext) ); this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup); } }, /** * @protected */ _replaceNodeWithMarkupByID: function(prevComponentID, nextMarkup) { ReactComponentEnvironment.replaceNodeWithMarkupByID( prevComponentID, nextMarkup ); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function() { var inst = this._instance; var renderedComponent = inst.render(); if ("production" !== "development") { // We allow auto-mocks to proceed as if they're returning null. if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } return renderedComponent; }, /** * @private */ _renderValidatedComponent: function(childContext) { var renderedComponent; var previousContext = ReactContext.current; ReactContext.current = this._mergeChildContext( this._currentElement._context, childContext ); ReactCurrentOwner.current = this; try { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactContext.current = previousContext; ReactCurrentOwner.current = null; } ("production" !== "development" ? invariant( // TODO: An `isValidNode` function would probably be more appropriate renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent), '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent' ) : invariant(// TODO: An `isValidNode` function would probably be more appropriate renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent))); return renderedComponent; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function(ref, component) { var inst = this.getPublicInstance(); var refs = inst.refs === emptyObject ? (inst.refs = {}) : inst.refs; refs[ref] = component.getPublicInstance(); }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function(ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function() { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return ( type.displayName || (constructor && constructor.displayName) || type.name || (constructor && constructor.name) || null ); }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by React.render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function() { return this._instance; }, // Stub _instantiateReactComponent: null }; ReactPerf.measureMethods( ReactCompositeComponentMixin, 'ReactCompositeComponent', { mountComponent: 'mountComponent', updateComponent: 'updateComponent', _renderValidatedComponent: '_renderValidatedComponent' } ); var ReactCompositeComponent = { Mixin: ReactCompositeComponentMixin }; module.exports = ReactCompositeComponent; },{"100":100,"130":130,"150":150,"167":167,"171":171,"29":29,"41":41,"44":44,"45":45,"63":63,"64":64,"73":73,"74":74,"80":80,"82":82,"84":84,"85":85,"89":89}],44:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactContext */ 'use strict'; var assign = _dereq_(29); var emptyObject = _dereq_(130); var warning = _dereq_(171); var didWarn = false; /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: emptyObject, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'}, () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { if ("production" !== "development") { ("production" !== "development" ? warning( didWarn, 'withContext is deprecated and will be removed in a future version. ' + 'Use a wrapper component with getChildContext instead.' ) : null); didWarn = true; } var result; var previousContext = ReactContext.current; ReactContext.current = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; },{"130":130,"171":171,"29":29}],45:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; },{}],46:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOM * @typechecks static-only */ 'use strict'; var ReactElement = _dereq_(63); var ReactElementValidator = _dereq_(64); var mapObject = _dereq_(158); /** * Create a factory that creates HTML tag elements. * * @param {string} tag Tag name (e.g. `div`). * @private */ function createDOMFactory(tag) { if ("production" !== "development") { return ReactElementValidator.createFactory(tag); } return ReactElement.createFactory(tag); } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOM = mapObject({ a: 'a', abbr: 'abbr', address: 'address', area: 'area', article: 'article', aside: 'aside', audio: 'audio', b: 'b', base: 'base', bdi: 'bdi', bdo: 'bdo', big: 'big', blockquote: 'blockquote', body: 'body', br: 'br', button: 'button', canvas: 'canvas', caption: 'caption', cite: 'cite', code: 'code', col: 'col', colgroup: 'colgroup', data: 'data', datalist: 'datalist', dd: 'dd', del: 'del', details: 'details', dfn: 'dfn', dialog: 'dialog', div: 'div', dl: 'dl', dt: 'dt', em: 'em', embed: 'embed', fieldset: 'fieldset', figcaption: 'figcaption', figure: 'figure', footer: 'footer', form: 'form', h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', head: 'head', header: 'header', hr: 'hr', html: 'html', i: 'i', iframe: 'iframe', img: 'img', input: 'input', ins: 'ins', kbd: 'kbd', keygen: 'keygen', label: 'label', legend: 'legend', li: 'li', link: 'link', main: 'main', map: 'map', mark: 'mark', menu: 'menu', menuitem: 'menuitem', meta: 'meta', meter: 'meter', nav: 'nav', noscript: 'noscript', object: 'object', ol: 'ol', optgroup: 'optgroup', option: 'option', output: 'output', p: 'p', param: 'param', picture: 'picture', pre: 'pre', progress: 'progress', q: 'q', rp: 'rp', rt: 'rt', ruby: 'ruby', s: 's', samp: 'samp', script: 'script', section: 'section', select: 'select', small: 'small', source: 'source', span: 'span', strong: 'strong', style: 'style', sub: 'sub', summary: 'summary', sup: 'sup', table: 'table', tbody: 'tbody', td: 'td', textarea: 'textarea', tfoot: 'tfoot', th: 'th', thead: 'thead', time: 'time', title: 'title', tr: 'tr', track: 'track', u: 'u', ul: 'ul', 'var': 'var', video: 'video', wbr: 'wbr', // SVG circle: 'circle', clipPath: 'clipPath', defs: 'defs', ellipse: 'ellipse', g: 'g', line: 'line', linearGradient: 'linearGradient', mask: 'mask', path: 'path', pattern: 'pattern', polygon: 'polygon', polyline: 'polyline', radialGradient: 'radialGradient', rect: 'rect', stop: 'stop', svg: 'svg', text: 'text', tspan: 'tspan' }, createDOMFactory); module.exports = ReactDOM; },{"158":158,"63":63,"64":64}],47:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMButton */ 'use strict'; var AutoFocusMixin = _dereq_(2); var ReactBrowserComponentMixin = _dereq_(32); var ReactClass = _dereq_(38); var ReactElement = _dereq_(63); var keyMirror = _dereq_(156); var button = ReactElement.createFactory('button'); var mouseListenerNames = keyMirror({ onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }); /** * Implements a <button> native component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = ReactClass.createClass({ displayName: 'ReactDOMButton', tagName: 'BUTTON', mixins: [AutoFocusMixin, ReactBrowserComponentMixin], render: function() { var props = {}; // Copy the props; except the mouse listeners if we're disabled for (var key in this.props) { if (this.props.hasOwnProperty(key) && (!this.props.disabled || !mouseListenerNames[key])) { props[key] = this.props[key]; } } return button(props, this.props.children); } }); module.exports = ReactDOMButton; },{"156":156,"2":2,"32":32,"38":38,"63":63}],48:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponent * @typechecks static-only */ /* global hasOwnProperty:true */ 'use strict'; var CSSPropertyOperations = _dereq_(6); var DOMProperty = _dereq_(11); var DOMPropertyOperations = _dereq_(12); var ReactBrowserEventEmitter = _dereq_(33); var ReactComponentBrowserEnvironment = _dereq_(40); var ReactMount = _dereq_(77); var ReactMultiChild = _dereq_(78); var ReactPerf = _dereq_(82); var assign = _dereq_(29); var escapeTextContentForBrowser = _dereq_(131); var invariant = _dereq_(150); var isEventSupported = _dereq_(151); var keyOf = _dereq_(157); var warning = _dereq_(171); var deleteListener = ReactBrowserEventEmitter.deleteListener; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = {'string': true, 'number': true}; var STYLE = keyOf({style: null}); var ELEMENT_NODE_TYPE = 1; /** * Optionally injectable operations for mutating the DOM */ var BackendIDOperations = null; /** * @param {?object} props */ function assertValidProps(props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (props.dangerouslySetInnerHTML != null) { ("production" !== "development" ? invariant( props.children == null, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.' ) : invariant(props.children == null)); ("production" !== "development" ? invariant( typeof props.dangerouslySetInnerHTML === 'object' && '__html' in props.dangerouslySetInnerHTML, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.' ) : invariant(typeof props.dangerouslySetInnerHTML === 'object' && '__html' in props.dangerouslySetInnerHTML)); } if ("production" !== "development") { ("production" !== "development" ? warning( props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.' ) : null); ("production" !== "development" ? warning( !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.' ) : null); } ("production" !== "development" ? invariant( props.style == null || typeof props.style === 'object', 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.' ) : invariant(props.style == null || typeof props.style === 'object')); } function putListener(id, registrationName, listener, transaction) { if ("production" !== "development") { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. ("production" !== "development" ? warning( registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event' ) : null); } var container = ReactMount.findReactContainerForID(id); if (container) { var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container; listenTo(registrationName, doc); } transaction.getPutListenerQueue().enqueuePutListener( id, registrationName, listener ); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special cased tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true // NOTE: menuitem's close tag should be omitted, but that causes problems. }; // We accept any tag to be rendered but since this gets injected into abitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { ("production" !== "development" ? invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag) : invariant(VALID_TAG_REGEX.test(tag))); validatedTagCache[tag] = true; } } /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(tag) { validateDangerousTag(tag); this._tag = tag; this._renderedChildren = null; this._previousStyleCopy = null; this._rootNodeID = null; } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { construct: function(element) { this._currentElement = element; }, /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {string} rootID The root DOM ID for this node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} The computed markup. */ mountComponent: function(rootID, transaction, context) { this._rootNodeID = rootID; assertValidProps(this._currentElement.props); var closeTag = omittedCloseTags[this._tag] ? '' : '</' + this._tag + '>'; return ( this._createOpenTagMarkupAndPutListeners(transaction) + this._createContentMarkup(transaction, context) + closeTag ); }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function(transaction) { var props = this._currentElement.props; var ret = '<' + this._tag; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { putListener(this._rootNodeID, propKey, propValue, transaction); } else { if (propKey === STYLE) { if (propValue) { propValue = this._previousStyleCopy = assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue); } var markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret + '>'; } var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID); return ret + ' ' + markupForID + '>'; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function(transaction, context) { var prefix = ''; if (this._tag === 'listing' || this._tag === 'pre' || this._tag === 'textarea') { // Add an initial newline because browsers ignore the first newline in // a <listing>, <pre>, or <textarea> as an "authoring convenience" -- see // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody. prefix = '\n'; } var props = this._currentElement.props; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { return prefix + innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { return prefix + escapeTextContentForBrowser(contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren( childrenToUse, transaction, context ); return prefix + mountImages.join(''); } } return prefix; }, receiveComponent: function(nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a native DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function(transaction, prevElement, nextElement, context) { assertValidProps(this._currentElement.props); this._updateDOMProperties(prevElement.props, transaction); this._updateDOMChildren(prevElement.props, transaction, context); }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {ReactReconcileTransaction} transaction */ _updateDOMProperties: function(lastProps, transaction) { var nextProps = this._currentElement.props; var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { deleteListener(this._rootNodeID, propKey); } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { BackendIDOperations.deletePropertyByID( this._rootNodeID, propKey ); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps[propKey]; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) { continue; } if (propKey === STYLE) { if (nextProp) { nextProp = this._previousStyleCopy = assign({}, nextProp); } else { this._previousStyleCopy = null; } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { putListener(this._rootNodeID, propKey, nextProp, transaction); } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { BackendIDOperations.updatePropertyByID( this._rootNodeID, propKey, nextProp ); } } if (styleUpdates) { BackendIDOperations.updateStylesByID( this._rootNodeID, styleUpdates ); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {ReactReconcileTransaction} transaction */ _updateDOMChildren: function(lastProps, transaction, context) { var nextProps = this._currentElement.props; var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { BackendIDOperations.updateInnerHTMLByID( this._rootNodeID, nextHtml ); } } else if (nextChildren != null) { this.updateChildren(nextChildren, transaction, context); } }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function() { this.unmountChildren(); ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID); ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); this._rootNodeID = null; } }; ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', { mountComponent: 'mountComponent', updateComponent: 'updateComponent' }); assign( ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin ); ReactDOMComponent.injection = { injectIDOperations: function(IDOperations) { ReactDOMComponent.BackendIDOperations = BackendIDOperations = IDOperations; } }; module.exports = ReactDOMComponent; },{"11":11,"12":12,"131":131,"150":150,"151":151,"157":157,"171":171,"29":29,"33":33,"40":40,"6":6,"77":77,"78":78,"82":82}],49:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMForm */ 'use strict'; var EventConstants = _dereq_(16); var LocalEventTrapMixin = _dereq_(27); var ReactBrowserComponentMixin = _dereq_(32); var ReactClass = _dereq_(38); var ReactElement = _dereq_(63); var form = ReactElement.createFactory('form'); /** * Since onSubmit doesn't bubble OR capture on the top level in IE8, we need * to capture it on the <form> element itself. There are lots of hacks we could * do to accomplish this, but the most reliable is to make <form> a * composite component and use `componentDidMount` to attach the event handlers. */ var ReactDOMForm = ReactClass.createClass({ displayName: 'ReactDOMForm', tagName: 'FORM', mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin], render: function() { // TODO: Instead of using `ReactDOM` directly, we should use JSX. However, // `jshint` fails to parse JSX so in order for linting to work in the open // source repo, we need to just use `ReactDOM.form`. return form(this.props); }, componentDidMount: function() { this.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset'); this.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit'); } }); module.exports = ReactDOMForm; },{"16":16,"27":27,"32":32,"38":38,"63":63}],50:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIDOperations * @typechecks static-only */ /*jslint evil: true */ 'use strict'; var CSSPropertyOperations = _dereq_(6); var DOMChildrenOperations = _dereq_(10); var DOMPropertyOperations = _dereq_(12); var ReactMount = _dereq_(77); var ReactPerf = _dereq_(82); var invariant = _dereq_(150); var setInnerHTML = _dereq_(164); /** * Errors for properties that should not be updated with `updatePropertyById()`. * * @type {object} * @private */ var INVALID_PROPERTY_ERRORS = { dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.', style: '`style` must be set using `updateStylesByID()`.' }; /** * Operations used to process updates to DOM nodes. This is made injectable via * `ReactDOMComponent.BackendIDOperations`. */ var ReactDOMIDOperations = { /** * Updates a DOM node with new property values. This should only be used to * update DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A valid property name, see `DOMProperty`. * @param {*} value New value of the property. * @internal */ updatePropertyByID: function(id, name, value) { var node = ReactMount.getNode(id); ("production" !== "development" ? invariant( !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name] ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name))); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (value != null) { DOMPropertyOperations.setValueForProperty(node, name, value); } else { DOMPropertyOperations.deleteValueForProperty(node, name); } }, /** * Updates a DOM node to remove a property. This should only be used to remove * DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A property name to remove, see `DOMProperty`. * @internal */ deletePropertyByID: function(id, name, value) { var node = ReactMount.getNode(id); ("production" !== "development" ? invariant( !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name] ) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name))); DOMPropertyOperations.deleteValueForProperty(node, name, value); }, /** * Updates a DOM node with new style values. If a value is specified as '', * the corresponding style property will be unset. * * @param {string} id ID of the node to update. * @param {object} styles Mapping from styles to values. * @internal */ updateStylesByID: function(id, styles) { var node = ReactMount.getNode(id); CSSPropertyOperations.setValueForStyles(node, styles); }, /** * Updates a DOM node's innerHTML. * * @param {string} id ID of the node to update. * @param {string} html An HTML string. * @internal */ updateInnerHTMLByID: function(id, html) { var node = ReactMount.getNode(id); setInnerHTML(node, html); }, /** * Updates a DOM node's text content set by `props.content`. * * @param {string} id ID of the node to update. * @param {string} content Text content. * @internal */ updateTextContentByID: function(id, content) { var node = ReactMount.getNode(id); DOMChildrenOperations.updateTextContent(node, content); }, /** * Replaces a DOM node that exists in the document with markup. * * @param {string} id ID of child to be replaced. * @param {string} markup Dangerous markup to inject in place of child. * @internal * @see {Danger.dangerouslyReplaceNodeWithMarkup} */ dangerouslyReplaceNodeWithMarkupByID: function(id, markup) { var node = ReactMount.getNode(id); DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); }, /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markup List of markup strings. * @internal */ dangerouslyProcessChildrenUpdates: function(updates, markup) { for (var i = 0; i < updates.length; i++) { updates[i].parentNode = ReactMount.getNode(updates[i].parentID); } DOMChildrenOperations.processUpdates(updates, markup); } }; ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', { updatePropertyByID: 'updatePropertyByID', deletePropertyByID: 'deletePropertyByID', updateStylesByID: 'updateStylesByID', updateInnerHTMLByID: 'updateInnerHTMLByID', updateTextContentByID: 'updateTextContentByID', dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID', dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates' }); module.exports = ReactDOMIDOperations; },{"10":10,"12":12,"150":150,"164":164,"6":6,"77":77,"82":82}],51:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIframe */ 'use strict'; var EventConstants = _dereq_(16); var LocalEventTrapMixin = _dereq_(27); var ReactBrowserComponentMixin = _dereq_(32); var ReactClass = _dereq_(38); var ReactElement = _dereq_(63); var iframe = ReactElement.createFactory('iframe'); /** * Since onLoad doesn't bubble OR capture on the top level in IE8, we need to * capture it on the <iframe> element itself. There are lots of hacks we could * do to accomplish this, but the most reliable is to make <iframe> a composite * component and use `componentDidMount` to attach the event handlers. */ var ReactDOMIframe = ReactClass.createClass({ displayName: 'ReactDOMIframe', tagName: 'IFRAME', mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin], render: function() { return iframe(this.props); }, componentDidMount: function() { this.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load'); } }); module.exports = ReactDOMIframe; },{"16":16,"27":27,"32":32,"38":38,"63":63}],52:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMImg */ 'use strict'; var EventConstants = _dereq_(16); var LocalEventTrapMixin = _dereq_(27); var ReactBrowserComponentMixin = _dereq_(32); var ReactClass = _dereq_(38); var ReactElement = _dereq_(63); var img = ReactElement.createFactory('img'); /** * Since onLoad doesn't bubble OR capture on the top level in IE8, we need to * capture it on the <img> element itself. There are lots of hacks we could do * to accomplish this, but the most reliable is to make <img> a composite * component and use `componentDidMount` to attach the event handlers. */ var ReactDOMImg = ReactClass.createClass({ displayName: 'ReactDOMImg', tagName: 'IMG', mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin], render: function() { return img(this.props); }, componentDidMount: function() { this.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load'); this.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error'); } }); module.exports = ReactDOMImg; },{"16":16,"27":27,"32":32,"38":38,"63":63}],53:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInput */ 'use strict'; var AutoFocusMixin = _dereq_(2); var DOMPropertyOperations = _dereq_(12); var LinkedValueUtils = _dereq_(26); var ReactBrowserComponentMixin = _dereq_(32); var ReactClass = _dereq_(38); var ReactElement = _dereq_(63); var ReactMount = _dereq_(77); var ReactUpdates = _dereq_(100); var assign = _dereq_(29); var invariant = _dereq_(150); var input = ReactElement.createFactory('input'); var instancesByReactID = {}; function forceUpdateIfMounted() { /*jshint validthis:true */ if (this.isMounted()) { this.forceUpdate(); } } /** * Implements an <input> native component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = ReactClass.createClass({ displayName: 'ReactDOMInput', tagName: 'INPUT', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], getInitialState: function() { var defaultValue = this.props.defaultValue; return { initialChecked: this.props.defaultChecked || false, initialValue: defaultValue != null ? defaultValue : null }; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); props.defaultChecked = null; props.defaultValue = null; var value = LinkedValueUtils.getValue(this); props.value = value != null ? value : this.state.initialValue; var checked = LinkedValueUtils.getChecked(this); props.checked = checked != null ? checked : this.state.initialChecked; props.onChange = this._handleChange; return input(props, this.props.children); }, componentDidMount: function() { var id = ReactMount.getID(this.getDOMNode()); instancesByReactID[id] = this; }, componentWillUnmount: function() { var rootNode = this.getDOMNode(); var id = ReactMount.getID(rootNode); delete instancesByReactID[id]; }, componentDidUpdate: function(prevProps, prevState, prevContext) { var rootNode = this.getDOMNode(); if (this.props.checked != null) { DOMPropertyOperations.setValueForProperty( rootNode, 'checked', this.props.checked || false ); } var value = LinkedValueUtils.getValue(this); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { returnValue = onChange.call(this, event); } // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = this.props.name; if (this.props.type === 'radio' && name != null) { var rootNode = this.getDOMNode(); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll( 'input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0, groupLen = group.length; i < groupLen; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } var otherID = ReactMount.getID(otherNode); ("production" !== "development" ? invariant( otherID, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.' ) : invariant(otherID)); var otherInstance = instancesByReactID[otherID]; ("production" !== "development" ? invariant( otherInstance, 'ReactDOMInput: Unknown radio button ID %s.', otherID ) : invariant(otherInstance)); // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } }); module.exports = ReactDOMInput; },{"100":100,"12":12,"150":150,"2":2,"26":26,"29":29,"32":32,"38":38,"63":63,"77":77}],54:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMOption */ 'use strict'; var ReactBrowserComponentMixin = _dereq_(32); var ReactClass = _dereq_(38); var ReactElement = _dereq_(63); var warning = _dereq_(171); var option = ReactElement.createFactory('option'); /** * Implements an <option> native component that warns when `selected` is set. */ var ReactDOMOption = ReactClass.createClass({ displayName: 'ReactDOMOption', tagName: 'OPTION', mixins: [ReactBrowserComponentMixin], componentWillMount: function() { // TODO (yungsters): Remove support for `selected` in <option>. if ("production" !== "development") { ("production" !== "development" ? warning( this.props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.' ) : null); } }, render: function() { return option(this.props, this.props.children); } }); module.exports = ReactDOMOption; },{"171":171,"32":32,"38":38,"63":63}],55:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelect */ 'use strict'; var AutoFocusMixin = _dereq_(2); var LinkedValueUtils = _dereq_(26); var ReactBrowserComponentMixin = _dereq_(32); var ReactClass = _dereq_(38); var ReactElement = _dereq_(63); var ReactUpdates = _dereq_(100); var assign = _dereq_(29); var select = ReactElement.createFactory('select'); function updateOptionsIfPendingUpdateAndMounted() { /*jshint validthis:true */ if (this._pendingUpdate) { this._pendingUpdate = false; var value = LinkedValueUtils.getValue(this); if (value != null && this.isMounted()) { updateOptions(this, value); } } } /** * Validation function for `value` and `defaultValue`. * @private */ function selectValueType(props, propName, componentName) { if (props[propName] == null) { return null; } if (props.multiple) { if (!Array.isArray(props[propName])) { return new Error( ("The `" + propName + "` prop supplied to <select> must be an array if ") + ("`multiple` is true.") ); } } else { if (Array.isArray(props[propName])) { return new Error( ("The `" + propName + "` prop supplied to <select> must be a scalar ") + ("value if `multiple` is false.") ); } } } /** * @param {ReactComponent} component Instance of ReactDOMSelect * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(component, propValue) { var selectedValue, i, l; var options = component.getDOMNode().options; if (component.props.multiple) { selectedValue = {}; for (i = 0, l = propValue.length; i < l; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0, l = options.length; i < l; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. selectedValue = '' + propValue; for (i = 0, l = options.length; i < l; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> native component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = ReactClass.createClass({ displayName: 'ReactDOMSelect', tagName: 'SELECT', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], propTypes: { defaultValue: selectValueType, value: selectValueType }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); props.onChange = this._handleChange; props.value = null; return select(props, this.props.children); }, componentWillMount: function() { this._pendingUpdate = false; }, componentDidMount: function() { var value = LinkedValueUtils.getValue(this); if (value != null) { updateOptions(this, value); } else if (this.props.defaultValue != null) { updateOptions(this, this.props.defaultValue); } }, componentDidUpdate: function(prevProps) { var value = LinkedValueUtils.getValue(this); if (value != null) { this._pendingUpdate = false; updateOptions(this, value); } else if (!prevProps.multiple !== !this.props.multiple) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (this.props.defaultValue != null) { updateOptions(this, this.props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(this, this.props.multiple ? [] : ''); } } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { returnValue = onChange.call(this, event); } this._pendingUpdate = true; ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } }); module.exports = ReactDOMSelect; },{"100":100,"2":2,"26":26,"29":29,"32":32,"38":38,"63":63}],56:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelection */ 'use strict'; var ExecutionEnvironment = _dereq_(22); var getNodeForCharacterOffset = _dereq_(143); var getTextContentAccessor = _dereq_(145); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed( selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset ); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed( tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset ); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (typeof offsets.end === 'undefined') { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ( ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window) ); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; },{"143":143,"145":145,"22":22}],57:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextComponent * @typechecks static-only */ 'use strict'; var DOMPropertyOperations = _dereq_(12); var ReactComponentBrowserEnvironment = _dereq_(40); var ReactDOMComponent = _dereq_(48); var assign = _dereq_(29); var escapeTextContentForBrowser = _dereq_(131); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings in elements so that they can undergo * the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function(props) { // This constructor and its argument is currently used by mocks. }; assign(ReactDOMTextComponent.prototype, { /** * @param {ReactText} text * @internal */ construct: function(text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // Properties this._rootNodeID = null; this._mountIndex = 0; }, /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function(rootID, transaction, context) { this._rootNodeID = rootID; var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this in a `span` for the reasons stated above, but // since this is a situation where React won't take over (static pages), // we can simply return the text as it is. return escapedText; } return ( '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>' ); }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function(nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; ReactDOMComponent.BackendIDOperations.updateTextContentByID( this._rootNodeID, nextStringText ); } } }, unmountComponent: function() { ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); } }); module.exports = ReactDOMTextComponent; },{"12":12,"131":131,"29":29,"40":40,"48":48}],58:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextarea */ 'use strict'; var AutoFocusMixin = _dereq_(2); var DOMPropertyOperations = _dereq_(12); var LinkedValueUtils = _dereq_(26); var ReactBrowserComponentMixin = _dereq_(32); var ReactClass = _dereq_(38); var ReactElement = _dereq_(63); var ReactUpdates = _dereq_(100); var assign = _dereq_(29); var invariant = _dereq_(150); var warning = _dereq_(171); var textarea = ReactElement.createFactory('textarea'); function forceUpdateIfMounted() { /*jshint validthis:true */ if (this.isMounted()) { this.forceUpdate(); } } /** * Implements a <textarea> native component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = ReactClass.createClass({ displayName: 'ReactDOMTextarea', tagName: 'TEXTAREA', mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin], getInitialState: function() { var defaultValue = this.props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = this.props.children; if (children != null) { if ("production" !== "development") { ("production" !== "development" ? warning( false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.' ) : null); } ("production" !== "development" ? invariant( defaultValue == null, 'If you supply `defaultValue` on a <textarea>, do not pass children.' ) : invariant(defaultValue == null)); if (Array.isArray(children)) { ("production" !== "development" ? invariant( children.length <= 1, '<textarea> can only have at most one child.' ) : invariant(children.length <= 1)); children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } var value = LinkedValueUtils.getValue(this); return { // We save the initial value so that `ReactDOMComponent` doesn't update // `textContent` (unnecessary since we update value). // The initial value can be a boolean or object so that's why it's // forced to be a string. initialValue: '' + (value != null ? value : defaultValue) }; }, render: function() { // Clone `this.props` so we don't mutate the input. var props = assign({}, this.props); ("production" !== "development" ? invariant( props.dangerouslySetInnerHTML == null, '`dangerouslySetInnerHTML` does not make sense on <textarea>.' ) : invariant(props.dangerouslySetInnerHTML == null)); props.defaultValue = null; props.value = null; props.onChange = this._handleChange; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. return textarea(props, this.state.initialValue); }, componentDidUpdate: function(prevProps, prevState, prevContext) { var value = LinkedValueUtils.getValue(this); if (value != null) { var rootNode = this.getDOMNode(); // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value); } }, _handleChange: function(event) { var returnValue; var onChange = LinkedValueUtils.getOnChange(this); if (onChange) { returnValue = onChange.call(this, event); } ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } }); module.exports = ReactDOMTextarea; },{"100":100,"12":12,"150":150,"171":171,"2":2,"26":26,"29":29,"32":32,"38":38,"63":63}],59:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultBatchingStrategy */ 'use strict'; var ReactUpdates = _dereq_(100); var Transaction = _dereq_(116); var assign = _dereq_(29); var emptyFunction = _dereq_(129); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function() { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } assign( ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; } } ); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function(callback, a, b, c, d) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d); } else { transaction.perform(callback, null, a, b, c, d); } } }; module.exports = ReactDefaultBatchingStrategy; },{"100":100,"116":116,"129":129,"29":29}],60:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultInjection */ 'use strict'; var BeforeInputEventPlugin = _dereq_(3); var ChangeEventPlugin = _dereq_(8); var ClientReactRootIndex = _dereq_(9); var DefaultEventPluginOrder = _dereq_(14); var EnterLeaveEventPlugin = _dereq_(15); var ExecutionEnvironment = _dereq_(22); var HTMLDOMPropertyConfig = _dereq_(24); var MobileSafariClickEventPlugin = _dereq_(28); var ReactBrowserComponentMixin = _dereq_(32); var ReactClass = _dereq_(38); var ReactComponentBrowserEnvironment = _dereq_(40); var ReactDefaultBatchingStrategy = _dereq_(59); var ReactDOMComponent = _dereq_(48); var ReactDOMButton = _dereq_(47); var ReactDOMForm = _dereq_(49); var ReactDOMImg = _dereq_(52); var ReactDOMIDOperations = _dereq_(50); var ReactDOMIframe = _dereq_(51); var ReactDOMInput = _dereq_(53); var ReactDOMOption = _dereq_(54); var ReactDOMSelect = _dereq_(55); var ReactDOMTextarea = _dereq_(58); var ReactDOMTextComponent = _dereq_(57); var ReactElement = _dereq_(63); var ReactEventListener = _dereq_(68); var ReactInjection = _dereq_(70); var ReactInstanceHandles = _dereq_(72); var ReactMount = _dereq_(77); var ReactReconcileTransaction = _dereq_(88); var SelectEventPlugin = _dereq_(102); var ServerReactRootIndex = _dereq_(103); var SimpleEventPlugin = _dereq_(104); var SVGDOMPropertyConfig = _dereq_(101); var createFullPageComponent = _dereq_(125); function autoGenerateWrapperClass(type) { return ReactClass.createClass({ tagName: type.toUpperCase(), render: function() { return new ReactElement( type, null, null, null, null, this.props ); } }); } function inject() { ReactInjection.EventEmitter.injectReactEventListener( ReactEventListener ); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles); ReactInjection.EventPluginHub.injectMount(ReactMount); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, MobileSafariClickEventPlugin: MobileSafariClickEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.NativeComponent.injectGenericComponentClass( ReactDOMComponent ); ReactInjection.NativeComponent.injectTextComponentClass( ReactDOMTextComponent ); ReactInjection.NativeComponent.injectAutoWrapper( autoGenerateWrapperClass ); // This needs to happen before createFullPageComponent() otherwise the mixin // won't be included. ReactInjection.Class.injectMixin(ReactBrowserComponentMixin); ReactInjection.NativeComponent.injectComponentClasses({ 'button': ReactDOMButton, 'form': ReactDOMForm, 'iframe': ReactDOMIframe, 'img': ReactDOMImg, 'input': ReactDOMInput, 'option': ReactDOMOption, 'select': ReactDOMSelect, 'textarea': ReactDOMTextarea, 'html': createFullPageComponent('html'), 'head': createFullPageComponent('head'), 'body': createFullPageComponent('body') }); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponent('noscript'); ReactInjection.Updates.injectReconcileTransaction( ReactReconcileTransaction ); ReactInjection.Updates.injectBatchingStrategy( ReactDefaultBatchingStrategy ); ReactInjection.RootIndex.injectCreateReactRootIndex( ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex ); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); ReactInjection.DOMComponent.injectIDOperations(ReactDOMIDOperations); if ("production" !== "development") { var url = (ExecutionEnvironment.canUseDOM && window.location.href) || ''; if ((/[?&]react_perf\b/).test(url)) { var ReactDefaultPerf = _dereq_(61); ReactDefaultPerf.start(); } } } module.exports = { inject: inject }; },{"101":101,"102":102,"103":103,"104":104,"125":125,"14":14,"15":15,"22":22,"24":24,"28":28,"3":3,"32":32,"38":38,"40":40,"47":47,"48":48,"49":49,"50":50,"51":51,"52":52,"53":53,"54":54,"55":55,"57":57,"58":58,"59":59,"61":61,"63":63,"68":68,"70":70,"72":72,"77":77,"8":8,"88":88,"9":9}],61:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerf * @typechecks static-only */ 'use strict'; var DOMProperty = _dereq_(11); var ReactDefaultPerfAnalysis = _dereq_(62); var ReactMount = _dereq_(77); var ReactPerf = _dereq_(82); var performanceNow = _dereq_(162); function roundFloat(val) { return Math.floor(val * 100) / 100; } function addValue(obj, key, val) { obj[key] = (obj[key] || 0) + val; } var ReactDefaultPerf = { _allMeasurements: [], // last item in the list is the current one _mountStack: [0], _injected: false, start: function() { if (!ReactDefaultPerf._injected) { ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure); } ReactDefaultPerf._allMeasurements.length = 0; ReactPerf.enableMeasure = true; }, stop: function() { ReactPerf.enableMeasure = false; }, getLastMeasurements: function() { return ReactDefaultPerf._allMeasurements; }, printExclusive: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements); console.table(summary.map(function(item) { return { 'Component class name': item.componentName, 'Total inclusive time (ms)': roundFloat(item.inclusive), 'Exclusive mount time (ms)': roundFloat(item.exclusive), 'Exclusive render time (ms)': roundFloat(item.render), 'Mount time per instance (ms)': roundFloat(item.exclusive / item.count), 'Render time per instance (ms)': roundFloat(item.render / item.count), 'Instances': item.count }; })); // TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct // number. }, printInclusive: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements); console.table(summary.map(function(item) { return { 'Owner > component': item.componentName, 'Inclusive time (ms)': roundFloat(item.time), 'Instances': item.count }; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, getMeasurementsSummaryMap: function(measurements) { var summary = ReactDefaultPerfAnalysis.getInclusiveSummary( measurements, true ); return summary.map(function(item) { return { 'Owner > component': item.componentName, 'Wasted time (ms)': item.time, 'Instances': item.count }; }); }, printWasted: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements)); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, printDOM: function(measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements); console.table(summary.map(function(item) { var result = {}; result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id; result['type'] = item.type; result['args'] = JSON.stringify(item.args); return result; })); console.log( 'Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms' ); }, _recordWrite: function(id, fnName, totalTime, args) { // TODO: totalTime isn't that useful since it doesn't count paints/reflows var writes = ReactDefaultPerf ._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1] .writes; writes[id] = writes[id] || []; writes[id].push({ type: fnName, time: totalTime, args: args }); }, measure: function(moduleName, fnName, func) { return function() {for (var args=[],$__0=0,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); var totalTime; var rv; var start; if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { // A "measurement" is a set of metrics recorded for each flush. We want // to group the metrics for a given flush together so we can look at the // components that rendered and the DOM operations that actually // happened to determine the amount of "wasted work" performed. ReactDefaultPerf._allMeasurements.push({ exclusive: {}, inclusive: {}, render: {}, counts: {}, writes: {}, displayNames: {}, totalTime: 0 }); start = performanceNow(); rv = func.apply(this, args); ReactDefaultPerf._allMeasurements[ ReactDefaultPerf._allMeasurements.length - 1 ].totalTime = performanceNow() - start; return rv; } else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactDOMIDOperations') { start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (fnName === '_mountImageIntoNode') { var mountID = ReactMount.getID(args[1]); ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]); } else if (fnName === 'dangerouslyProcessChildrenUpdates') { // special format args[0].forEach(function(update) { var writeArgs = {}; if (update.fromIndex !== null) { writeArgs.fromIndex = update.fromIndex; } if (update.toIndex !== null) { writeArgs.toIndex = update.toIndex; } if (update.textContent !== null) { writeArgs.textContent = update.textContent; } if (update.markupIndex !== null) { writeArgs.markup = args[1][update.markupIndex]; } ReactDefaultPerf._recordWrite( update.parentID, update.type, totalTime, writeArgs ); }); } else { // basic format ReactDefaultPerf._recordWrite( args[0], fnName, totalTime, Array.prototype.slice.call(args, 1) ); } return rv; } else if (moduleName === 'ReactCompositeComponent' && ( (// TODO: receiveComponent()? (fnName === 'mountComponent' || fnName === 'updateComponent' || fnName === '_renderValidatedComponent')))) { if (typeof this._currentElement.type === 'string') { return func.apply(this, args); } var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID; var isRender = fnName === '_renderValidatedComponent'; var isMount = fnName === 'mountComponent'; var mountStack = ReactDefaultPerf._mountStack; var entry = ReactDefaultPerf._allMeasurements[ ReactDefaultPerf._allMeasurements.length - 1 ]; if (isRender) { addValue(entry.counts, rootNodeID, 1); } else if (isMount) { mountStack.push(0); } start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (isRender) { addValue(entry.render, rootNodeID, totalTime); } else if (isMount) { var subMountTime = mountStack.pop(); mountStack[mountStack.length - 1] += totalTime; addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); addValue(entry.inclusive, rootNodeID, totalTime); } else { addValue(entry.inclusive, rootNodeID, totalTime); } entry.displayNames[rootNodeID] = { current: this.getName(), owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>' }; return rv; } else { return func.apply(this, args); } }; } }; module.exports = ReactDefaultPerf; },{"11":11,"162":162,"62":62,"77":77,"82":82}],62:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerfAnalysis */ var assign = _dereq_(29); // Don't try to save users less than 1.2ms (a number I made up) var DONT_CARE_THRESHOLD = 1.2; var DOM_OPERATION_TYPES = { '_mountImageIntoNode': 'set innerHTML', INSERT_MARKUP: 'set innerHTML', MOVE_EXISTING: 'move', REMOVE_NODE: 'remove', TEXT_CONTENT: 'set textContent', 'updatePropertyByID': 'update attribute', 'deletePropertyByID': 'delete attribute', 'updateStylesByID': 'update styles', 'updateInnerHTMLByID': 'set innerHTML', 'dangerouslyReplaceNodeWithMarkupByID': 'replace' }; function getTotalTime(measurements) { // TODO: return number of DOM ops? could be misleading. // TODO: measure dropped frames after reconcile? // TODO: log total time of each reconcile and the top-level component // class that triggered it. var totalTime = 0; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; totalTime += measurement.totalTime; } return totalTime; } function getDOMSummary(measurements) { var items = []; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var id; for (id in measurement.writes) { measurement.writes[id].forEach(function(write) { items.push({ id: id, type: DOM_OPERATION_TYPES[write.type] || write.type, args: write.args }); }); } } return items; } function getExclusiveSummary(measurements) { var candidates = {}; var displayName; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign( {}, measurement.exclusive, measurement.inclusive ); for (var id in allIDs) { displayName = measurement.displayNames[id].current; candidates[displayName] = candidates[displayName] || { componentName: displayName, inclusive: 0, exclusive: 0, render: 0, count: 0 }; if (measurement.render[id]) { candidates[displayName].render += measurement.render[id]; } if (measurement.exclusive[id]) { candidates[displayName].exclusive += measurement.exclusive[id]; } if (measurement.inclusive[id]) { candidates[displayName].inclusive += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[displayName].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (displayName in candidates) { if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) { arr.push(candidates[displayName]); } } arr.sort(function(a, b) { return b.exclusive - a.exclusive; }); return arr; } function getInclusiveSummary(measurements, onlyClean) { var candidates = {}; var inclusiveKey; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign( {}, measurement.exclusive, measurement.inclusive ); var cleanComponents; if (onlyClean) { cleanComponents = getUnchangedComponents(measurement); } for (var id in allIDs) { if (onlyClean && !cleanComponents[id]) { continue; } var displayName = measurement.displayNames[id]; // Inclusive time is not useful for many components without knowing where // they are instantiated. So we aggregate inclusive time with both the // owner and current displayName as the key. inclusiveKey = displayName.owner + ' > ' + displayName.current; candidates[inclusiveKey] = candidates[inclusiveKey] || { componentName: inclusiveKey, time: 0, count: 0 }; if (measurement.inclusive[id]) { candidates[inclusiveKey].time += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[inclusiveKey].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (inclusiveKey in candidates) { if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { arr.push(candidates[inclusiveKey]); } } arr.sort(function(a, b) { return b.time - a.time; }); return arr; } function getUnchangedComponents(measurement) { // For a given reconcile, look at which components did not actually // render anything to the DOM and return a mapping of their ID to // the amount of time it took to render the entire subtree. var cleanComponents = {}; var dirtyLeafIDs = Object.keys(measurement.writes); var allIDs = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // For each component that rendered, see if a component that triggered // a DOM op is in its subtree. for (var i = 0; i < dirtyLeafIDs.length; i++) { if (dirtyLeafIDs[i].indexOf(id) === 0) { isDirty = true; break; } } if (!isDirty && measurement.counts[id] > 0) { cleanComponents[id] = true; } } return cleanComponents; } var ReactDefaultPerfAnalysis = { getExclusiveSummary: getExclusiveSummary, getInclusiveSummary: getInclusiveSummary, getDOMSummary: getDOMSummary, getTotalTime: getTotalTime }; module.exports = ReactDefaultPerfAnalysis; },{"29":29}],63:[function(_dereq_,module,exports){ /** * 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 ReactElement */ 'use strict'; var ReactContext = _dereq_(44); var ReactCurrentOwner = _dereq_(45); var assign = _dereq_(29); var warning = _dereq_(171); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== "development" ? warning( false, 'Don\'t set the %s property of the React element. Instead, ' + 'specify the correct value when initially creating the element.', key ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== "development") { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = {props: props, originalProps: assign({}, props)}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if ("production" !== "development") { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if ("production" !== "development") { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function(element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return new ReactElement( element.type, key, ref, owner, element._context, props ); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement; },{"171":171,"29":29,"44":44,"45":45}],64:[function(_dereq_,module,exports){ /** * 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 ReactElementValidator */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactElement = _dereq_(63); var ReactFragment = _dereq_(69); var ReactPropTypeLocations = _dereq_(85); var ReactPropTypeLocationNames = _dereq_(84); var ReactCurrentOwner = _dereq_(45); var ReactNativeComponent = _dereq_(80); var getIteratorFn = _dereq_(141); var invariant = _dereq_(150); var warning = _dereq_(171); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; var loggedTypeFailures = {}; var NUMERIC_PROPERTY_REGEX = /^\d+$/; /** * Gets the instance's name for use in warnings. * * @internal * @return {?string} Display name or undefined */ function getName(instance) { var publicInstance = instance && instance.getPublicInstance(); if (!publicInstance) { return undefined; } var constructor = publicInstance.constructor; if (!constructor) { return undefined; } return constructor.displayName || constructor.name || undefined; } /** * Gets the current owner's displayName for use in warnings. * * @internal * @return {?string} Display name or undefined */ function getCurrentOwnerDisplayName() { var current = ReactCurrentOwner.current; return ( current && getName(current) || undefined ); } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (element._store.validated || element.key != null) { return; } element._store.validated = true; warnAndMonitorForKeyUse( 'Each child in an array or iterator should have a unique "key" prop.', element, parentType ); } /** * Warn if the key is being defined as an object property but has an incorrect * value. * * @internal * @param {string} name Property name of the key. * @param {ReactElement} element Component that requires a key. * @param {*} parentType element's parent's type. */ function validatePropertyKey(name, element, parentType) { if (!NUMERIC_PROPERTY_REGEX.test(name)) { return; } warnAndMonitorForKeyUse( 'Child objects should have non-numeric keys so ordering is preserved.', element, parentType ); } /** * Shared warning and monitoring code for the key warnings. * * @internal * @param {string} message The base warning that gets output. * @param {ReactElement} element Component that requires a key. * @param {*} parentType element's parent's type. */ function warnAndMonitorForKeyUse(message, element, parentType) { var ownerName = getCurrentOwnerDisplayName(); var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; var useName = ownerName || parentName; var memoizer = ownerHasKeyUseWarning[message] || ( (ownerHasKeyUseWarning[message] = {}) ); if (memoizer.hasOwnProperty(useName)) { return; } memoizer[useName] = true; var parentOrOwnerAddendum = ownerName ? (" Check the render method of " + ownerName + ".") : parentName ? (" Check the React.render call using <" + parentName + ">.") : ''; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwnerAddendum = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Name of the component that originally created this child. var childOwnerName = getName(element._owner); childOwnerAddendum = (" It was passed a child from " + childOwnerName + "."); } ("production" !== "development" ? warning( false, message + '%s%s See https://fb.me/react-warning-keys for more information.', parentOrOwnerAddendum, childOwnerAddendum ) : null); } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. node._store.validated = true; } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } else if (typeof node === 'object') { var fragment = ReactFragment.extractIfFragment(node); for (var key in fragment) { if (fragment.hasOwnProperty(key)) { validatePropertyKey(key, fragment[key], parentType); } } } } } /** * Assert that the props are valid * * @param {string} componentName Name of the component for error messages. * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ function checkPropTypes(componentName, propTypes, props, location) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. ("production" !== "development" ? invariant( typeof propTypes[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName ) : invariant(typeof propTypes[propName] === 'function')); error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(this); ("production" !== "development" ? warning(false, 'Failed propType: %s%s', error.message, addendum) : null); } } } } var warnedPropsMutations = {}; /** * Warn about mutating props when setting `propName` on `element`. * * @param {string} propName The string key within props that was set * @param {ReactElement} element */ function warnForPropsMutation(propName, element) { var type = element.type; var elementName = typeof type === 'string' ? type : type.displayName; var ownerName = element._owner ? element._owner.getPublicInstance().constructor.displayName : null; var warningKey = propName + '|' + elementName + '|' + ownerName; if (warnedPropsMutations.hasOwnProperty(warningKey)) { return; } warnedPropsMutations[warningKey] = true; var elementInfo = ''; if (elementName) { elementInfo = ' <' + elementName + ' />'; } var ownerInfo = ''; if (ownerName) { ownerInfo = ' The element was created by ' + ownerName + '.'; } ("production" !== "development" ? warning( false, 'Don\'t set .props.%s of the React component%s. Instead, specify the ' + 'correct value when initially creating the element or use ' + 'React.cloneElement to make a new element with updated props.%s', propName, elementInfo, ownerInfo ) : null); } // Inline Object.is polyfill function is(a, b) { if (a !== a) { // NaN return b !== b; } if (a === 0 && b === 0) { // +-0 return 1 / a === 1 / b; } return a === b; } /** * Given an element, check if its props have been mutated since element * creation (or the last call to this function). In particular, check if any * new props have been added, which we can't directly catch by defining warning * properties on the props object. * * @param {ReactElement} element */ function checkAndWarnForMutatedProps(element) { if (!element._store) { // Element was created using `new ReactElement` directly or with // `ReactElement.createElement`; skip mutation checking return; } var originalProps = element._store.originalProps; var props = element.props; for (var propName in props) { if (props.hasOwnProperty(propName)) { if (!originalProps.hasOwnProperty(propName) || !is(originalProps[propName], props[propName])) { warnForPropsMutation(propName, element); // Copy over the new value so that the two props objects match again originalProps[propName] = props[propName]; } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { if (element.type == null) { // This has already warned. Don't throw. return; } // Extract the component class from the element. Converts string types // to a composite class which may have propTypes. // TODO: Validating a string's propTypes is not decoupled from the // rendering target which is problematic. var componentClass = ReactNativeComponent.getComponentClassForElement( element ); var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkPropTypes( name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop ); } if (typeof componentClass.getDefaultProps === 'function') { ("production" !== "development" ? warning( componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.' ) : null); } } var ReactElementValidator = { checkAndWarnForMutatedProps: checkAndWarnForMutatedProps, createElement: function(type, props, children) { // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. ("production" !== "development" ? warning( type != null, 'React.createElement: type should not be null or undefined. It should ' + 'be a string (for DOM elements) or a ReactClass (for composite ' + 'components).' ) : null); var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } validatePropTypes(element); return element; }, createFactory: function(type) { var validatedFactory = ReactElementValidator.createElement.bind( null, type ); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if ("production" !== "development") { try { Object.defineProperty( validatedFactory, 'type', { enumerable: false, get: function() { ("production" !== "development" ? warning( false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.' ) : null); Object.defineProperty(this, 'type', { value: type }); return type; } } ); } catch (x) { // IE will fail on defineProperty (es5-shim/sham too) } } return validatedFactory; }, cloneElement: function(element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; },{"141":141,"150":150,"171":171,"45":45,"63":63,"69":69,"80":80,"84":84,"85":85}],65:[function(_dereq_,module,exports){ /** * 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 ReactEmptyComponent */ 'use strict'; var ReactElement = _dereq_(63); var ReactInstanceMap = _dereq_(73); var invariant = _dereq_(150); var component; // This registry keeps track of the React IDs of the components that rendered to // `null` (in reality a placeholder such as `noscript`) var nullComponentIDsRegistry = {}; var ReactEmptyComponentInjection = { injectEmptyComponent: function(emptyComponent) { component = ReactElement.createFactory(emptyComponent); } }; var ReactEmptyComponentType = function() {}; ReactEmptyComponentType.prototype.componentDidMount = function() { var internalInstance = ReactInstanceMap.get(this); // TODO: Make sure we run these methods in the correct order, we shouldn't // need this check. We're going to assume if we're here it means we ran // componentWillUnmount already so there is no internal instance (it gets // removed as part of the unmounting process). if (!internalInstance) { return; } registerNullComponentID(internalInstance._rootNodeID); }; ReactEmptyComponentType.prototype.componentWillUnmount = function() { var internalInstance = ReactInstanceMap.get(this); // TODO: Get rid of this check. See TODO in componentDidMount. if (!internalInstance) { return; } deregisterNullComponentID(internalInstance._rootNodeID); }; ReactEmptyComponentType.prototype.render = function() { ("production" !== "development" ? invariant( component, 'Trying to return null from a render, but no null placeholder component ' + 'was injected.' ) : invariant(component)); return component(); }; var emptyElement = ReactElement.createElement(ReactEmptyComponentType); /** * Mark the component as having rendered to null. * @param {string} id Component's `_rootNodeID`. */ function registerNullComponentID(id) { nullComponentIDsRegistry[id] = true; } /** * Unmark the component as having rendered to null: it renders to something now. * @param {string} id Component's `_rootNodeID`. */ function deregisterNullComponentID(id) { delete nullComponentIDsRegistry[id]; } /** * @param {string} id Component's `_rootNodeID`. * @return {boolean} True if the component is rendered to null. */ function isNullComponentID(id) { return !!nullComponentIDsRegistry[id]; } var ReactEmptyComponent = { emptyElement: emptyElement, injection: ReactEmptyComponentInjection, isNullComponentID: isNullComponentID }; module.exports = ReactEmptyComponent; },{"150":150,"63":63,"73":73}],66:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactErrorUtils * @typechecks */ "use strict"; var ReactErrorUtils = { /** * Creates a guarded version of a function. This is supposed to make debugging * of event handlers easier. To aid debugging with the browser's debugger, * this currently simply returns the original function. * * @param {function} func Function to be executed * @param {string} name The name of the guard * @return {function} */ guard: function(func, name) { return func; } }; module.exports = ReactErrorUtils; },{}],67:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventEmitterMixin */ 'use strict'; var EventPluginHub = _dereq_(18); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native environment event. */ handleTopLevel: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events = EventPluginHub.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; },{"18":18}],68:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventListener * @typechecks static-only */ 'use strict'; var EventListener = _dereq_(17); var ExecutionEnvironment = _dereq_(22); var PooledClass = _dereq_(30); var ReactInstanceHandles = _dereq_(72); var ReactMount = _dereq_(77); var ReactUpdates = _dereq_(100); var assign = _dereq_(29); var getEventTarget = _dereq_(140); var getUnboundedScrollPosition = _dereq_(146); /** * Finds the parent React component of `node`. * * @param {*} node * @return {?DOMEventTarget} Parent container, or `null` if the specified node * is not nested. */ function findParent(node) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. var nodeID = ReactMount.getID(node); var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); var container = ReactMount.findReactContainerForID(rootID); var parent = ReactMount.getFirstReactDOM(container); return parent; } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } assign(TopLevelCallbackBookKeeping.prototype, { destructor: function() { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo( TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler ); function handleTopLevelImpl(bookKeeping) { var topLevelTarget = ReactMount.getFirstReactDOM( getEventTarget(bookKeeping.nativeEvent) ) || window; // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = topLevelTarget; while (ancestor) { bookKeeping.ancestors.push(ancestor); ancestor = findParent(ancestor); } for (var i = 0, l = bookKeeping.ancestors.length; i < l; i++) { topLevelTarget = bookKeeping.ancestors[i]; var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; ReactEventListener._handleTopLevel( bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent ); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function(handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function(enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function() { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.listen( element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType) ); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.capture( element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType) ); }, monitorScrollValue: function(refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function(topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled( topLevelType, nativeEvent ); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; },{"100":100,"140":140,"146":146,"17":17,"22":22,"29":29,"30":30,"72":72,"77":77}],69:[function(_dereq_,module,exports){ /** * 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 = _dereq_(63); var warning = _dereq_(171); /** * 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. */ if ("production" !== "development") { var fragmentKey = '_reactFragment'; var didWarnKey = '_reactDidWarn'; var canWarnForReactFragment = false; 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) { } var proxyPropertyAccessWithWarning = function(obj, key) { Object.defineProperty(obj, key, { enumerable: true, get: function() { ("production" !== "development" ? 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.' ) : null); this[didWarnKey] = true; return this[fragmentKey][key]; }, set: function(value) { ("production" !== "development" ? warning( this[didWarnKey], 'A ReactFragment is an immutable opaque type. Mutating its ' + 'properties is deprecated.' ) : null); this[didWarnKey] = true; this[fragmentKey][key] = value; } }); }; var issuedWarnings = {}; var didWarnForFragment = function(fragment) { // We use the keys and the type of the value as a heuristic to dedupe the // warning to avoid spamming too much. var fragmentCacheKey = ''; for (var key in fragment) { fragmentCacheKey += key + ':' + (typeof fragment[key]) + ','; } 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 ("production" !== "development") { if (typeof object !== 'object' || !object || Array.isArray(object)) { ("production" !== "development" ? warning( false, 'React.addons.createFragment only accepts a single object.', object ) : null); return object; } if (ReactElement.isValidElement(object)) { ("production" !== "development" ? warning( false, 'React.addons.createFragment does not accept a ReactElement ' + 'without a wrapper object.' ) : null); 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 ("production" !== "development") { if (canWarnForReactFragment) { if (!fragment[fragmentKey]) { ("production" !== "development" ? warning( didWarnForFragment(fragment), 'Any use of a keyed object should be wrapped in ' + 'React.addons.createFragment(object) before being passed as a ' + 'child.' ) : null); 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 ("production" !== "development") { 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; },{"171":171,"63":63}],70:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInjection */ 'use strict'; var DOMProperty = _dereq_(11); var EventPluginHub = _dereq_(18); var ReactComponentEnvironment = _dereq_(41); var ReactClass = _dereq_(38); var ReactEmptyComponent = _dereq_(65); var ReactBrowserEventEmitter = _dereq_(33); var ReactNativeComponent = _dereq_(80); var ReactDOMComponent = _dereq_(48); var ReactPerf = _dereq_(82); var ReactRootIndex = _dereq_(91); var ReactUpdates = _dereq_(100); var ReactInjection = { Component: ReactComponentEnvironment.injection, Class: ReactClass.injection, DOMComponent: ReactDOMComponent.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventEmitter: ReactBrowserEventEmitter.injection, NativeComponent: ReactNativeComponent.injection, Perf: ReactPerf.injection, RootIndex: ReactRootIndex.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; },{"100":100,"11":11,"18":18,"33":33,"38":38,"41":41,"48":48,"65":65,"80":80,"82":82,"91":91}],71:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInputSelection */ 'use strict'; var ReactDOMSelection = _dereq_(56); var containsNode = _dereq_(123); var focusNode = _dereq_(134); var getActiveElement = _dereq_(136); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function(elem) { return elem && ( ((elem.nodeName === 'INPUT' && elem.type === 'text') || elem.nodeName === 'TEXTAREA' || elem.contentEditable === 'true') ); }, getSelectionInformation: function() { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function(priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection( priorFocusedElem, priorSelectionRange ); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function(input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName === 'INPUT') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || {start: 0, end: 0}; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function(input, offsets) { var start = offsets.start; var end = offsets.end; if (typeof end === 'undefined') { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName === 'INPUT') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; },{"123":123,"134":134,"136":136,"56":56}],72:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceHandles * @typechecks static-only */ 'use strict'; var ReactRootIndex = _dereq_(91); var invariant = _dereq_(150); var SEPARATOR = '.'; var SEPARATOR_LENGTH = SEPARATOR.length; /** * Maximum depth of traversals before we consider the possibility of a bad ID. */ var MAX_TREE_DEPTH = 100; /** * Creates a DOM ID prefix to use when mounting React components. * * @param {number} index A unique integer * @return {string} React root ID. * @internal */ function getReactRootIDString(index) { return SEPARATOR + index.toString(36); } /** * Checks if a character in the supplied ID is a separator or the end. * * @param {string} id A React DOM ID. * @param {number} index Index of the character to check. * @return {boolean} True if the character is a separator or end of the ID. * @private */ function isBoundary(id, index) { return id.charAt(index) === SEPARATOR || index === id.length; } /** * Checks if the supplied string is a valid React DOM ID. * * @param {string} id A React DOM ID, maybe. * @return {boolean} True if the string is a valid React DOM ID. * @private */ function isValidID(id) { return id === '' || ( id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR ); } /** * Checks if the first ID is an ancestor of or equal to the second ID. * * @param {string} ancestorID * @param {string} descendantID * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. * @internal */ function isAncestorIDOf(ancestorID, descendantID) { return ( descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length) ); } /** * Gets the parent ID of the supplied React DOM ID, `id`. * * @param {string} id ID of a component. * @return {string} ID of the parent, or an empty string. * @private */ function getParentID(id) { return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; } /** * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the * supplied `destinationID`. If they are equal, the ID is returned. * * @param {string} ancestorID ID of an ancestor node of `destinationID`. * @param {string} destinationID ID of the destination node. * @return {string} Next ID on the path from `ancestorID` to `destinationID`. * @private */ function getNextDescendantID(ancestorID, destinationID) { ("production" !== "development" ? invariant( isValidID(ancestorID) && isValidID(destinationID), 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID ) : invariant(isValidID(ancestorID) && isValidID(destinationID))); ("production" !== "development" ? invariant( isAncestorIDOf(ancestorID, destinationID), 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID ) : invariant(isAncestorIDOf(ancestorID, destinationID))); if (ancestorID === destinationID) { return ancestorID; } // Skip over the ancestor and the immediate separator. Traverse until we hit // another separator or we reach the end of `destinationID`. var start = ancestorID.length + SEPARATOR_LENGTH; var i; for (i = start; i < destinationID.length; i++) { if (isBoundary(destinationID, i)) { break; } } return destinationID.substr(0, i); } /** * Gets the nearest common ancestor ID of two IDs. * * Using this ID scheme, the nearest common ancestor ID is the longest common * prefix of the two IDs that immediately preceded a "marker" in both strings. * * @param {string} oneID * @param {string} twoID * @return {string} Nearest common ancestor ID, or the empty string if none. * @private */ function getFirstCommonAncestorID(oneID, twoID) { var minLength = Math.min(oneID.length, twoID.length); if (minLength === 0) { return ''; } var lastCommonMarkerIndex = 0; // Use `<=` to traverse until the "EOL" of the shorter string. for (var i = 0; i <= minLength; i++) { if (isBoundary(oneID, i) && isBoundary(twoID, i)) { lastCommonMarkerIndex = i; } else if (oneID.charAt(i) !== twoID.charAt(i)) { break; } } var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); ("production" !== "development" ? invariant( isValidID(longestCommonID), 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID ) : invariant(isValidID(longestCommonID))); return longestCommonID; } /** * Traverses the parent path between two IDs (either up or down). The IDs must * not be the same, and there must exist a parent path between them. If the * callback returns `false`, traversal is stopped. * * @param {?string} start ID at which to start traversal. * @param {?string} stop ID at which to end traversal. * @param {function} cb Callback to invoke each ID with. * @param {?boolean} skipFirst Whether or not to skip the first node. * @param {?boolean} skipLast Whether or not to skip the last node. * @private */ function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { start = start || ''; stop = stop || ''; ("production" !== "development" ? invariant( start !== stop, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start ) : invariant(start !== stop)); var traverseUp = isAncestorIDOf(stop, start); ("production" !== "development" ? invariant( traverseUp || isAncestorIDOf(start, stop), 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop ) : invariant(traverseUp || isAncestorIDOf(start, stop))); // Traverse from `start` to `stop` one depth at a time. var depth = 0; var traverse = traverseUp ? getParentID : getNextDescendantID; for (var id = start; /* until break */; id = traverse(id, stop)) { var ret; if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { ret = cb(id, traverseUp, arg); } if (ret === false || id === stop) { // Only break //after// visiting `stop`. break; } ("production" !== "development" ? invariant( depth++ < MAX_TREE_DEPTH, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop ) : invariant(depth++ < MAX_TREE_DEPTH)); } } /** * Manages the IDs assigned to DOM representations of React components. This * uses a specific scheme in order to traverse the DOM efficiently (e.g. in * order to simulate events). * * @internal */ var ReactInstanceHandles = { /** * Constructs a React root ID * @return {string} A React root ID. */ createReactRootID: function() { return getReactRootIDString(ReactRootIndex.createReactRootIndex()); }, /** * Constructs a React ID by joining a root ID with a name. * * @param {string} rootID Root ID of a parent component. * @param {string} name A component's name (as flattened children). * @return {string} A React ID. * @internal */ createReactID: function(rootID, name) { return rootID + name; }, /** * Gets the DOM ID of the React component that is the root of the tree that * contains the React component with the supplied DOM ID. * * @param {string} id DOM ID of a React component. * @return {?string} DOM ID of the React component that is the root. * @internal */ getReactRootIDFromNodeID: function(id) { if (id && id.charAt(0) === SEPARATOR && id.length > 1) { var index = id.indexOf(SEPARATOR, 1); return index > -1 ? id.substr(0, index) : id; } return null; }, /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * NOTE: Does not invoke the callback on the nearest common ancestor because * nothing "entered" or "left" that element. * * @param {string} leaveID ID being left. * @param {string} enterID ID being entered. * @param {function} cb Callback to invoke on each entered/left ID. * @param {*} upArg Argument to invoke the callback with on left IDs. * @param {*} downArg Argument to invoke the callback with on entered IDs. * @internal */ traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) { var ancestorID = getFirstCommonAncestorID(leaveID, enterID); if (ancestorID !== leaveID) { traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); } if (ancestorID !== enterID) { traverseParentPath(ancestorID, enterID, cb, downArg, true, false); } }, /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseTwoPhase: function(targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, false); traverseParentPath(targetID, '', cb, arg, false, true); } }, /** * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For * example, passing `.0.$row-0.1` would result in `cb` getting called * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseAncestors: function(targetID, cb, arg) { traverseParentPath('', targetID, cb, arg, true, false); }, /** * Exposed for unit testing. * @private */ _getFirstCommonAncestorID: getFirstCommonAncestorID, /** * Exposed for unit testing. * @private */ _getNextDescendantID: getNextDescendantID, isAncestorIDOf: isAncestorIDOf, SEPARATOR: SEPARATOR }; module.exports = ReactInstanceHandles; },{"150":150,"91":91}],73:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceMap */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function(key) { key._reactInternalInstance = undefined; }, get: function(key) { return key._reactInternalInstance; }, has: function(key) { return key._reactInternalInstance !== undefined; }, set: function(key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; },{}],74:[function(_dereq_,module,exports){ /** * 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 ReactLifeCycle */ 'use strict'; /** * This module manages the bookkeeping when a component is in the process * of being mounted or being unmounted. This is used as a way to enforce * invariants (or warnings) when it is not recommended to call * setState/forceUpdate. * * currentlyMountingInstance: During the construction phase, it is not possible * to trigger an update since the instance is not fully mounted yet. However, we * currently allow this as a convenience for mutating the initial state. * * currentlyUnmountingInstance: During the unmounting phase, the instance is * still mounted and can therefore schedule an update. However, this is not * recommended and probably an error since it's about to be unmounted. * Therefore we still want to trigger in an error for that case. */ var ReactLifeCycle = { currentlyMountingInstance: null, currentlyUnmountingInstance: null }; module.exports = ReactLifeCycle; },{}],75:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactLink * @typechecks static-only */ 'use strict'; /** * ReactLink encapsulates a common pattern in which a component wants to modify * a prop received from its parent. ReactLink allows the parent to pass down a * value coupled with a callback that, when invoked, expresses an intent to * modify that value. For example: * * React.createClass({ * getInitialState: function() { * return {value: ''}; * }, * render: function() { * var valueLink = new ReactLink(this.state.value, this._handleValueChange); * return <input valueLink={valueLink} />; * }, * this._handleValueChange: function(newValue) { * this.setState({value: newValue}); * } * }); * * We have provided some sugary mixins to make the creation and * consumption of ReactLink easier; see LinkedValueUtils and LinkedStateMixin. */ var React = _dereq_(31); /** * @param {*} value current value of the link * @param {function} requestChange callback to request a change */ function ReactLink(value, requestChange) { this.value = value; this.requestChange = requestChange; } /** * Creates a PropType that enforces the ReactLink API and optionally checks the * type of the value being passed inside the link. Example: * * MyComponent.propTypes = { * tabIndexLink: ReactLink.PropTypes.link(React.PropTypes.number) * } */ function createLinkTypeChecker(linkType) { var shapes = { value: typeof linkType === 'undefined' ? React.PropTypes.any.isRequired : linkType.isRequired, requestChange: React.PropTypes.func.isRequired }; return React.PropTypes.shape(shapes); } ReactLink.PropTypes = { link: createLinkTypeChecker }; module.exports = ReactLink; },{"31":31}],76:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMarkupChecksum */ 'use strict'; var adler32 = _dereq_(119); var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function(markup) { var checksum = adler32(markup); return markup.replace( '>', ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '">' ); }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function(markup, element) { var existingChecksum = element.getAttribute( ReactMarkupChecksum.CHECKSUM_ATTR_NAME ); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; },{"119":119}],77:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMount */ 'use strict'; var DOMProperty = _dereq_(11); var ReactBrowserEventEmitter = _dereq_(33); var ReactCurrentOwner = _dereq_(45); var ReactElement = _dereq_(63); var ReactElementValidator = _dereq_(64); var ReactEmptyComponent = _dereq_(65); var ReactInstanceHandles = _dereq_(72); var ReactInstanceMap = _dereq_(73); var ReactMarkupChecksum = _dereq_(76); var ReactPerf = _dereq_(82); var ReactReconciler = _dereq_(89); var ReactUpdateQueue = _dereq_(99); var ReactUpdates = _dereq_(100); var emptyObject = _dereq_(130); var containsNode = _dereq_(123); var getReactRootElementInContainer = _dereq_(144); var instantiateReactComponent = _dereq_(149); var invariant = _dereq_(150); var setInnerHTML = _dereq_(164); var shouldUpdateReactComponent = _dereq_(167); var warning = _dereq_(171); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var nodeCache = {}; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; /** Mapping from reactRootID to React component instance. */ var instancesByReactRootID = {}; /** Mapping from reactRootID to `container` nodes. */ var containersByReactRootID = {}; if ("production" !== "development") { /** __DEV__-only mapping from reactRootID to root elements. */ var rootElementsByReactRootID = {}; } // Used to store breadth-first search state in findComponentRoot. var findComponentRootReusableArray = []; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement} container DOM element that may contain a React component. * @return {?string} A "reactRoot" ID, if a React component is rendered. */ function getReactRootID(container) { var rootElement = getReactRootElementInContainer(container); return rootElement && ReactMount.getID(rootElement); } /** * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form * element can return its control whose name or ID equals ATTR_NAME. All * DOM nodes support `getAttributeNode` but this can also get called on * other objects so just return '' if we're given something other than a * DOM node (such as window). * * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. * @return {string} ID of the supplied `domNode`. */ function getID(node) { var id = internalGetID(node); if (id) { if (nodeCache.hasOwnProperty(id)) { var cached = nodeCache[id]; if (cached !== node) { ("production" !== "development" ? invariant( !isValid(cached, id), 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id ) : invariant(!isValid(cached, id))); nodeCache[id] = node; } } else { nodeCache[id] = node; } } return id; } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Sets the React-specific ID of the given node. * * @param {DOMElement} node The DOM node whose ID will be set. * @param {string} id The value of the ID attribute. */ function setID(node, id) { var oldID = internalGetID(node); if (oldID !== id) { delete nodeCache[oldID]; } node.setAttribute(ATTR_NAME, id); nodeCache[id] = node; } /** * Finds the node with the supplied React-generated DOM ID. * * @param {string} id A React-generated DOM ID. * @return {DOMElement} DOM node with the suppled `id`. * @internal */ function getNode(id) { if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * Finds the node with the supplied public React instance. * * @param {*} instance A public React instance. * @return {?DOMElement} DOM node with the suppled `id`. * @internal */ function getNodeFromInstance(instance) { var id = ReactInstanceMap.get(instance)._rootNodeID; if (ReactEmptyComponent.isNullComponentID(id)) { return null; } if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * A node is "valid" if it is contained by a currently mounted container. * * This means that the node does not have to be contained by a document in * order to be considered valid. * * @param {?DOMElement} node The candidate DOM node. * @param {string} id The expected ID of the node. * @return {boolean} Whether the node is contained by a mounted container. */ function isValid(node, id) { if (node) { ("production" !== "development" ? invariant( internalGetID(node) === id, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME ) : invariant(internalGetID(node) === id)); var container = ReactMount.findReactContainerForID(id); if (container && containsNode(container, node)) { return true; } } return false; } /** * Causes the cache to forget about one React-specific ID. * * @param {string} id The ID to forget. */ function purgeID(id) { delete nodeCache[id]; } var deepestNodeSoFar = null; function findDeepestCachedAncestorImpl(ancestorID) { var ancestor = nodeCache[ancestorID]; if (ancestor && isValid(ancestor, ancestorID)) { deepestNodeSoFar = ancestor; } else { // This node isn't populated in the cache, so presumably none of its // descendants are. Break out of the loop. return false; } } /** * Return the deepest cached node whose ID is a prefix of `targetID`. */ function findDeepestCachedAncestor(targetID) { deepestNodeSoFar = null; ReactInstanceHandles.traverseAncestors( targetID, findDeepestCachedAncestorImpl ); var foundNode = deepestNodeSoFar; deepestNodeSoFar = null; return foundNode; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode( componentInstance, rootID, container, transaction, shouldReuseMarkup) { var markup = ReactReconciler.mountComponent( componentInstance, rootID, transaction, emptyObject ); componentInstance._isTopLevel = true; ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode( componentInstance, rootID, container, shouldReuseMarkup) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); transaction.perform( mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup ); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * Mounting is the process of initializing a React component by creating its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { /** Exposed for debugging purposes **/ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function(container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function( prevComponent, nextElement, container, callback) { if ("production" !== "development") { ReactElementValidator.checkAndWarnForMutatedProps(nextElement); } ReactMount.scrollMonitor(container, function() { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); if ("production" !== "development") { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container); } return prevComponent; }, /** * Register a component into the instance map and starts scroll value * monitoring * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @return {string} reactRoot ID prefix */ _registerComponent: function(nextComponent, container) { ("production" !== "development" ? invariant( container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ), '_registerComponent(...): Target container is not a DOM element.' ) : invariant(container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ))); ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var reactRootID = ReactMount.registerContainer(container); instancesByReactRootID[reactRootID] = nextComponent; return reactRootID; }, /** * Render a new component into the DOM. * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function( nextElement, container, shouldReuseMarkup ) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. ("production" !== "development" ? warning( ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); var componentInstance = instantiateReactComponent(nextElement, null); var reactRootID = ReactMount._registerComponent( componentInstance, container ); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates( batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup ); if ("production" !== "development") { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); } return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function(nextElement, container, callback) { ("production" !== "development" ? invariant( ReactElement.isValidElement(nextElement), 'React.render(): Invalid component element.%s', ( typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : typeof nextElement === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '' ) ) : invariant(ReactElement.isValidElement(nextElement))); var prevComponent = instancesByReactRootID[getReactRootID(container)]; if (prevComponent) { var prevElement = prevComponent._currentElement; if (shouldUpdateReactComponent(prevElement, nextElement)) { return ReactMount._updateRootComponent( prevComponent, nextElement, container, callback ).getPublicInstance(); } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && ReactMount.isRenderedByReact(reactRootElement); if ("production" !== "development") { if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (ReactMount.isRenderedByReact(rootElementSibling)) { ("production" !== "development" ? warning( false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.' ) : null); break; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent; var component = ReactMount._renderNewRootComponent( nextElement, container, shouldReuseMarkup ).getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Constructs a component instance of `constructor` with `initialProps` and * renders it into the supplied `container`. * * @param {function} constructor React component constructor. * @param {?object} props Initial props of the component instance. * @param {DOMElement} container DOM element to render into. * @return {ReactComponent} Component instance rendered in `container`. */ constructAndRenderComponent: function(constructor, props, container) { var element = ReactElement.createElement(constructor, props); return ReactMount.render(element, container); }, /** * Constructs a component instance of `constructor` with `initialProps` and * renders it into a container node identified by supplied `id`. * * @param {function} componentConstructor React component constructor * @param {?object} props Initial props of the component instance. * @param {string} id ID of the DOM element to render into. * @return {ReactComponent} Component instance rendered in the container node. */ constructAndRenderComponentByID: function(constructor, props, id) { var domNode = document.getElementById(id); ("production" !== "development" ? invariant( domNode, 'Tried to get element with id of "%s" but it is not present on the page.', id ) : invariant(domNode)); return ReactMount.constructAndRenderComponent(constructor, props, domNode); }, /** * Registers a container node into which React components will be rendered. * This also creates the "reactRoot" ID that will be assigned to the element * rendered within. * * @param {DOMElement} container DOM element to register as a container. * @return {string} The "reactRoot" ID of elements rendered within. */ registerContainer: function(container) { var reactRootID = getReactRootID(container); if (reactRootID) { // If one exists, make sure it is a valid "reactRoot" ID. reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID); } if (!reactRootID) { // No valid "reactRoot" ID found, create one. reactRootID = ReactInstanceHandles.createReactRootID(); } containersByReactRootID[reactRootID] = container; return reactRootID; }, /** * Unmounts and destroys the React component rendered in the `container`. * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function(container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) ("production" !== "development" ? warning( ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function of ' + 'props and state; triggering nested component updates from render is ' + 'not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); ("production" !== "development" ? invariant( container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ), 'unmountComponentAtNode(...): Target container is not a DOM element.' ) : invariant(container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ))); var reactRootID = getReactRootID(container); var component = instancesByReactRootID[reactRootID]; if (!component) { return false; } ReactMount.unmountComponentFromNode(component, container); delete instancesByReactRootID[reactRootID]; delete containersByReactRootID[reactRootID]; if ("production" !== "development") { delete rootElementsByReactRootID[reactRootID]; } return true; }, /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ unmountComponentFromNode: function(instance, container) { ReactReconciler.unmountComponent(instance); if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } }, /** * Finds the container DOM element that contains React component to which the * supplied DOM `id` belongs. * * @param {string} id The ID of an element rendered by a React component. * @return {?DOMElement} DOM element that contains the `id`. */ findReactContainerForID: function(id) { var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id); var container = containersByReactRootID[reactRootID]; if ("production" !== "development") { var rootElement = rootElementsByReactRootID[reactRootID]; if (rootElement && rootElement.parentNode !== container) { ("production" !== "development" ? invariant( // Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.' ) : invariant(// Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID)); var containerChild = container.firstChild; if (containerChild && reactRootID === internalGetID(containerChild)) { // If the container has a new child with the same ID as the old // root element, then rootElementsByReactRootID[reactRootID] is // just stale and needs to be updated. The case that deserves a // warning is when the container is empty. rootElementsByReactRootID[reactRootID] = containerChild; } else { ("production" !== "development" ? warning( false, 'ReactMount: Root element has been removed from its original ' + 'container. New container:', rootElement.parentNode ) : null); } } } return container; }, /** * Finds an element rendered by React with the supplied ID. * * @param {string} id ID of a DOM node in the React component. * @return {DOMElement} Root DOM node of the React component. */ findReactNodeByID: function(id) { var reactRoot = ReactMount.findReactContainerForID(id); return ReactMount.findComponentRoot(reactRoot, id); }, /** * True if the supplied `node` is rendered by React. * * @param {*} node DOM Element to check. * @return {boolean} True if the DOM Element appears to be rendered by React. * @internal */ isRenderedByReact: function(node) { if (node.nodeType !== 1) { // Not a DOMElement, therefore not a React component return false; } var id = ReactMount.getID(node); return id ? id.charAt(0) === SEPARATOR : false; }, /** * Traverses up the ancestors of the supplied node to find a node that is a * DOM representation of a React component. * * @param {*} node * @return {?DOMEventTarget} * @internal */ getFirstReactDOM: function(node) { var current = node; while (current && current.parentNode !== current) { if (ReactMount.isRenderedByReact(current)) { return current; } current = current.parentNode; } return null; }, /** * Finds a node with the supplied `targetID` inside of the supplied * `ancestorNode`. Exploits the ID naming scheme to perform the search * quickly. * * @param {DOMEventTarget} ancestorNode Search from this root. * @pararm {string} targetID ID of the DOM representation of the component. * @return {DOMEventTarget} DOM node with the supplied `targetID`. * @internal */ findComponentRoot: function(ancestorNode, targetID) { var firstChildren = findComponentRootReusableArray; var childIndex = 0; var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode; firstChildren[0] = deepestAncestor.firstChild; firstChildren.length = 1; while (childIndex < firstChildren.length) { var child = firstChildren[childIndex++]; var targetChild; while (child) { var childID = ReactMount.getID(child); if (childID) { // Even if we find the node we're looking for, we finish looping // through its siblings to ensure they're cached so that we don't have // to revisit this node again. Otherwise, we make n^2 calls to getID // when visiting the many children of a single node in order. if (targetID === childID) { targetChild = child; } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) { // If we find a child whose ID is an ancestor of the given ID, // then we can be sure that we only want to search the subtree // rooted at this child, so we can throw out the rest of the // search state. firstChildren.length = childIndex = 0; firstChildren.push(child.firstChild); } } else { // If this child had no ID, then there's a chance that it was // injected automatically by the browser, as when a `<table>` // element sprouts an extra `<tbody>` child as a side effect of // `.innerHTML` parsing. Optimistically continue down this // branch, but not before examining the other siblings. firstChildren.push(child.firstChild); } child = child.nextSibling; } if (targetChild) { // Emptying firstChildren/findComponentRootReusableArray is // not necessary for correctness, but it helps the GC reclaim // any nodes that were left at the end of the search. firstChildren.length = 0; return targetChild; } } firstChildren.length = 0; ("production" !== "development" ? invariant( false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode) ) : invariant(false)); }, _mountImageIntoNode: function(markup, container, shouldReuseMarkup) { ("production" !== "development" ? invariant( container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ), 'mountComponentIntoNode(...): Target container is not valid.' ) : invariant(container && ( (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE) ))); if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { return; } else { var checksum = rootElement.getAttribute( ReactMarkupChecksum.CHECKSUM_ATTR_NAME ); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute( ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum ); var diffIndex = firstDifferenceIndex(markup, rootMarkup); var difference = ' (client) ' + markup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); ("production" !== "development" ? invariant( container.nodeType !== DOC_NODE_TYPE, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference ) : invariant(container.nodeType !== DOC_NODE_TYPE)); if ("production" !== "development") { ("production" !== "development" ? warning( false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference ) : null); } } } ("production" !== "development" ? invariant( container.nodeType !== DOC_NODE_TYPE, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See React.renderToString() for server rendering.' ) : invariant(container.nodeType !== DOC_NODE_TYPE)); setInnerHTML(container, markup); }, /** * React ID utilities. */ getReactRootID: getReactRootID, getID: getID, setID: setID, getNode: getNode, getNodeFromInstance: getNodeFromInstance, purgeID: purgeID }; ReactPerf.measureMethods(ReactMount, 'ReactMount', { _renderNewRootComponent: '_renderNewRootComponent', _mountImageIntoNode: '_mountImageIntoNode' }); module.exports = ReactMount; },{"100":100,"11":11,"123":123,"130":130,"144":144,"149":149,"150":150,"164":164,"167":167,"171":171,"33":33,"45":45,"63":63,"64":64,"65":65,"72":72,"73":73,"76":76,"82":82,"89":89,"99":99}],78:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChild * @typechecks static-only */ 'use strict'; var ReactComponentEnvironment = _dereq_(41); var ReactMultiChildUpdateTypes = _dereq_(79); var ReactReconciler = _dereq_(89); var ReactChildReconciler = _dereq_(36); /** * Updating children of a component may trigger recursive updates. The depth is * used to batch recursive updates to render markup more efficiently. * * @type {number} * @private */ var updateDepth = 0; /** * Queue of update configuration objects. * * Each object has a `type` property that is in `ReactMultiChildUpdateTypes`. * * @type {array<object>} * @private */ var updateQueue = []; /** * Queue of markup to be rendered. * * @type {array<string>} * @private */ var markupQueue = []; /** * Enqueues markup to be rendered and inserted at a supplied index. * * @param {string} parentID ID of the parent component. * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function enqueueMarkup(parentID, markup, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.INSERT_MARKUP, markupIndex: markupQueue.push(markup) - 1, textContent: null, fromIndex: null, toIndex: toIndex }); } /** * Enqueues moving an existing element to another index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function enqueueMove(parentID, fromIndex, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.MOVE_EXISTING, markupIndex: null, textContent: null, fromIndex: fromIndex, toIndex: toIndex }); } /** * Enqueues removing an element at an index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Index of the element to remove. * @private */ function enqueueRemove(parentID, fromIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.REMOVE_NODE, markupIndex: null, textContent: null, fromIndex: fromIndex, toIndex: null }); } /** * Enqueues setting the text content. * * @param {string} parentID ID of the parent component. * @param {string} textContent Text content to set. * @private */ function enqueueTextContent(parentID, textContent) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.TEXT_CONTENT, markupIndex: null, textContent: textContent, fromIndex: null, toIndex: null }); } /** * Processes any enqueued updates. * * @private */ function processQueue() { if (updateQueue.length) { ReactComponentEnvironment.processChildrenUpdates( updateQueue, markupQueue ); clearQueue(); } } /** * Clears any enqueued updates. * * @private */ function clearQueue() { updateQueue.length = 0; markupQueue.length = 0; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function(nestedChildren, transaction, context) { var children = ReactChildReconciler.instantiateChildren( nestedChildren, transaction, context ); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = ReactReconciler.mountComponent( child, rootID, transaction, context ); child._mountIndex = index; mountImages.push(mountImage); index++; } } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function(nextContent) { updateDepth++; var errorThrown = true; try { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren); // TODO: The setTextContent operation should be enough for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { this._unmountChildByName(prevChildren[name], name); } } // Set new text content. this.setTextContent(nextContent); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildren Nested child maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function(nextNestedChildren, transaction, context) { updateDepth++; var errorThrown = true; try { this._updateChildren(nextNestedChildren, transaction, context); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Improve performance by isolating this hot code path from the try/catch * block in `updateChildren`. * * @param {?object} nextNestedChildren Nested child maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function(nextNestedChildren, transaction, context) { var prevChildren = this._renderedChildren; var nextChildren = ReactChildReconciler.updateChildren( prevChildren, nextNestedChildren, transaction, context ); this._renderedChildren = nextChildren; if (!nextChildren && !prevChildren) { return; } var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var lastIndex = 0; var nextIndex = 0; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { this.moveChild(prevChild, nextIndex, lastIndex); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); this._unmountChildByName(prevChild, name); } // The child must be instantiated before it's mounted. this._mountChildByNameAtIndex( nextChild, name, nextIndex, transaction, context ); } nextIndex++; } // Remove children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { this._unmountChildByName(prevChildren[name], name); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @internal */ unmountChildren: function() { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function(child, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { enqueueMove(this._rootNodeID, child._mountIndex, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function(child, mountImage) { enqueueMarkup(this._rootNodeID, mountImage, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function(child) { enqueueRemove(this._rootNodeID, child._mountIndex); }, /** * Sets this text content string. * * @param {string} textContent Text content to set. * @protected */ setTextContent: function(textContent) { enqueueTextContent(this._rootNodeID, textContent); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildByNameAtIndex: function( child, name, index, transaction, context) { // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = ReactReconciler.mountComponent( child, rootID, transaction, context ); child._mountIndex = index; this.createChild(child, mountImage); }, /** * Unmounts a rendered child by name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @param {string} name Name of the child in `this._renderedChildren`. * @private */ _unmountChildByName: function(child, name) { this.removeChild(child); child._mountIndex = null; } } }; module.exports = ReactMultiChild; },{"36":36,"41":41,"79":79,"89":89}],79:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChildUpdateTypes */ 'use strict'; var keyMirror = _dereq_(156); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; },{"156":156}],80:[function(_dereq_,module,exports){ /** * 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 ReactNativeComponent */ 'use strict'; var assign = _dereq_(29); var invariant = _dereq_(150); var autoGenerateWrapperClass = null; var genericComponentClass = null; // This registry keeps track of wrapper classes around native tags var tagToComponentClass = {}; var textComponentClass = null; var ReactNativeComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function(componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function(componentClass) { textComponentClass = componentClass; }, // This accepts a keyed object with classes as values. Each key represents a // tag. That particular tag will use this class instead of the generic one. injectComponentClasses: function(componentClasses) { assign(tagToComponentClass, componentClasses); }, // Temporary hack since we expect DOM refs to behave like composites, // for this release. injectAutoWrapper: function(wrapperFactory) { autoGenerateWrapperClass = wrapperFactory; } }; /** * Get a composite component wrapper class for a specific tag. * * @param {ReactElement} element The tag for which to get the class. * @return {function} The React class constructor function. */ function getComponentClassForElement(element) { if (typeof element.type === 'function') { return element.type; } var tag = element.type; var componentClass = tagToComponentClass[tag]; if (componentClass == null) { tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag); } return componentClass; } /** * Get a native internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { ("production" !== "development" ? invariant( genericComponentClass, 'There is no registered component for the tag %s', element.type ) : invariant(genericComponentClass)); return new genericComponentClass(element.type, element.props); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactNativeComponent = { getComponentClassForElement: getComponentClassForElement, createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactNativeComponentInjection }; module.exports = ReactNativeComponent; },{"150":150,"29":29}],81:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactOwner */ 'use strict'; var invariant = _dereq_(150); /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ isValidOwner: function(object) { return !!( (object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function') ); }, /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function(component, ref, owner) { ("production" !== "development" ? invariant( ReactOwner.isValidOwner(owner), 'addComponentAsRefTo(...): Only a ReactOwner can have refs. This ' + 'usually means that you\'re trying to add a ref to a component that ' + 'doesn\'t have an owner (that is, was not created inside of another ' + 'component\'s `render` method). Try rendering this component inside of ' + 'a new top-level component which will hold the ref.' ) : invariant(ReactOwner.isValidOwner(owner))); owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function(component, ref, owner) { ("production" !== "development" ? invariant( ReactOwner.isValidOwner(owner), 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This ' + 'usually means that you\'re trying to remove a ref to a component that ' + 'doesn\'t have an owner (that is, was not created inside of another ' + 'component\'s `render` method). Try rendering this component inside of ' + 'a new top-level component which will hold the ref.' ) : invariant(ReactOwner.isValidOwner(owner))); // Check that `component` is still the current ref because we do not want to // detach the ref if another component stole it. if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; },{"150":150}],82:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPerf * @typechecks static-only */ 'use strict'; /** * ReactPerf is a general AOP system designed to measure performance. This * module only has the hooks: see ReactDefaultPerf for the analysis tool. */ var ReactPerf = { /** * Boolean to enable/disable measurement. Set to false by default to prevent * accidental logging and perf loss. */ enableMeasure: false, /** * Holds onto the measure function in use. By default, don't measure * anything, but we'll override this if we inject a measure function. */ storedMeasure: _noMeasure, /** * @param {object} object * @param {string} objectName * @param {object<string>} methodNames */ measureMethods: function(object, objectName, methodNames) { if ("production" !== "development") { for (var key in methodNames) { if (!methodNames.hasOwnProperty(key)) { continue; } object[key] = ReactPerf.measure( objectName, methodNames[key], object[key] ); } } }, /** * Use this to wrap methods you want to measure. Zero overhead in production. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ measure: function(objName, fnName, func) { if ("production" !== "development") { var measuredFunc = null; var wrapper = function() { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; wrapper.displayName = objName + '_' + fnName; return wrapper; } return func; }, injection: { /** * @param {function} measure */ injectMeasure: function(measure) { ReactPerf.storedMeasure = measure; } } }; /** * Simply passes through the measured function, without measuring it. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ function _noMeasure(objName, fnName, func) { return func; } module.exports = ReactPerf; },{}],83:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTransferer */ 'use strict'; var assign = _dereq_(29); var emptyFunction = _dereq_(129); var joinClasses = _dereq_(155); /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return assign({}, b, a); }); /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { return transferInto(assign({}, oldProps), newProps); } }; module.exports = ReactPropTransferer; },{"129":129,"155":155,"29":29}],84:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocationNames */ 'use strict'; var ReactPropTypeLocationNames = {}; if ("production" !== "development") { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; },{}],85:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocations */ 'use strict'; var keyMirror = _dereq_(156); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; },{"156":156}],86:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypes */ 'use strict'; var ReactElement = _dereq_(63); var ReactFragment = _dereq_(69); var ReactPropTypeLocationNames = _dereq_(84); var emptyFunction = _dereq_(129); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var elementTypeChecker = createElementTypeChecker(); var nodeTypeChecker = createNodeChecker(); var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: elementTypeChecker, instanceOf: createInstanceTypeChecker, node: nodeTypeChecker, objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location) { componentName = componentName || ANONYMOUS; if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { return new Error( ("Required " + locationName + " `" + propName + "` was not specified in ") + ("`" + componentName + "`.") ); } return null; } else { return validate(props, propName, componentName, location); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new Error( ("Invalid " + locationName + " `" + propName + "` of type `" + preciseType + "` ") + ("supplied to `" + componentName + "`, expected `" + expectedType + "`.") ); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location) { var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new Error( ("Invalid " + locationName + " `" + propName + "` of type ") + ("`" + propType + "` supplied to `" + componentName + "`, expected an array.") ); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location) { if (!ReactElement.isValidElement(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected a ReactElement.") ); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected instance of `" + expectedClassName + "`.") ); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { function validate(props, propName, componentName, location) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (propValue === expectedValues[i]) { return null; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new Error( ("Invalid " + locationName + " `" + propName + "` of value `" + propValue + "` ") + ("supplied to `" + componentName + "`, expected one of " + valuesString + ".") ); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` of type ") + ("`" + propType + "` supplied to `" + componentName + "`, expected an object.") ); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { function validate(props, propName, componentName, location) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`.") ); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` supplied to ") + ("`" + componentName + "`, expected a ReactNode.") ); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error( ("Invalid " + locationName + " `" + propName + "` of type `" + propType + "` ") + ("supplied to `" + componentName + "`, expected `object`.") ); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } propValue = ReactFragment.extractIfFragment(propValue); for (var k in propValue) { if (!isNode(propValue[k])) { return false; } } return true; default: return false; } } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } module.exports = ReactPropTypes; },{"129":129,"63":63,"69":69,"84":84}],87:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPutListenerQueue */ 'use strict'; var PooledClass = _dereq_(30); var ReactBrowserEventEmitter = _dereq_(33); var assign = _dereq_(29); function ReactPutListenerQueue() { this.listenersToPut = []; } assign(ReactPutListenerQueue.prototype, { enqueuePutListener: function(rootNodeID, propKey, propValue) { this.listenersToPut.push({ rootNodeID: rootNodeID, propKey: propKey, propValue: propValue }); }, putListeners: function() { for (var i = 0; i < this.listenersToPut.length; i++) { var listenerToPut = this.listenersToPut[i]; ReactBrowserEventEmitter.putListener( listenerToPut.rootNodeID, listenerToPut.propKey, listenerToPut.propValue ); } }, reset: function() { this.listenersToPut.length = 0; }, destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(ReactPutListenerQueue); module.exports = ReactPutListenerQueue; },{"29":29,"30":30,"33":33}],88:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconcileTransaction * @typechecks static-only */ 'use strict'; var CallbackQueue = _dereq_(7); var PooledClass = _dereq_(30); var ReactBrowserEventEmitter = _dereq_(33); var ReactInputSelection = _dereq_(71); var ReactPutListenerQueue = _dereq_(87); var Transaction = _dereq_(116); var assign = _dereq_(29); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function() { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occured. `close` * restores the previous value. */ close: function(previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function() { this.reactMountReady.notifyAll(); } }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: function() { this.putListenerQueue.putListeners(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ PUT_LISTENER_QUEUEING, SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING ]; /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction() { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap proceedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function() { return this.reactMountReady; }, getPutListenerQueue: function() { return this.putListenerQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be resused. */ destructor: function() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; },{"116":116,"29":29,"30":30,"33":33,"7":7,"71":71,"87":87}],89:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconciler */ 'use strict'; var ReactRef = _dereq_(90); var ReactElementValidator = _dereq_(64); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function(internalInstance, rootID, transaction, context) { var markup = internalInstance.mountComponent(rootID, transaction, context); if ("production" !== "development") { ReactElementValidator.checkAndWarnForMutatedProps( internalInstance._currentElement ); } transaction.getReactMountReady().enqueue(attachRefs, internalInstance); return markup; }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function(internalInstance) { ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(); }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function( internalInstance, nextElement, transaction, context ) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && nextElement._owner != null) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. return; } if ("production" !== "development") { ReactElementValidator.checkAndWarnForMutatedProps(nextElement); } var refsChanged = ReactRef.shouldUpdateRefs( prevElement, nextElement ); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function( internalInstance, transaction ) { internalInstance.performUpdateIfNecessary(transaction); } }; module.exports = ReactReconciler; },{"64":64,"90":90}],90:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRef */ 'use strict'; var ReactOwner = _dereq_(81); var ReactRef = {}; function attachRef(ref, component, owner) { if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function(instance, element) { var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function(prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. return ( nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref ); }; ReactRef.detachRefs = function(instance, element) { var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; },{"81":81}],91:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRootIndex * @typechecks */ 'use strict'; var ReactRootIndexInjection = { /** * @param {function} _createReactRootIndex */ injectCreateReactRootIndex: function(_createReactRootIndex) { ReactRootIndex.createReactRootIndex = _createReactRootIndex; } }; var ReactRootIndex = { createReactRootIndex: null, injection: ReactRootIndexInjection }; module.exports = ReactRootIndex; },{}],92:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only * @providesModule ReactServerRendering */ 'use strict'; var ReactElement = _dereq_(63); var ReactInstanceHandles = _dereq_(72); var ReactMarkupChecksum = _dereq_(76); var ReactServerRenderingTransaction = _dereq_(93); var emptyObject = _dereq_(130); var instantiateReactComponent = _dereq_(149); var invariant = _dereq_(150); /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToString(element) { ("production" !== "development" ? invariant( ReactElement.isValidElement(element), 'renderToString(): You must pass a valid ReactElement.' ) : invariant(ReactElement.isValidElement(element))); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(false); return transaction.perform(function() { var componentInstance = instantiateReactComponent(element, null); var markup = componentInstance.mountComponent(id, transaction, emptyObject); return ReactMarkupChecksum.addChecksumToMarkup(markup); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } } /** * @param {ReactElement} element * @return {string} the HTML markup, without the extra React ID and checksum * (for generating static pages) */ function renderToStaticMarkup(element) { ("production" !== "development" ? invariant( ReactElement.isValidElement(element), 'renderToStaticMarkup(): You must pass a valid ReactElement.' ) : invariant(ReactElement.isValidElement(element))); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(true); return transaction.perform(function() { var componentInstance = instantiateReactComponent(element, null); return componentInstance.mountComponent(id, transaction, emptyObject); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } } module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; },{"130":130,"149":149,"150":150,"63":63,"72":72,"76":76,"93":93}],93:[function(_dereq_,module,exports){ /** * 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 ReactServerRenderingTransaction * @typechecks */ 'use strict'; var PooledClass = _dereq_(30); var CallbackQueue = _dereq_(7); var ReactPutListenerQueue = _dereq_(87); var Transaction = _dereq_(116); var assign = _dereq_(29); var emptyFunction = _dereq_(129); /** * Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks * during the performing of the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, close: emptyFunction }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: emptyFunction }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ PUT_LISTENER_QUEUEING, ON_DOM_READY_QUEUEING ]; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.reactMountReady = CallbackQueue.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap proceedures. */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function() { return this.reactMountReady; }, getPutListenerQueue: function() { return this.putListenerQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be resused. */ destructor: function() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; assign( ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin ); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; },{"116":116,"129":129,"29":29,"30":30,"7":7,"87":87}],94:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactStateSetters */ 'use strict'; var ReactStateSetters = { /** * Returns a function that calls the provided function, and uses the result * of that to set the component's state. * * @param {ReactCompositeComponent} component * @param {function} funcReturningState Returned callback uses this to * determine how to update state. * @return {function} callback that when invoked uses funcReturningState to * determined the object literal to setState. */ createStateSetter: function(component, funcReturningState) { return function(a, b, c, d, e, f) { var partialState = funcReturningState.call(component, a, b, c, d, e, f); if (partialState) { component.setState(partialState); } }; }, /** * Returns a single-argument callback that can be used to update a single * key in the component's state. * * Note: this is memoized function, which makes it inexpensive to call. * * @param {ReactCompositeComponent} component * @param {string} key The key in the state that you should update. * @return {function} callback of 1 argument which calls setState() with * the provided keyName and callback argument. */ createStateKeySetter: function(component, key) { // Memoize the setters. var cache = component.__keySetters || (component.__keySetters = {}); return cache[key] || (cache[key] = createStateKeySetter(component, key)); } }; function createStateKeySetter(component, key) { // Partial state is allocated outside of the function closure so it can be // reused with every call, avoiding memory allocation when this function // is called. var partialState = {}; return function stateKeySetter(value) { partialState[key] = value; component.setState(partialState); }; } ReactStateSetters.Mixin = { /** * Returns a function that calls the provided function, and uses the result * of that to set the component's state. * * For example, these statements are equivalent: * * this.setState({x: 1}); * this.createStateSetter(function(xValue) { * return {x: xValue}; * })(1); * * @param {function} funcReturningState Returned callback uses this to * determine how to update state. * @return {function} callback that when invoked uses funcReturningState to * determined the object literal to setState. */ createStateSetter: function(funcReturningState) { return ReactStateSetters.createStateSetter(this, funcReturningState); }, /** * Returns a single-argument callback that can be used to update a single * key in the component's state. * * For example, these statements are equivalent: * * this.setState({x: 1}); * this.createStateKeySetter('x')(1); * * Note: this is memoized function, which makes it inexpensive to call. * * @param {string} key The key in the state that you should update. * @return {function} callback of 1 argument which calls setState() with * the provided keyName and callback argument. */ createStateKeySetter: function(key) { return ReactStateSetters.createStateKeySetter(this, key); } }; module.exports = ReactStateSetters; },{}],95:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTestUtils */ 'use strict'; var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(18); var EventPropagators = _dereq_(21); var React = _dereq_(31); var ReactElement = _dereq_(63); var ReactEmptyComponent = _dereq_(65); var ReactBrowserEventEmitter = _dereq_(33); var ReactCompositeComponent = _dereq_(43); var ReactInstanceHandles = _dereq_(72); var ReactInstanceMap = _dereq_(73); var ReactMount = _dereq_(77); var ReactUpdates = _dereq_(100); var SyntheticEvent = _dereq_(108); var assign = _dereq_(29); var emptyObject = _dereq_(130); var topLevelTypes = EventConstants.topLevelTypes; function Event(suffix) {} /** * @class ReactTestUtils */ /** * Todo: Support the entire DOM.scry query syntax. For now, these simple * utilities will suffice for testing purposes. * @lends ReactTestUtils */ var ReactTestUtils = { renderIntoDocument: function(instance) { var div = document.createElement('div'); // None of our tests actually require attaching the container to the // DOM, and doing so creates a mess that we rely on test isolation to // clean up, so we're going to stop honoring the name of this method // (and probably rename it eventually) if no problems arise. // document.documentElement.appendChild(div); return React.render(instance, div); }, isElement: function(element) { return ReactElement.isValidElement(element); }, isElementOfType: function(inst, convenienceConstructor) { return ( ReactElement.isValidElement(inst) && inst.type === convenienceConstructor ); }, isDOMComponent: function(inst) { // TODO: Fix this heuristic. It's just here because composites can currently // pretend to be DOM components. return !!(inst && inst.tagName && inst.getDOMNode); }, isDOMComponentElement: function(inst) { return !!(inst && ReactElement.isValidElement(inst) && !!inst.tagName); }, isCompositeComponent: function(inst) { return typeof inst.render === 'function' && typeof inst.setState === 'function'; }, isCompositeComponentWithType: function(inst, type) { return !!(ReactTestUtils.isCompositeComponent(inst) && (inst.constructor === type)); }, isCompositeComponentElement: function(inst) { if (!ReactElement.isValidElement(inst)) { return false; } // We check the prototype of the type that will get mounted, not the // instance itself. This is a future proof way of duck typing. var prototype = inst.type.prototype; return ( typeof prototype.render === 'function' && typeof prototype.setState === 'function' ); }, isCompositeComponentElementWithType: function(inst, type) { return !!(ReactTestUtils.isCompositeComponentElement(inst) && (inst.constructor === type)); }, getRenderedChildOfCompositeComponent: function(inst) { if (!ReactTestUtils.isCompositeComponent(inst)) { return null; } var internalInstance = ReactInstanceMap.get(inst); return internalInstance._renderedComponent.getPublicInstance(); }, findAllInRenderedTree: function(inst, test) { if (!inst) { return []; } var ret = test(inst) ? [inst] : []; if (ReactTestUtils.isDOMComponent(inst)) { var internalInstance = ReactInstanceMap.get(inst); var renderedChildren = internalInstance ._renderedComponent ._renderedChildren; var key; for (key in renderedChildren) { if (!renderedChildren.hasOwnProperty(key)) { continue; } if (!renderedChildren[key].getPublicInstance) { continue; } ret = ret.concat( ReactTestUtils.findAllInRenderedTree( renderedChildren[key].getPublicInstance(), test ) ); } } else if (ReactTestUtils.isCompositeComponent(inst)) { ret = ret.concat( ReactTestUtils.findAllInRenderedTree( ReactTestUtils.getRenderedChildOfCompositeComponent(inst), test ) ); } return ret; }, /** * Finds all instance of components in the rendered tree that are DOM * components with the class name matching `className`. * @return an array of all the matches. */ scryRenderedDOMComponentsWithClass: function(root, className) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { var instClassName = inst.props.className; return ReactTestUtils.isDOMComponent(inst) && ( (instClassName && (' ' + instClassName + ' ').indexOf(' ' + className + ' ') !== -1) ); }); }, /** * Like scryRenderedDOMComponentsWithClass but expects there to be one result, * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactDOMComponent} The one match. */ findRenderedDOMComponentWithClass: function(root, className) { var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className); if (all.length !== 1) { throw new Error('Did not find exactly one match ' + '(found: ' + all.length + ') for class:' + className ); } return all[0]; }, /** * Finds all instance of components in the rendered tree that are DOM * components with the tag name matching `tagName`. * @return an array of all the matches. */ scryRenderedDOMComponentsWithTag: function(root, tagName) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { return ReactTestUtils.isDOMComponent(inst) && inst.tagName === tagName.toUpperCase(); }); }, /** * Like scryRenderedDOMComponentsWithTag but expects there to be one result, * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactDOMComponent} The one match. */ findRenderedDOMComponentWithTag: function(root, tagName) { var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName); if (all.length !== 1) { throw new Error('Did not find exactly one match for tag:' + tagName); } return all[0]; }, /** * Finds all instances of components with type equal to `componentType`. * @return an array of all the matches. */ scryRenderedComponentsWithType: function(root, componentType) { return ReactTestUtils.findAllInRenderedTree(root, function(inst) { return ReactTestUtils.isCompositeComponentWithType( inst, componentType ); }); }, /** * Same as `scryRenderedComponentsWithType` but expects there to be one result * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactComponent} The one match. */ findRenderedComponentWithType: function(root, componentType) { var all = ReactTestUtils.scryRenderedComponentsWithType( root, componentType ); if (all.length !== 1) { throw new Error( 'Did not find exactly one match for componentType:' + componentType ); } return all[0]; }, /** * Pass a mocked component module to this method to augment it with * useful methods that allow it to be used as a dummy React component. * Instead of rendering as usual, the component will become a simple * <div> containing any provided children. * * @param {object} module the mock function object exported from a * module that defines the component to be mocked * @param {?string} mockTagName optional dummy root tag name to return * from render method (overrides * module.mockTagName if provided) * @return {object} the ReactTestUtils object (for chaining) */ mockComponent: function(module, mockTagName) { mockTagName = mockTagName || module.mockTagName || "div"; module.prototype.render.mockImplementation(function() { return React.createElement( mockTagName, null, this.props.children ); }); return this; }, /** * Simulates a top level event being dispatched from a raw event that occured * on an `Element` node. * @param topLevelType {Object} A type from `EventConstants.topLevelTypes` * @param {!Element} node The dom to simulate an event occurring on. * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. */ simulateNativeEventOnNode: function(topLevelType, node, fakeNativeEvent) { fakeNativeEvent.target = node; ReactBrowserEventEmitter.ReactEventListener.dispatchEvent( topLevelType, fakeNativeEvent ); }, /** * Simulates a top level event being dispatched from a raw event that occured * on the `ReactDOMComponent` `comp`. * @param topLevelType {Object} A type from `EventConstants.topLevelTypes`. * @param comp {!ReactDOMComponent} * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. */ simulateNativeEventOnDOMComponent: function( topLevelType, comp, fakeNativeEvent) { ReactTestUtils.simulateNativeEventOnNode( topLevelType, comp.getDOMNode(), fakeNativeEvent ); }, nativeTouchData: function(x, y) { return { touches: [ {pageX: x, pageY: y} ] }; }, createRenderer: function() { return new ReactShallowRenderer(); }, Simulate: null, SimulateNative: {} }; /** * @class ReactShallowRenderer */ var ReactShallowRenderer = function() { this._instance = null; }; ReactShallowRenderer.prototype.getRenderOutput = function() { return ( (this._instance && this._instance._renderedComponent && this._instance._renderedComponent._renderedOutput) || null ); }; var NoopInternalComponent = function(element) { this._renderedOutput = element; this._currentElement = element === null || element === false ? ReactEmptyComponent.emptyElement : element; }; NoopInternalComponent.prototype = { mountComponent: function() { }, receiveComponent: function(element) { this._renderedOutput = element; this._currentElement = element === null || element === false ? ReactEmptyComponent.emptyElement : element; }, unmountComponent: function() { } }; var ShallowComponentWrapper = function() { }; assign( ShallowComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _instantiateReactComponent: function(element) { return new NoopInternalComponent(element); }, _replaceNodeWithMarkupByID: function() {}, _renderValidatedComponent: ReactCompositeComponent.Mixin. _renderValidatedComponentWithoutOwnerOrContext } ); ReactShallowRenderer.prototype.render = function(element, context) { if (!context) { context = emptyObject; } var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); this._render(element, transaction, context); ReactUpdates.ReactReconcileTransaction.release(transaction); }; ReactShallowRenderer.prototype.unmount = function() { if (this._instance) { this._instance.unmountComponent(); } }; ReactShallowRenderer.prototype._render = function(element, transaction, context) { if (!this._instance) { var rootID = ReactInstanceHandles.createReactRootID(); var instance = new ShallowComponentWrapper(element.type); instance.construct(element); instance.mountComponent(rootID, transaction, context); this._instance = instance; } else { this._instance.receiveComponent(element, transaction, context); } }; /** * Exports: * * - `ReactTestUtils.Simulate.click(Element/ReactDOMComponent)` * - `ReactTestUtils.Simulate.mouseMove(Element/ReactDOMComponent)` * - `ReactTestUtils.Simulate.change(Element/ReactDOMComponent)` * - ... (All keys from event plugin `eventTypes` objects) */ function makeSimulator(eventType) { return function(domComponentOrNode, eventData) { var node; if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { node = domComponentOrNode.getDOMNode(); } else if (domComponentOrNode.tagName) { node = domComponentOrNode; } var fakeNativeEvent = new Event(); fakeNativeEvent.target = node; // We don't use SyntheticEvent.getPooled in order to not have to worry about // properly destroying any properties assigned from `eventData` upon release var event = new SyntheticEvent( ReactBrowserEventEmitter.eventNameDispatchConfigs[eventType], ReactMount.getID(node), fakeNativeEvent ); assign(event, eventData); EventPropagators.accumulateTwoPhaseDispatches(event); ReactUpdates.batchedUpdates(function() { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(); }); }; } function buildSimulators() { ReactTestUtils.Simulate = {}; var eventType; for (eventType in ReactBrowserEventEmitter.eventNameDispatchConfigs) { /** * @param {!Element || ReactDOMComponent} domComponentOrNode * @param {?object} eventData Fake event data to use in SyntheticEvent. */ ReactTestUtils.Simulate[eventType] = makeSimulator(eventType); } } // Rebuild ReactTestUtils.Simulate whenever event plugins are injected var oldInjectEventPluginOrder = EventPluginHub.injection.injectEventPluginOrder; EventPluginHub.injection.injectEventPluginOrder = function() { oldInjectEventPluginOrder.apply(this, arguments); buildSimulators(); }; var oldInjectEventPlugins = EventPluginHub.injection.injectEventPluginsByName; EventPluginHub.injection.injectEventPluginsByName = function() { oldInjectEventPlugins.apply(this, arguments); buildSimulators(); }; buildSimulators(); /** * Exports: * * - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)` * - ... (All keys from `EventConstants.topLevelTypes`) * * Note: Top level event types are a subset of the entire set of handler types * (which include a broader set of "synthetic" events). For example, onDragDone * is a synthetic event. Except when testing an event plugin or React's event * handling code specifically, you probably want to use ReactTestUtils.Simulate * to dispatch synthetic events. */ function makeNativeSimulator(eventType) { return function(domComponentOrNode, nativeEventData) { var fakeNativeEvent = new Event(eventType); assign(fakeNativeEvent, nativeEventData); if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { ReactTestUtils.simulateNativeEventOnDOMComponent( eventType, domComponentOrNode, fakeNativeEvent ); } else if (!!domComponentOrNode.tagName) { // Will allow on actual dom nodes. ReactTestUtils.simulateNativeEventOnNode( eventType, domComponentOrNode, fakeNativeEvent ); } }; } var eventType; for (eventType in topLevelTypes) { // Event type is stored as 'topClick' - we transform that to 'click' var convenienceName = eventType.indexOf('top') === 0 ? eventType.charAt(3).toLowerCase() + eventType.substr(4) : eventType; /** * @param {!Element || ReactDOMComponent} domComponentOrNode * @param {?Event} nativeEventData Fake native event to use in SyntheticEvent. */ ReactTestUtils.SimulateNative[convenienceName] = makeNativeSimulator(eventType); } module.exports = ReactTestUtils; },{"100":100,"108":108,"130":130,"16":16,"18":18,"21":21,"29":29,"31":31,"33":33,"43":43,"63":63,"65":65,"72":72,"73":73,"77":77}],96:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only * @providesModule ReactTransitionChildMapping */ 'use strict'; var ReactChildren = _dereq_(37); var ReactFragment = _dereq_(69); var ReactTransitionChildMapping = { /** * Given `this.props.children`, return an object mapping key to child. Just * simple syntactic sugar around ReactChildren.map(). * * @param {*} children `this.props.children` * @return {object} Mapping of key to child */ getChildMapping: function(children) { if (!children) { return children; } return ReactFragment.extract(ReactChildren.map(children, function(child) { return child; })); }, /** * When you're adding or removing children some may be added or removed in the * same render pass. We want to show *both* since we want to simultaneously * animate elements in and out. This function takes a previous set of keys * and a new set of keys and merges them with its best guess of the correct * ordering. In the future we may expose some of the utilities in * ReactMultiChild to make this easy, but for now React itself does not * directly have this concept of the union of prevChildren and nextChildren * so we implement it here. * * @param {object} prev prev children as returned from * `ReactTransitionChildMapping.getChildMapping()`. * @param {object} next next children as returned from * `ReactTransitionChildMapping.getChildMapping()`. * @return {object} a key set that contains all keys in `prev` and all keys * in `next` in a reasonable order. */ mergeChildMappings: function(prev, next) { prev = prev || {}; next = next || {}; function getValueForKey(key) { if (next.hasOwnProperty(key)) { return next[key]; } else { return prev[key]; } } // For each key of `next`, the list of keys to insert before that key in // the combined list var nextKeysPending = {}; var pendingKeys = []; for (var prevKey in prev) { if (next.hasOwnProperty(prevKey)) { if (pendingKeys.length) { nextKeysPending[prevKey] = pendingKeys; pendingKeys = []; } } else { pendingKeys.push(prevKey); } } var i; var childMapping = {}; for (var nextKey in next) { if (nextKeysPending.hasOwnProperty(nextKey)) { for (i = 0; i < nextKeysPending[nextKey].length; i++) { var pendingNextKey = nextKeysPending[nextKey][i]; childMapping[nextKeysPending[nextKey][i]] = getValueForKey( pendingNextKey ); } } childMapping[nextKey] = getValueForKey(nextKey); } // Finally, add the keys which didn't appear before any key in `next` for (i = 0; i < pendingKeys.length; i++) { childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]); } return childMapping; } }; module.exports = ReactTransitionChildMapping; },{"37":37,"69":69}],97:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionEvents */ 'use strict'; var ExecutionEnvironment = _dereq_(22); /** * EVENT_NAME_MAP is used to determine which event fired when a * transition/animation ends, based on the style property used to * define that event. */ var EVENT_NAME_MAP = { transitionend: { 'transition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'mozTransitionEnd', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd' }, animationend: { 'animation': 'animationend', 'WebkitAnimation': 'webkitAnimationEnd', 'MozAnimation': 'mozAnimationEnd', 'OAnimation': 'oAnimationEnd', 'msAnimation': 'MSAnimationEnd' } }; var endEvents = []; function detectEvents() { var testEl = document.createElement('div'); var style = testEl.style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are useable, and if not remove them // from the map if (!('AnimationEvent' in window)) { delete EVENT_NAME_MAP.animationend.animation; } if (!('TransitionEvent' in window)) { delete EVENT_NAME_MAP.transitionend.transition; } for (var baseEventName in EVENT_NAME_MAP) { var baseEvents = EVENT_NAME_MAP[baseEventName]; for (var styleName in baseEvents) { if (styleName in style) { endEvents.push(baseEvents[styleName]); break; } } } } if (ExecutionEnvironment.canUseDOM) { detectEvents(); } // We use the raw {add|remove}EventListener() call because EventListener // does not know how to remove event listeners and we really should // clean up. Also, these events are not triggered in older browsers // so we should be A-OK here. function addEventListener(node, eventName, eventListener) { node.addEventListener(eventName, eventListener, false); } function removeEventListener(node, eventName, eventListener) { node.removeEventListener(eventName, eventListener, false); } var ReactTransitionEvents = { addEndEventListener: function(node, eventListener) { if (endEvents.length === 0) { // If CSS transitions are not supported, trigger an "end animation" // event immediately. window.setTimeout(eventListener, 0); return; } endEvents.forEach(function(endEvent) { addEventListener(node, endEvent, eventListener); }); }, removeEndEventListener: function(node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function(endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; module.exports = ReactTransitionEvents; },{"22":22}],98:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionGroup */ 'use strict'; var React = _dereq_(31); var ReactTransitionChildMapping = _dereq_(96); var assign = _dereq_(29); var cloneWithProps = _dereq_(122); var emptyFunction = _dereq_(129); var ReactTransitionGroup = React.createClass({ displayName: 'ReactTransitionGroup', propTypes: { component: React.PropTypes.any, childFactory: React.PropTypes.func }, getDefaultProps: function() { return { component: 'span', childFactory: emptyFunction.thatReturnsArgument }; }, getInitialState: function() { return { children: ReactTransitionChildMapping.getChildMapping(this.props.children) }; }, componentWillMount: function() { this.currentlyTransitioningKeys = {}; this.keysToEnter = []; this.keysToLeave = []; }, componentDidMount: function() { var initialChildMapping = this.state.children; for (var key in initialChildMapping) { if (initialChildMapping[key]) { this.performAppear(key); } } }, componentWillReceiveProps: function(nextProps) { var nextChildMapping = ReactTransitionChildMapping.getChildMapping( nextProps.children ); var prevChildMapping = this.state.children; this.setState({ children: ReactTransitionChildMapping.mergeChildMappings( prevChildMapping, nextChildMapping ) }); var key; for (key in nextChildMapping) { var hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key); if (nextChildMapping[key] && !hasPrev && !this.currentlyTransitioningKeys[key]) { this.keysToEnter.push(key); } } for (key in prevChildMapping) { var hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key); if (prevChildMapping[key] && !hasNext && !this.currentlyTransitioningKeys[key]) { this.keysToLeave.push(key); } } // If we want to someday check for reordering, we could do it here. }, componentDidUpdate: function() { var keysToEnter = this.keysToEnter; this.keysToEnter = []; keysToEnter.forEach(this.performEnter); var keysToLeave = this.keysToLeave; this.keysToLeave = []; keysToLeave.forEach(this.performLeave); }, performAppear: function(key) { this.currentlyTransitioningKeys[key] = true; var component = this.refs[key]; if (component.componentWillAppear) { component.componentWillAppear( this._handleDoneAppearing.bind(this, key) ); } else { this._handleDoneAppearing(key); } }, _handleDoneAppearing: function(key) { var component = this.refs[key]; if (component.componentDidAppear) { component.componentDidAppear(); } delete this.currentlyTransitioningKeys[key]; var currentChildMapping = ReactTransitionChildMapping.getChildMapping( this.props.children ); if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) { // This was removed before it had fully appeared. Remove it. this.performLeave(key); } }, performEnter: function(key) { this.currentlyTransitioningKeys[key] = true; var component = this.refs[key]; if (component.componentWillEnter) { component.componentWillEnter( this._handleDoneEntering.bind(this, key) ); } else { this._handleDoneEntering(key); } }, _handleDoneEntering: function(key) { var component = this.refs[key]; if (component.componentDidEnter) { component.componentDidEnter(); } delete this.currentlyTransitioningKeys[key]; var currentChildMapping = ReactTransitionChildMapping.getChildMapping( this.props.children ); if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) { // This was removed before it had fully entered. Remove it. this.performLeave(key); } }, performLeave: function(key) { this.currentlyTransitioningKeys[key] = true; var component = this.refs[key]; if (component.componentWillLeave) { component.componentWillLeave(this._handleDoneLeaving.bind(this, key)); } else { // Note that this is somewhat dangerous b/c it calls setState() // again, effectively mutating the component before all the work // is done. this._handleDoneLeaving(key); } }, _handleDoneLeaving: function(key) { var component = this.refs[key]; if (component.componentDidLeave) { component.componentDidLeave(); } delete this.currentlyTransitioningKeys[key]; var currentChildMapping = ReactTransitionChildMapping.getChildMapping( this.props.children ); if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) { // This entered again before it fully left. Add it again. this.performEnter(key); } else { var newChildren = assign({}, this.state.children); delete newChildren[key]; this.setState({children: newChildren}); } }, render: function() { // TODO: we could get rid of the need for the wrapper node // by cloning a single child var childrenToRender = []; for (var key in this.state.children) { var child = this.state.children[key]; if (child) { // You may need to apply reactive updates to a child as it is leaving. // The normal React way to do it won't work since the child will have // already been removed. In case you need this behavior you can provide // a childFactory function to wrap every child, even the ones that are // leaving. childrenToRender.push(cloneWithProps( this.props.childFactory(child), {ref: key, key: key} )); } } return React.createElement( this.props.component, this.props, childrenToRender ); } }); module.exports = ReactTransitionGroup; },{"122":122,"129":129,"29":29,"31":31,"96":96}],99:[function(_dereq_,module,exports){ /** * 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 ReactUpdateQueue */ 'use strict'; var ReactLifeCycle = _dereq_(74); var ReactCurrentOwner = _dereq_(45); var ReactElement = _dereq_(63); var ReactInstanceMap = _dereq_(73); var ReactUpdates = _dereq_(100); var assign = _dereq_(29); var invariant = _dereq_(150); var warning = _dereq_(171); function enqueueUpdate(internalInstance) { if (internalInstance !== ReactLifeCycle.currentlyMountingInstance) { // If we're in a componentWillMount handler, don't enqueue a rerender // because ReactUpdates assumes we're in a browser context (which is // wrong for server rendering) and we're about to do a render anyway. // See bug in #1740. ReactUpdates.enqueueUpdate(internalInstance); } } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { ("production" !== "development" ? invariant( ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName ) : invariant(ReactCurrentOwner.current == null)); var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if ("production" !== "development") { // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. ("production" !== "development" ? warning( !callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted ' + 'component. This is a no-op.', callerName, callerName ) : null); } return null; } if (internalInstance === ReactLifeCycle.currentlyUnmountingInstance) { return null; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function(publicInstance, callback) { ("production" !== "development" ? invariant( typeof callback === 'function', 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.' ) : invariant(typeof callback === 'function')); var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. if (!internalInstance || internalInstance === ReactLifeCycle.currentlyMountingInstance) { return null; } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. enqueueUpdate(internalInstance); }, enqueueCallbackInternal: function(internalInstance, callback) { ("production" !== "development" ? invariant( typeof callback === 'function', 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.' ) : invariant(typeof callback === 'function')); if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldUpdateComponent`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function(publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate( publicInstance, 'forceUpdate' ); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function(publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate( publicInstance, 'replaceState' ); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function(publicInstance, partialState) { var internalInstance = getInternalInstanceReadyForUpdate( publicInstance, 'setState' ); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, /** * Sets a subset of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialProps Subset of the next props. * @internal */ enqueueSetProps: function(publicInstance, partialProps) { var internalInstance = getInternalInstanceReadyForUpdate( publicInstance, 'setProps' ); if (!internalInstance) { return; } ("production" !== "development" ? invariant( internalInstance._isTopLevel, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.' ) : invariant(internalInstance._isTopLevel)); // Merge with the pending element if it exists, otherwise with existing // element props. var element = internalInstance._pendingElement || internalInstance._currentElement; var props = assign({}, element.props, partialProps); internalInstance._pendingElement = ReactElement.cloneAndReplaceProps( element, props ); enqueueUpdate(internalInstance); }, /** * Replaces all of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} props New props. * @internal */ enqueueReplaceProps: function(publicInstance, props) { var internalInstance = getInternalInstanceReadyForUpdate( publicInstance, 'replaceProps' ); if (!internalInstance) { return; } ("production" !== "development" ? invariant( internalInstance._isTopLevel, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.' ) : invariant(internalInstance._isTopLevel)); // Merge with the pending element if it exists, otherwise with existing // element props. var element = internalInstance._pendingElement || internalInstance._currentElement; internalInstance._pendingElement = ReactElement.cloneAndReplaceProps( element, props ); enqueueUpdate(internalInstance); }, enqueueElementInternal: function(internalInstance, newElement) { internalInstance._pendingElement = newElement; enqueueUpdate(internalInstance); } }; module.exports = ReactUpdateQueue; },{"100":100,"150":150,"171":171,"29":29,"45":45,"63":63,"73":73,"74":74}],100:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdates */ 'use strict'; var CallbackQueue = _dereq_(7); var PooledClass = _dereq_(30); var ReactCurrentOwner = _dereq_(45); var ReactPerf = _dereq_(82); var ReactReconciler = _dereq_(89); var Transaction = _dereq_(116); var assign = _dereq_(29); var invariant = _dereq_(150); var warning = _dereq_(171); var dirtyComponents = []; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { ("production" !== "development" ? invariant( ReactUpdates.ReactReconcileTransaction && batchingStrategy, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy' ) : invariant(ReactUpdates.ReactReconcileTransaction && batchingStrategy)); } var NESTED_UPDATES = { initialize: function() { this.dirtyComponentsLength = dirtyComponents.length; }, close: function() { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function() { this.callbackQueue.reset(); }, close: function() { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(); } assign( ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, destructor: function() { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function(method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call( this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a ); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d) { ensureInjected(); batchingStrategy.batchedUpdates(callback, a, b, c, d); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; ("production" !== "development" ? invariant( len === dirtyComponents.length, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length ) : invariant(len === dirtyComponents.length)); // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; ReactReconciler.performUpdateIfNecessary( component, transaction.reconcileTransaction ); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue( callbacks[j], component.getPublicInstance() ); } } } } var flushBatchedUpdates = function() { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }; flushBatchedUpdates = ReactPerf.measure( 'ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates ); /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) ("production" !== "development" ? warning( ReactCurrentOwner.current == null, 'enqueueUpdate(): Render methods should be a pure function of props ' + 'and state; triggering nested component updates from render is not ' + 'allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate.' ) : null); if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { ("production" !== "development" ? invariant( batchingStrategy.isBatchingUpdates, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.' ) : invariant(batchingStrategy.isBatchingUpdates)); asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function(ReconcileTransaction) { ("production" !== "development" ? invariant( ReconcileTransaction, 'ReactUpdates: must provide a reconcile transaction class' ) : invariant(ReconcileTransaction)); ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function(_batchingStrategy) { ("production" !== "development" ? invariant( _batchingStrategy, 'ReactUpdates: must provide a batching strategy' ) : invariant(_batchingStrategy)); ("production" !== "development" ? invariant( typeof _batchingStrategy.batchedUpdates === 'function', 'ReactUpdates: must provide a batchedUpdates() function' ) : invariant(typeof _batchingStrategy.batchedUpdates === 'function')); ("production" !== "development" ? invariant( typeof _batchingStrategy.isBatchingUpdates === 'boolean', 'ReactUpdates: must provide an isBatchingUpdates boolean attribute' ) : invariant(typeof _batchingStrategy.isBatchingUpdates === 'boolean')); batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; },{"116":116,"150":150,"171":171,"29":29,"30":30,"45":45,"7":7,"82":82,"89":89}],101:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SVGDOMPropertyConfig */ /*jslint bitwise: true*/ 'use strict'; var DOMProperty = _dereq_(11); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var SVGDOMPropertyConfig = { Properties: { clipPath: MUST_USE_ATTRIBUTE, cx: MUST_USE_ATTRIBUTE, cy: MUST_USE_ATTRIBUTE, d: MUST_USE_ATTRIBUTE, dx: MUST_USE_ATTRIBUTE, dy: MUST_USE_ATTRIBUTE, fill: MUST_USE_ATTRIBUTE, fillOpacity: MUST_USE_ATTRIBUTE, fontFamily: MUST_USE_ATTRIBUTE, fontSize: MUST_USE_ATTRIBUTE, fx: MUST_USE_ATTRIBUTE, fy: MUST_USE_ATTRIBUTE, gradientTransform: MUST_USE_ATTRIBUTE, gradientUnits: MUST_USE_ATTRIBUTE, markerEnd: MUST_USE_ATTRIBUTE, markerMid: MUST_USE_ATTRIBUTE, markerStart: MUST_USE_ATTRIBUTE, offset: MUST_USE_ATTRIBUTE, opacity: MUST_USE_ATTRIBUTE, patternContentUnits: MUST_USE_ATTRIBUTE, patternUnits: MUST_USE_ATTRIBUTE, points: MUST_USE_ATTRIBUTE, preserveAspectRatio: MUST_USE_ATTRIBUTE, r: MUST_USE_ATTRIBUTE, rx: MUST_USE_ATTRIBUTE, ry: MUST_USE_ATTRIBUTE, spreadMethod: MUST_USE_ATTRIBUTE, stopColor: MUST_USE_ATTRIBUTE, stopOpacity: MUST_USE_ATTRIBUTE, stroke: MUST_USE_ATTRIBUTE, strokeDasharray: MUST_USE_ATTRIBUTE, strokeLinecap: MUST_USE_ATTRIBUTE, strokeOpacity: MUST_USE_ATTRIBUTE, strokeWidth: MUST_USE_ATTRIBUTE, textAnchor: MUST_USE_ATTRIBUTE, transform: MUST_USE_ATTRIBUTE, version: MUST_USE_ATTRIBUTE, viewBox: MUST_USE_ATTRIBUTE, x1: MUST_USE_ATTRIBUTE, x2: MUST_USE_ATTRIBUTE, x: MUST_USE_ATTRIBUTE, y1: MUST_USE_ATTRIBUTE, y2: MUST_USE_ATTRIBUTE, y: MUST_USE_ATTRIBUTE }, DOMAttributeNames: { clipPath: 'clip-path', fillOpacity: 'fill-opacity', fontFamily: 'font-family', fontSize: 'font-size', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', patternContentUnits: 'patternContentUnits', patternUnits: 'patternUnits', preserveAspectRatio: 'preserveAspectRatio', spreadMethod: 'spreadMethod', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strokeDasharray: 'stroke-dasharray', strokeLinecap: 'stroke-linecap', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', viewBox: 'viewBox' } }; module.exports = SVGDOMPropertyConfig; },{"11":11}],102:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SelectEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(21); var ReactInputSelection = _dereq_(71); var SyntheticEvent = _dereq_(108); var getActiveElement = _dereq_(136); var isTextInputElement = _dereq_(153); var keyOf = _dereq_(157); var shallowEqual = _dereq_(166); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({onSelect: null}), captured: keyOf({onSelectCapture: null}) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange ] } }; var activeElement = null; var activeElementID = null; var lastSelection = null; var mouseDown = false; /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @param {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled( eventTypes.select, activeElementID, nativeEvent ); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') { activeElement = topLevelTarget; activeElementID = topLevelTargetID; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementID = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. case topLevelTypes.topSelectionChange: case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent); } } }; module.exports = SelectEventPlugin; },{"108":108,"136":136,"153":153,"157":157,"16":16,"166":166,"21":21,"71":71}],103:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ServerReactRootIndex * @typechecks */ 'use strict'; /** * Size of the reactRoot ID space. We generate random numbers for React root * IDs and if there's a collision the events and DOM update system will * get confused. In the future we need a way to generate GUIDs but for * now this will work on a smaller scale. */ var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53); var ServerReactRootIndex = { createReactRootIndex: function() { return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX); } }; module.exports = ServerReactRootIndex; },{}],104:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SimpleEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPluginUtils = _dereq_(20); var EventPropagators = _dereq_(21); var SyntheticClipboardEvent = _dereq_(105); var SyntheticEvent = _dereq_(108); var SyntheticFocusEvent = _dereq_(109); var SyntheticKeyboardEvent = _dereq_(111); var SyntheticMouseEvent = _dereq_(112); var SyntheticDragEvent = _dereq_(107); var SyntheticTouchEvent = _dereq_(113); var SyntheticUIEvent = _dereq_(114); var SyntheticWheelEvent = _dereq_(115); var getEventCharCode = _dereq_(137); var invariant = _dereq_(150); var keyOf = _dereq_(157); var warning = _dereq_(171); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { blur: { phasedRegistrationNames: { bubbled: keyOf({onBlur: true}), captured: keyOf({onBlurCapture: true}) } }, click: { phasedRegistrationNames: { bubbled: keyOf({onClick: true}), captured: keyOf({onClickCapture: true}) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({onContextMenu: true}), captured: keyOf({onContextMenuCapture: true}) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({onCopy: true}), captured: keyOf({onCopyCapture: true}) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({onCut: true}), captured: keyOf({onCutCapture: true}) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({onDoubleClick: true}), captured: keyOf({onDoubleClickCapture: true}) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({onDrag: true}), captured: keyOf({onDragCapture: true}) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({onDragEnd: true}), captured: keyOf({onDragEndCapture: true}) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({onDragEnter: true}), captured: keyOf({onDragEnterCapture: true}) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({onDragExit: true}), captured: keyOf({onDragExitCapture: true}) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({onDragLeave: true}), captured: keyOf({onDragLeaveCapture: true}) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({onDragOver: true}), captured: keyOf({onDragOverCapture: true}) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({onDragStart: true}), captured: keyOf({onDragStartCapture: true}) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({onDrop: true}), captured: keyOf({onDropCapture: true}) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({onFocus: true}), captured: keyOf({onFocusCapture: true}) } }, input: { phasedRegistrationNames: { bubbled: keyOf({onInput: true}), captured: keyOf({onInputCapture: true}) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({onKeyDown: true}), captured: keyOf({onKeyDownCapture: true}) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({onKeyPress: true}), captured: keyOf({onKeyPressCapture: true}) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({onKeyUp: true}), captured: keyOf({onKeyUpCapture: true}) } }, load: { phasedRegistrationNames: { bubbled: keyOf({onLoad: true}), captured: keyOf({onLoadCapture: true}) } }, error: { phasedRegistrationNames: { bubbled: keyOf({onError: true}), captured: keyOf({onErrorCapture: true}) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({onMouseDown: true}), captured: keyOf({onMouseDownCapture: true}) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({onMouseMove: true}), captured: keyOf({onMouseMoveCapture: true}) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({onMouseOut: true}), captured: keyOf({onMouseOutCapture: true}) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({onMouseOver: true}), captured: keyOf({onMouseOverCapture: true}) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({onMouseUp: true}), captured: keyOf({onMouseUpCapture: true}) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({onPaste: true}), captured: keyOf({onPasteCapture: true}) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({onReset: true}), captured: keyOf({onResetCapture: true}) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({onScroll: true}), captured: keyOf({onScrollCapture: true}) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({onSubmit: true}), captured: keyOf({onSubmitCapture: true}) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({onTouchCancel: true}), captured: keyOf({onTouchCancelCapture: true}) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({onTouchEnd: true}), captured: keyOf({onTouchEndCapture: true}) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({onTouchMove: true}), captured: keyOf({onTouchMoveCapture: true}) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({onTouchStart: true}), captured: keyOf({onTouchStartCapture: true}) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({onWheel: true}), captured: keyOf({onWheelCapture: true}) } } }; var topLevelEventsToDispatchConfig = { topBlur: eventTypes.blur, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSubmit: eventTypes.submit, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topWheel: eventTypes.wheel }; for (var type in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[type].dependencies = [type]; } var SimpleEventPlugin = { eventTypes: eventTypes, /** * Same as the default implementation, except cancels the event when return * value is false. This behavior will be disabled in a future release. * * @param {object} Event to be dispatched. * @param {function} Application-level callback. * @param {string} domID DOM ID to pass to the callback. */ executeDispatch: function(event, listener, domID) { var returnValue = EventPluginUtils.executeDispatch(event, listener, domID); ("production" !== "development" ? warning( typeof returnValue !== 'boolean', 'Returning `false` from an event handler is deprecated and will be ' + 'ignored in a future release. Instead, manually call ' + 'e.stopPropagation() or e.preventDefault(), as appropriate.' ) : null); if (returnValue === false) { event.stopPropagation(); event.preventDefault(); } }, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topInput: case topLevelTypes.topLoad: case topLevelTypes.topError: case topLevelTypes.topReset: case topLevelTypes.topSubmit: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyPress: // FireFox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } ("production" !== "development" ? invariant( EventConstructor, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType ) : invariant(EventConstructor)); var event = EventConstructor.getPooled( dispatchConfig, topLevelTargetID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); return event; } }; module.exports = SimpleEventPlugin; },{"105":105,"107":107,"108":108,"109":109,"111":111,"112":112,"113":113,"114":114,"115":115,"137":137,"150":150,"157":157,"16":16,"171":171,"20":20,"21":21}],105:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticClipboardEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = _dereq_(108); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function(event) { return ( 'clipboardData' in event ? event.clipboardData : window.clipboardData ); } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; },{"108":108}],106:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticCompositionEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = _dereq_(108); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent( dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass( SyntheticCompositionEvent, CompositionEventInterface ); module.exports = SyntheticCompositionEvent; },{"108":108}],107:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticDragEvent * @typechecks static-only */ 'use strict'; var SyntheticMouseEvent = _dereq_(112); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; },{"112":112}],108:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticEvent * @typechecks static-only */ 'use strict'; var PooledClass = _dereq_(30); var assign = _dereq_(29); var emptyFunction = _dereq_(129); var getEventTarget = _dereq_(140); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: getEventTarget, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function(event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. */ function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent) { this.dispatchConfig = dispatchConfig; this.dispatchMarker = dispatchMarker; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { this[propName] = nativeEvent[propName]; } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; } assign(SyntheticEvent.prototype, { preventDefault: function() { this.defaultPrevented = true; var event = this.nativeEvent; if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function() { var event = this.nativeEvent; if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function() { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function() { var Interface = this.constructor.Interface; for (var propName in Interface) { this[propName] = null; } this.dispatchConfig = null; this.dispatchMarker = null; this.nativeEvent = null; } }); SyntheticEvent.Interface = EventInterface; /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function(Class, Interface) { var Super = this; var prototype = Object.create(Super.prototype); assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.threeArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler); module.exports = SyntheticEvent; },{"129":129,"140":140,"29":29,"30":30}],109:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticFocusEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = _dereq_(114); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; },{"114":114}],110:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticInputEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = _dereq_(108); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent( dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass( SyntheticInputEvent, InputEventInterface ); module.exports = SyntheticInputEvent; },{"108":108}],111:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticKeyboardEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = _dereq_(114); var getEventCharCode = _dereq_(137); var getEventKey = _dereq_(138); var getEventModifierState = _dereq_(139); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function(event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function(event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function(event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; },{"114":114,"137":137,"138":138,"139":139}],112:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticMouseEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = _dereq_(114); var ViewportMetrics = _dereq_(117); var getEventModifierState = _dereq_(139); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function(event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function(event) { return event.relatedTarget || ( ((event.fromElement === event.srcElement ? event.toElement : event.fromElement)) ); }, // "Proprietary" Interface. pageX: function(event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function(event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; },{"114":114,"117":117,"139":139}],113:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTouchEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = _dereq_(114); var getEventModifierState = _dereq_(139); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; },{"114":114,"139":139}],114:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticUIEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = _dereq_(108); var getEventTarget = _dereq_(140); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function(event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target != null && target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function(event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; },{"108":108,"140":140}],115:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticWheelEvent * @typechecks static-only */ 'use strict'; var SyntheticMouseEvent = _dereq_(112); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function(event) { return ( 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0 ); }, deltaY: function(event) { return ( 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0 ); }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; },{"112":112}],116:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Transaction */ 'use strict'; var invariant = _dereq_(150); /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var Mixin = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function() { this.transactionWrappers = this.getTransactionWrappers(); if (!this.wrapperInitData) { this.wrapperInitData = []; } else { this.wrapperInitData.length = 0; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function() { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} args... Arguments to pass to the method (optional). * Helps prevent need to bind in many cases. * @return Return value from `method`. */ perform: function(method, scope, a, b, c, d, e, f) { ("production" !== "development" ? invariant( !this.isInTransaction(), 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.' ) : invariant(!this.isInTransaction())); var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) { } } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function(startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) { } } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function(startIndex) { ("production" !== "development" ? invariant( this.isInTransaction(), 'Transaction.closeAll(): Cannot close transaction when none are open.' ) : invariant(this.isInTransaction())); var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) { } } } } this.wrapperInitData.length = 0; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occured. */ OBSERVED_ERROR: {} }; module.exports = Transaction; },{"150":150}],117:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViewportMetrics */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function(scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; },{}],118:[function(_dereq_,module,exports){ /** * 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 accumulateInto */ 'use strict'; var invariant = _dereq_(150); /** * * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { ("production" !== "development" ? invariant( next != null, 'accumulateInto(...): Accumulated items must not be null or undefined.' ) : invariant(next != null)); if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray && nextIsArray) { current.push.apply(current, next); return current; } if (currentIsArray) { current.push(next); return current; } if (nextIsArray) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; },{"150":150}],119:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule adler32 */ /* jslint bitwise:true */ 'use strict'; var MOD = 65521; // This is a clean-room implementation of adler32 designed for detecting // if markup is not what we expect it to be. It does not need to be // cryptographically strong, only reasonably good at detecting if markup // generated on the server is different than that on the client. function adler32(data) { var a = 1; var b = 0; for (var i = 0; i < data.length; i++) { a = (a + data.charCodeAt(i)) % MOD; b = (b + a) % MOD; } return a | (b << 16); } module.exports = adler32; },{}],120:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelize * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function(_, character) { return character.toUpperCase(); }); } module.exports = camelize; },{}],121:[function(_dereq_,module,exports){ /** * 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 camelizeStyleName * @typechecks */ "use strict"; var camelize = _dereq_(120); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; },{"120":120}],122:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only * @providesModule cloneWithProps */ 'use strict'; var ReactElement = _dereq_(63); var ReactPropTransferer = _dereq_(83); var keyOf = _dereq_(157); var warning = _dereq_(171); var CHILDREN_PROP = keyOf({children: null}); /** * Sometimes you want to change the props of a child passed to you. Usually * this is to add a CSS class. * * @param {ReactElement} child child element you'd like to clone * @param {object} props props you'd like to modify. className and style will be * merged automatically. * @return {ReactElement} a clone of child with props merged in. */ function cloneWithProps(child, props) { if ("production" !== "development") { ("production" !== "development" ? warning( !child.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.' ) : null); } var newProps = ReactPropTransferer.mergeProps(props, child.props); // Use `child.props.children` if it is provided. if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { newProps.children = child.props.children; } // The current API doesn't retain _owner and _context, which is why this // doesn't use ReactElement.cloneAndReplaceProps. return ReactElement.createElement(child.type, newProps); } module.exports = cloneWithProps; },{"157":157,"171":171,"63":63,"83":83}],123:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule containsNode * @typechecks */ var isTextNode = _dereq_(154); /*jslint bitwise:true */ /** * Checks if a given DOM node contains or is another DOM node. * * @param {?DOMNode} outerNode Outer DOM node. * @param {?DOMNode} innerNode Inner DOM node. * @return {boolean} True if `outerNode` contains or is `innerNode`. */ function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if (outerNode.contains) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } module.exports = containsNode; },{"154":154}],124:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createArrayFromMixed * @typechecks */ var toArray = _dereq_(168); /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return ( // not null/false !!obj && // arrays are objects, NodeLists are functions in Safari (typeof obj == 'object' || typeof obj == 'function') && // quacks like an array ('length' in obj) && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 (typeof obj.nodeType != 'number') && ( // a real array (// HTMLCollection/NodeList (Array.isArray(obj) || // arguments ('callee' in obj) || 'item' in obj)) ) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; },{"168":168}],125:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createFullPageComponent * @typechecks */ 'use strict'; // Defeat circular references by requiring this directly. var ReactClass = _dereq_(38); var ReactElement = _dereq_(63); var invariant = _dereq_(150); /** * Create a component that will throw an exception when unmounted. * * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. * * @param {string} tag The tag to wrap * @return {function} convenience constructor of new component */ function createFullPageComponent(tag) { var elementFactory = ReactElement.createFactory(tag); var FullPageComponent = ReactClass.createClass({ tagName: tag.toUpperCase(), displayName: 'ReactFullPageComponent' + tag, componentWillUnmount: function() { ("production" !== "development" ? invariant( false, '%s tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, <head>, ' + 'and <body>) reliably and efficiently. To fix this, have a single ' + 'top-level component that never unmounts render these elements.', this.constructor.displayName ) : invariant(false)); }, render: function() { return elementFactory(this.props); } }); return FullPageComponent; } module.exports = createFullPageComponent; },{"150":150,"38":38,"63":63}],126:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createNodesFromMarkup * @typechecks */ /*jslint evil: true, sub: true */ var ExecutionEnvironment = _dereq_(22); var createArrayFromMixed = _dereq_(124); var getMarkupWrap = _dereq_(142); var invariant = _dereq_(150); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; ("production" !== "development" ? invariant(!!dummyNode, 'createNodesFromMarkup dummy not initialized') : invariant(!!dummyNode)); var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { ("production" !== "development" ? invariant( handleScript, 'createNodesFromMarkup(...): Unexpected <script> element rendered.' ) : invariant(handleScript)); createArrayFromMixed(scripts).forEach(handleScript); } var nodes = createArrayFromMixed(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; },{"124":124,"142":142,"150":150,"22":22}],127:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule cx */ /** * This function is used to mark string literals representing CSS class names * so that they can be transformed statically. This allows for modularization * and minification of CSS class names. * * In static_upstream, this function is actually implemented, but it should * eventually be replaced with something more descriptive, and the transform * that is used in the main stack should be ported for use elsewhere. * * @param string|object className to modularize, or an object of key/values. * In the object case, the values are conditions that * determine if the className keys should be included. * @param [string ...] Variable list of classNames in the string case. * @return string Renderable space-separated CSS className. */ 'use strict'; var warning = _dereq_(171); var warned = false; function cx(classNames) { if ("production" !== "development") { ("production" !== "development" ? warning( warned, 'React.addons.classSet will be deprecated in a future version. See ' + 'http://fb.me/react-addons-classset' ) : null); warned = true; } if (typeof classNames == 'object') { return Object.keys(classNames).filter(function(className) { return classNames[className]; }).join(' '); } else { return Array.prototype.join.call(arguments, ' '); } } module.exports = cx; },{"171":171}],128:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule dangerousStyleValue * @typechecks static-only */ 'use strict'; var CSSProperty = _dereq_(5); var isUnitlessNumber = CSSProperty.isUnitlessNumber; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; },{"5":5}],129:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @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; },{}],130:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyObject */ "use strict"; var emptyObject = {}; if ("production" !== "development") { Object.freeze(emptyObject); } module.exports = emptyObject; },{}],131:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule escapeTextContentForBrowser */ 'use strict'; var ESCAPE_LOOKUP = { '&': '&amp;', '>': '&gt;', '<': '&lt;', '"': '&quot;', '\'': '&#x27;' }; var ESCAPE_REGEX = /[&><"']/g; function escaper(match) { return ESCAPE_LOOKUP[match]; } /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { return ('' + text).replace(ESCAPE_REGEX, escaper); } module.exports = escapeTextContentForBrowser; },{}],132:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule findDOMNode * @typechecks static-only */ 'use strict'; var ReactCurrentOwner = _dereq_(45); var ReactInstanceMap = _dereq_(73); var ReactMount = _dereq_(77); var invariant = _dereq_(150); var isNode = _dereq_(152); var warning = _dereq_(171); /** * Returns the DOM node rendered by this element. * * @param {ReactComponent|DOMElement} componentOrElement * @return {DOMElement} The root node of this element. */ function findDOMNode(componentOrElement) { if ("production" !== "development") { var owner = ReactCurrentOwner.current; if (owner !== null) { ("production" !== "development" ? warning( owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component' ) : null); owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (isNode(componentOrElement)) { return componentOrElement; } if (ReactInstanceMap.has(componentOrElement)) { return ReactMount.getNodeFromInstance(componentOrElement); } ("production" !== "development" ? invariant( componentOrElement.render == null || typeof componentOrElement.render !== 'function', 'Component (with keys: %s) contains `render` method ' + 'but is not mounted in the DOM', Object.keys(componentOrElement) ) : invariant(componentOrElement.render == null || typeof componentOrElement.render !== 'function')); ("production" !== "development" ? invariant( false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement) ) : invariant(false)); } module.exports = findDOMNode; },{"150":150,"152":152,"171":171,"45":45,"73":73,"77":77}],133:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule flattenChildren */ 'use strict'; var traverseAllChildren = _dereq_(169); var warning = _dereq_(171); /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. */ function flattenSingleChildIntoContext(traverseContext, child, name) { // We found a component instance. var result = traverseContext; var keyUnique = !result.hasOwnProperty(name); if ("production" !== "development") { ("production" !== "development" ? warning( keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name ) : null); } if (keyUnique && child != null) { result[name] = child; } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children) { if (children == null) { return children; } var result = {}; traverseAllChildren(children, flattenSingleChildIntoContext, result); return result; } module.exports = flattenChildren; },{"169":169,"171":171}],134:[function(_dereq_,module,exports){ /** * 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 focusNode */ "use strict"; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch(e) { } } module.exports = focusNode; },{}],135:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule forEachAccumulated */ 'use strict'; /** * @param {array} an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ var forEachAccumulated = function(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }; module.exports = forEachAccumulated; },{}],136:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getActiveElement * @typechecks */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document body is not yet defined. */ function getActiveElement() /*?DOMElement*/ { try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; },{}],137:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventCharCode * @typechecks static-only */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {string} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; },{}],138:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventKey * @typechecks static-only */ 'use strict'; var getEventCharCode = _dereq_(137); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', 144: 'NumLock', 145: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; },{"137":137}],139:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventModifierState * @typechecks static-only */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { /*jshint validthis:true */ var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; },{}],140:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventTarget * @typechecks static-only */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; },{}],141:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getIteratorFn * @typechecks static-only */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && ( (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]) ); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; },{}],142:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getMarkupWrap */ var ExecutionEnvironment = _dereq_(22); var invariant = _dereq_(150); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = { // Force wrapping for SVG elements because if they get created inside a <div>, // they will be initialized in the wrong namespace (and will not display). 'circle': true, 'clipPath': true, 'defs': true, 'ellipse': true, 'g': true, 'line': true, 'linearGradient': true, 'path': true, 'polygon': true, 'polyline': true, 'radialGradient': true, 'rect': true, 'stop': true, 'text': true }; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg>', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap, 'circle': svgWrap, 'clipPath': svgWrap, 'defs': svgWrap, 'ellipse': svgWrap, 'g': svgWrap, 'line': svgWrap, 'linearGradient': svgWrap, 'path': svgWrap, 'polygon': svgWrap, 'polyline': svgWrap, 'radialGradient': svgWrap, 'rect': svgWrap, 'stop': svgWrap, 'text': svgWrap }; /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { ("production" !== "development" ? invariant(!!dummyNode, 'Markup wrapping node not initialized') : invariant(!!dummyNode)); if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; },{"150":150,"22":22}],143:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getNodeForCharacterOffset */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; },{}],144:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getReactRootElementInContainer */ 'use strict'; var DOC_NODE_TYPE = 9; /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } module.exports = getReactRootElementInContainer; },{}],145:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getTextContentAccessor */ 'use strict'; var ExecutionEnvironment = _dereq_(22); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; },{"22":22}],146:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getUnboundedScrollPosition * @typechecks */ "use strict"; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; },{}],147:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenate * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; },{}],148:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenateStyleName * @typechecks */ "use strict"; var hyphenate = _dereq_(147); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; },{"147":147}],149:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule instantiateReactComponent * @typechecks static-only */ 'use strict'; var ReactCompositeComponent = _dereq_(43); var ReactEmptyComponent = _dereq_(65); var ReactNativeComponent = _dereq_(80); var assign = _dereq_(29); var invariant = _dereq_(150); var warning = _dereq_(171); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function() { }; assign( ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _instantiateReactComponent: instantiateReactComponent } ); /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return ( typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function' ); } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @param {*} parentCompositeType The composite type that resolved this. * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node, parentCompositeType) { var instance; if (node === null || node === false) { node = ReactEmptyComponent.emptyElement; } if (typeof node === 'object') { var element = node; if ("production" !== "development") { ("production" !== "development" ? warning( element && (typeof element.type === 'function' || typeof element.type === 'string'), 'Only functions or strings can be mounted as React components.' ) : null); } // Special case string values if (parentCompositeType === element.type && typeof element.type === 'string') { // Avoid recursion if the wrapper renders itself. instance = ReactNativeComponent.createInternalComponent(element); // All native components are currently wrapped in a composite so we're // safe to assume that this is what we should instantiate. } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // represenations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); } else { instance = new ReactCompositeComponentWrapper(); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactNativeComponent.createInstanceForText(node); } else { ("production" !== "development" ? invariant( false, 'Encountered invalid React node of type %s', typeof node ) : invariant(false)); } if ("production" !== "development") { ("production" !== "development" ? warning( typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.' ) : null); } // Sets up the instance. This can probably just move into the constructor now. instance.construct(node); // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if ("production" !== "development") { instance._isOwnerNecessary = false; instance._warnedAboutRefsInRender = false; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if ("production" !== "development") { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; },{"150":150,"171":171,"29":29,"43":43,"65":65,"80":80}],150:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ "use strict"; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if ("production" !== "development") { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( 'Invariant Violation: ' + format.replace(/%s/g, function() { return args[argIndex++]; }) ); } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; },{}],151:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ 'use strict'; var ExecutionEnvironment = _dereq_(22); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; },{"22":22}],152:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isNode * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && ( ((typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')) )); } module.exports = isNode; },{}],153:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextInputElement */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { return elem && ( (elem.nodeName === 'INPUT' && supportedInputTypes[elem.type] || elem.nodeName === 'TEXTAREA') ); } module.exports = isTextInputElement; },{}],154:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextNode * @typechecks */ var isNode = _dereq_(152); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; },{"152":152}],155:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule joinClasses * @typechecks static-only */ 'use strict'; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} classes * @return {string} */ function joinClasses(className/*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; },{}],156:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyMirror * @typechecks static-only */ 'use strict'; var invariant = _dereq_(150); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function(obj) { var ret = {}; var key; ("production" !== "development" ? invariant( obj instanceof Object && !Array.isArray(obj), 'keyMirror(...): Argument must be an object.' ) : invariant(obj instanceof Object && !Array.isArray(obj))); for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; },{"150":150}],157:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; },{}],158:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule mapObject */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Executes the provided `callback` once for each enumerable own property in the * object and constructs a new object from the results. The `callback` is * invoked with three arguments: * * - the property value * - the property name * - the object being traversed * * Properties that are added after the call to `mapObject` will not be visited * by `callback`. If the values of existing properties are changed, the value * passed to `callback` will be the value at the time `mapObject` visits them. * Properties that are deleted before being visited are not visited. * * @grep function objectMap() * @grep function objMap() * * @param {?object} object * @param {function} callback * @param {*} context * @return {?object} */ function mapObject(object, callback, context) { if (!object) { return null; } var result = {}; for (var name in object) { if (hasOwnProperty.call(object, name)) { result[name] = callback.call(context, object[name], name, object); } } return result; } module.exports = mapObject; },{}],159:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule memoizeStringOnly * @typechecks static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeStringOnly(callback) { var cache = {}; return function(string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; },{}],160:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule onlyChild */ 'use strict'; var ReactElement = _dereq_(63); var invariant = _dereq_(150); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. The current implementation of this * function assumes that a single child gets passed without a wrapper, but the * purpose of this helper function is to abstract away the particular structure * of children. * * @param {?object} children Child collection structure. * @return {ReactComponent} The first and only `ReactComponent` contained in the * structure. */ function onlyChild(children) { ("production" !== "development" ? invariant( ReactElement.isValidElement(children), 'onlyChild must be passed a children with exactly one child.' ) : invariant(ReactElement.isValidElement(children))); return children; } module.exports = onlyChild; },{"150":150,"63":63}],161:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performance * @typechecks */ "use strict"; var ExecutionEnvironment = _dereq_(22); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; },{"22":22}],162:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performanceNow * @typechecks */ var performance = _dereq_(161); /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (!performance || !performance.now) { performance = Date; } var performanceNow = performance.now.bind(performance); module.exports = performanceNow; },{"161":161}],163:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule quoteAttributeValueForBrowser */ 'use strict'; var escapeTextContentForBrowser = _dereq_(131); /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } module.exports = quoteAttributeValueForBrowser; },{"131":131}],164:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setInnerHTML */ /* globals MSApp */ 'use strict'; var ExecutionEnvironment = _dereq_(22); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = function(node, html) { node.innerHTML = html; }; // Win8 apps: Allow all html to be inserted if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { setInnerHTML = function(node, html) { MSApp.execUnsafeLocalFunction(function() { node.innerHTML = html; }); }; } if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function(node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. node.innerHTML = '\uFEFF' + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } } module.exports = setInnerHTML; },{"22":22}],165:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setTextContent */ 'use strict'; var ExecutionEnvironment = _dereq_(22); var escapeTextContentForBrowser = _dereq_(131); var setInnerHTML = _dereq_(164); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function(node, text) { node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function(node, text) { setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; },{"131":131,"164":164,"22":22}],166:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual */ 'use strict'; /** * Performs equality by iterating through keys on an object and returning * false when any key has values which are not strictly equal between * objA and objB. Returns true when the values of all keys are strictly equal. * * @return {boolean} */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } var key; // Test for A's keys different from B. for (key in objA) { if (objA.hasOwnProperty(key) && (!objB.hasOwnProperty(key) || objA[key] !== objB[key])) { return false; } } // Test for B's keys missing from A. for (key in objB) { if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) { return false; } } return true; } module.exports = shallowEqual; },{}],167:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shouldUpdateReactComponent * @typechecks static-only */ 'use strict'; var warning = _dereq_(171); /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { if (prevElement != null && nextElement != null) { var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return (nextType === 'string' || nextType === 'number'); } else { if (nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key) { var ownersMatch = prevElement._owner === nextElement._owner; var prevName = null; var nextName = null; var nextDisplayName = null; if ("production" !== "development") { if (!ownersMatch) { if (prevElement._owner != null && prevElement._owner.getPublicInstance() != null && prevElement._owner.getPublicInstance().constructor != null) { prevName = prevElement._owner.getPublicInstance().constructor.displayName; } if (nextElement._owner != null && nextElement._owner.getPublicInstance() != null && nextElement._owner.getPublicInstance().constructor != null) { nextName = nextElement._owner.getPublicInstance().constructor.displayName; } if (nextElement.type != null && nextElement.type.displayName != null) { nextDisplayName = nextElement.type.displayName; } if (nextElement.type != null && typeof nextElement.type === 'string') { nextDisplayName = nextElement.type; } if (typeof nextElement.type !== 'string' || nextElement.type === 'input' || nextElement.type === 'textarea') { if ((prevElement._owner != null && prevElement._owner._isOwnerNecessary === false) || (nextElement._owner != null && nextElement._owner._isOwnerNecessary === false)) { if (prevElement._owner != null) { prevElement._owner._isOwnerNecessary = true; } if (nextElement._owner != null) { nextElement._owner._isOwnerNecessary = true; } ("production" !== "development" ? warning( false, '<%s /> is being rendered by both %s and %s using the same ' + 'key (%s) in the same place. Currently, this means that ' + 'they don\'t preserve state. This behavior should be very ' + 'rare so we\'re considering deprecating it. Please contact ' + 'the React team and explain your use case so that we can ' + 'take that into consideration.', nextDisplayName || 'Unknown Component', prevName || '[Unknown]', nextName || '[Unknown]', prevElement.key ) : null); } } } } return ownersMatch; } } } return false; } module.exports = shouldUpdateReactComponent; },{"171":171}],168:[function(_dereq_,module,exports){ /** * 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 toArray * @typechecks */ var invariant = _dereq_(150); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browse builtin objects can report typeof 'function' (e.g. NodeList in // old versions of Safari). ("production" !== "development" ? invariant( !Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function'), 'toArray: Array-like object expected' ) : invariant(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function'))); ("production" !== "development" ? invariant( typeof length === 'number', 'toArray: Object needs a length property' ) : invariant(typeof length === 'number')); ("production" !== "development" ? invariant( length === 0 || (length - 1) in obj, 'toArray: Object should have keys for indices' ) : invariant(length === 0 || (length - 1) in obj)); // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } module.exports = toArray; },{"150":150}],169:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule traverseAllChildren */ 'use strict'; var ReactElement = _dereq_(63); var ReactFragment = _dereq_(69); var ReactInstanceHandles = _dereq_(72); var getIteratorFn = _dereq_(141); var invariant = _dereq_(150); var warning = _dereq_(171); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var SUBSEPARATOR = ':'; /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var userProvidedKeyEscaperLookup = { '=': '=0', '.': '=1', ':': '=2' }; var userProvidedKeyEscapeRegex = /[=.:]/g; var didWarnAboutMaps = false; function userProvidedKeyEscaper(match) { return userProvidedKeyEscaperLookup[match]; } /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { if (component && component.key != null) { // Explicit key return wrapUserProvidedKey(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * Escape a component key so that it is safe to use in a reactid. * * @param {*} key Component key to be escaped. * @return {string} An escaped string. */ function escapeUserProvidedKey(text) { return ('' + text).replace( userProvidedKeyEscapeRegex, userProvidedKeyEscaper ); } /** * Wrap a `key` value explicitly provided by the user to distinguish it from * implicitly-generated keys generated by a component's index in its parent. * * @param {string} key Value of a user-provided `key` attribute * @return {string} */ function wrapUserProvidedKey(key) { return '$' + escapeUserProvidedKey(key); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!number} indexSoFar Number of children encountered until this point. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl( children, nameSoFar, indexSoFar, callback, traverseContext ) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { callback( traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar, indexSoFar ); return 1; } var child, nextName, nextIndex; var subtreeCount = 0; // Count of children found in the current subtree. if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = ( (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) + getComponentKey(child, i) ); nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( child, nextName, nextIndex, callback, traverseContext ); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = ( (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) + getComponentKey(child, ii++) ); nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( child, nextName, nextIndex, callback, traverseContext ); } } else { if ("production" !== "development") { ("production" !== "development" ? warning( didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.' ) : null); didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = ( (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0) ); nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( child, nextName, nextIndex, callback, traverseContext ); } } } } else if (type === 'object') { ("production" !== "development" ? invariant( children.nodeType !== 1, 'traverseAllChildren(...): Encountered an invalid child; DOM ' + 'elements are not valid children of React components.' ) : invariant(children.nodeType !== 1)); var fragment = ReactFragment.extract(children); for (var key in fragment) { if (fragment.hasOwnProperty(key)) { child = fragment[key]; nextName = ( (nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) + wrapUserProvidedKey(key) + SUBSEPARATOR + getComponentKey(child, 0) ); nextIndex = indexSoFar + subtreeCount; subtreeCount += traverseAllChildrenImpl( child, nextName, nextIndex, callback, traverseContext ); } } } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', 0, callback, traverseContext); } module.exports = traverseAllChildren; },{"141":141,"150":150,"171":171,"63":63,"69":69,"72":72}],170:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule update */ /* global hasOwnProperty:true */ 'use strict'; var assign = _dereq_(29); var keyOf = _dereq_(157); var invariant = _dereq_(150); var hasOwnProperty = {}.hasOwnProperty; function shallowCopy(x) { if (Array.isArray(x)) { return x.concat(); } else if (x && typeof x === 'object') { return assign(new x.constructor(), x); } else { return x; } } var COMMAND_PUSH = keyOf({$push: null}); var COMMAND_UNSHIFT = keyOf({$unshift: null}); var COMMAND_SPLICE = keyOf({$splice: null}); var COMMAND_SET = keyOf({$set: null}); var COMMAND_MERGE = keyOf({$merge: null}); var COMMAND_APPLY = keyOf({$apply: null}); var ALL_COMMANDS_LIST = [ COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY ]; var ALL_COMMANDS_SET = {}; ALL_COMMANDS_LIST.forEach(function(command) { ALL_COMMANDS_SET[command] = true; }); function invariantArrayCase(value, spec, command) { ("production" !== "development" ? invariant( Array.isArray(value), 'update(): expected target of %s to be an array; got %s.', command, value ) : invariant(Array.isArray(value))); var specValue = spec[command]; ("production" !== "development" ? invariant( Array.isArray(specValue), 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue ) : invariant(Array.isArray(specValue))); } function update(value, spec) { ("production" !== "development" ? invariant( typeof spec === 'object', 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET ) : invariant(typeof spec === 'object')); if (hasOwnProperty.call(spec, COMMAND_SET)) { ("production" !== "development" ? invariant( Object.keys(spec).length === 1, 'Cannot have more than one key in an object with %s', COMMAND_SET ) : invariant(Object.keys(spec).length === 1)); return spec[COMMAND_SET]; } var nextValue = shallowCopy(value); if (hasOwnProperty.call(spec, COMMAND_MERGE)) { var mergeObj = spec[COMMAND_MERGE]; ("production" !== "development" ? invariant( mergeObj && typeof mergeObj === 'object', 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj ) : invariant(mergeObj && typeof mergeObj === 'object')); ("production" !== "development" ? invariant( nextValue && typeof nextValue === 'object', 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue ) : invariant(nextValue && typeof nextValue === 'object')); assign(nextValue, spec[COMMAND_MERGE]); } if (hasOwnProperty.call(spec, COMMAND_PUSH)) { invariantArrayCase(value, spec, COMMAND_PUSH); spec[COMMAND_PUSH].forEach(function(item) { nextValue.push(item); }); } if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) { invariantArrayCase(value, spec, COMMAND_UNSHIFT); spec[COMMAND_UNSHIFT].forEach(function(item) { nextValue.unshift(item); }); } if (hasOwnProperty.call(spec, COMMAND_SPLICE)) { ("production" !== "development" ? invariant( Array.isArray(value), 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value ) : invariant(Array.isArray(value))); ("production" !== "development" ? invariant( Array.isArray(spec[COMMAND_SPLICE]), 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE] ) : invariant(Array.isArray(spec[COMMAND_SPLICE]))); spec[COMMAND_SPLICE].forEach(function(args) { ("production" !== "development" ? invariant( Array.isArray(args), 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE] ) : invariant(Array.isArray(args))); nextValue.splice.apply(nextValue, args); }); } if (hasOwnProperty.call(spec, COMMAND_APPLY)) { ("production" !== "development" ? invariant( typeof spec[COMMAND_APPLY] === 'function', 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY] ) : invariant(typeof spec[COMMAND_APPLY] === 'function')); nextValue = spec[COMMAND_APPLY](nextValue); } for (var k in spec) { if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { nextValue[k] = update(value[k], spec[k]); } } return nextValue; } module.exports = update; },{"150":150,"157":157,"29":29}],171:[function(_dereq_,module,exports){ /** * 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 = _dereq_(129); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("production" !== "development") { warning = function(condition, format ) {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; },{"129":129}]},{},[1])(1) });
client/Components/ComponentParams/ParamSelector/index.js
myheritage/UiZoo.js
import React from 'react'; import calculateType from './calculateType'; import {getBaseSynonym} from '../../../services/synonymService'; import ParamSelectorBoolean from './ParamSelectorBoolean'; import ParamSelectorVariant from './ParamSelectorVariant'; import ParamSelectorJSON from './ParamSelectorJSON'; import ParamSelectorFunction from './ParamSelectorFunction'; import ParamSelectorJSX from './ParamSelectorJSX'; import ParamSelectorObject from './ParamSelectorObject'; const paramTypeToComponent = { 'bool': ParamSelectorBoolean, 'variant': ParamSelectorVariant, 'function' : ParamSelectorFunction, 'node': ParamSelectorJSX, 'object': ParamSelectorObject, 'default': ParamSelectorJSON, }; /** * @description * wrapper to be used to get the needed selector * * @param {string} type Doctrine expression for the type * @param {string} name selector name for unique id/key * @param {any} selectedValue update the selector with the current selected value * @param {function} onChange report to parent on changes in the selector */ export default class ParamSelector extends React.Component { /** * get the right selector * @param {string} type * @param {array} values * @return {object} */ getSelector(type, values) { let Selector = paramTypeToComponent[getBaseSynonym(type.toLowerCase())]; if (type === 'variant' && (!values || !values.length)) { Selector = paramTypeToComponent['default']; } return Selector || paramTypeToComponent['default']; } /** * Render the right selector for the job */ render() { const {type, values} = calculateType(this.props.type); const Selector = this.getSelector(type, values); return (<Selector {...this.props} values={values}/>); } }
server/sonar-web/src/main/js/components/select-list/list.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import Item from './item'; export default React.createClass({ propTypes: { items: React.PropTypes.array.isRequired, renderItem: React.PropTypes.func.isRequired, getItemKey: React.PropTypes.func.isRequired, selectItem: React.PropTypes.func.isRequired, deselectItem: React.PropTypes.func.isRequired }, render() { const renderedItems = this.props.items.map(item => { const key = this.props.getItemKey(item); return <Item key={key} {...this.props} item={item} />; }); return <ul>{renderedItems}</ul>; } });
lib/werkzeug/debug/shared/jquery.js
awagnon/maraschino
/*! * jQuery JavaScript Library v1.4.4 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Nov 11 19:04:53 2010 -0500 */ (function(E,B){function ka(a,b,d){if(d===B&&a.nodeType===1){d=a.getAttribute("data-"+b);if(typeof d==="string"){try{d=d==="true"?true:d==="false"?false:d==="null"?null:!c.isNaN(d)?parseFloat(d):Ja.test(d)?c.parseJSON(d):d}catch(e){}c.data(a,b,d)}else d=B}return d}function U(){return false}function ca(){return true}function la(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ka(a){var b,d,e,f,h,l,k,o,x,r,A,C=[];f=[];h=c.data(this,this.nodeType?"events":"__events__");if(typeof h==="function")h= h.events;if(!(a.liveFired===this||!h||!h.live||a.button&&a.type==="click")){if(a.namespace)A=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var J=h.live.slice(0);for(k=0;k<J.length;k++){h=J[k];h.origType.replace(X,"")===a.type?f.push(h.selector):J.splice(k--,1)}f=c(a.target).closest(f,a.currentTarget);o=0;for(x=f.length;o<x;o++){r=f[o];for(k=0;k<J.length;k++){h=J[k];if(r.selector===h.selector&&(!A||A.test(h.namespace))){l=r.elem;e=null;if(h.preType==="mouseenter"|| h.preType==="mouseleave"){a.type=h.preType;e=c(a.relatedTarget).closest(h.selector)[0]}if(!e||e!==l)C.push({elem:l,handleObj:h,level:r.level})}}}o=0;for(x=C.length;o<x;o++){f=C[o];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data;a.handleObj=f.handleObj;A=f.handleObj.origHandler.apply(f.elem,arguments);if(A===false||a.isPropagationStopped()){d=f.level;if(A===false)b=false;if(a.isImmediatePropagationStopped())break}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(La, "`").replace(Ma,"&")}function ma(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Na.test(b))return c.filter(b,e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function na(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this, e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var l in e[h])c.event.add(this,h,e[h][l],e[h][l].data)}}})}function Oa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function oa(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?Pa:Qa,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a, "margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function da(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Ra.test(a)?e(a,h):da(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)?e(a,""):c.each(b,function(f,h){da(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(pa.concat.apply([],pa.slice(0,b)),function(){d[this]=a});return d}function qa(a){if(!ea[a]){var b=c("<"+ a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";ea[a]=d}return ea[a]}function fa(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var t=E.document,c=function(){function a(){if(!b.isReady){try{t.documentElement.doScroll("left")}catch(j){setTimeout(a,1);return}b.ready()}}var b=function(j,s){return new b.fn.init(j,s)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,l=/\S/,k=/^\s+/,o=/\s+$/,x=/\W/,r=/\d/,A=/^<(\w+)\s*\/?>(?:<\/\1>)?$/, C=/^[\],:{}\s]*$/,J=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,I=/(?:^|:|,)(?:\s*\[)+/g,L=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,i=/(msie) ([\w.]+)/,n=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false,q=[],u,y=Object.prototype.toString,F=Object.prototype.hasOwnProperty,M=Array.prototype.push,N=Array.prototype.slice,O=String.prototype.trim,D=Array.prototype.indexOf,R={};b.fn=b.prototype={init:function(j, s){var v,z,H;if(!j)return this;if(j.nodeType){this.context=this[0]=j;this.length=1;return this}if(j==="body"&&!s&&t.body){this.context=t;this[0]=t.body;this.selector="body";this.length=1;return this}if(typeof j==="string")if((v=h.exec(j))&&(v[1]||!s))if(v[1]){H=s?s.ownerDocument||s:t;if(z=A.exec(j))if(b.isPlainObject(s)){j=[t.createElement(z[1])];b.fn.attr.call(j,s,true)}else j=[H.createElement(z[1])];else{z=b.buildFragment([v[1]],[H]);j=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this, j)}else{if((z=t.getElementById(v[2]))&&z.parentNode){if(z.id!==v[2])return f.find(j);this.length=1;this[0]=z}this.context=t;this.selector=j;return this}else if(!s&&!x.test(j)){this.selector=j;this.context=t;j=t.getElementsByTagName(j);return b.merge(this,j)}else return!s||s.jquery?(s||f).find(j):b(s).find(j);else if(b.isFunction(j))return f.ready(j);if(j.selector!==B){this.selector=j.selector;this.context=j.context}return b.makeArray(j,this)},selector:"",jquery:"1.4.4",length:0,size:function(){return this.length}, toArray:function(){return N.call(this,0)},get:function(j){return j==null?this.toArray():j<0?this.slice(j)[0]:this[j]},pushStack:function(j,s,v){var z=b();b.isArray(j)?M.apply(z,j):b.merge(z,j);z.prevObject=this;z.context=this.context;if(s==="find")z.selector=this.selector+(this.selector?" ":"")+v;else if(s)z.selector=this.selector+"."+s+"("+v+")";return z},each:function(j,s){return b.each(this,j,s)},ready:function(j){b.bindReady();if(b.isReady)j.call(t,b);else q&&q.push(j);return this},eq:function(j){return j=== -1?this.slice(j):this.slice(j,+j+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(j){return this.pushStack(b.map(this,function(s,v){return j.call(s,v,s)}))},end:function(){return this.prevObject||b(null)},push:M,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var j,s,v,z,H,G=arguments[0]||{},K=1,Q=arguments.length,ga=false; if(typeof G==="boolean"){ga=G;G=arguments[1]||{};K=2}if(typeof G!=="object"&&!b.isFunction(G))G={};if(Q===K){G=this;--K}for(;K<Q;K++)if((j=arguments[K])!=null)for(s in j){v=G[s];z=j[s];if(G!==z)if(ga&&z&&(b.isPlainObject(z)||(H=b.isArray(z)))){if(H){H=false;v=v&&b.isArray(v)?v:[]}else v=v&&b.isPlainObject(v)?v:{};G[s]=b.extend(ga,v,z)}else if(z!==B)G[s]=z}return G};b.extend({noConflict:function(j){E.$=e;if(j)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(j){j===true&&b.readyWait--; if(!b.readyWait||j!==true&&!b.isReady){if(!t.body)return setTimeout(b.ready,1);b.isReady=true;if(!(j!==true&&--b.readyWait>0))if(q){var s=0,v=q;for(q=null;j=v[s++];)j.call(t,b);b.fn.trigger&&b(t).trigger("ready").unbind("ready")}}},bindReady:function(){if(!p){p=true;if(t.readyState==="complete")return setTimeout(b.ready,1);if(t.addEventListener){t.addEventListener("DOMContentLoaded",u,false);E.addEventListener("load",b.ready,false)}else if(t.attachEvent){t.attachEvent("onreadystatechange",u);E.attachEvent("onload", b.ready);var j=false;try{j=E.frameElement==null}catch(s){}t.documentElement.doScroll&&j&&a()}}},isFunction:function(j){return b.type(j)==="function"},isArray:Array.isArray||function(j){return b.type(j)==="array"},isWindow:function(j){return j&&typeof j==="object"&&"setInterval"in j},isNaN:function(j){return j==null||!r.test(j)||isNaN(j)},type:function(j){return j==null?String(j):R[y.call(j)]||"object"},isPlainObject:function(j){if(!j||b.type(j)!=="object"||j.nodeType||b.isWindow(j))return false;if(j.constructor&& !F.call(j,"constructor")&&!F.call(j.constructor.prototype,"isPrototypeOf"))return false;for(var s in j);return s===B||F.call(j,s)},isEmptyObject:function(j){for(var s in j)return false;return true},error:function(j){throw j;},parseJSON:function(j){if(typeof j!=="string"||!j)return null;j=b.trim(j);if(C.test(j.replace(J,"@").replace(w,"]").replace(I,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(j):(new Function("return "+j))();else b.error("Invalid JSON: "+j)},noop:function(){},globalEval:function(j){if(j&& l.test(j)){var s=t.getElementsByTagName("head")[0]||t.documentElement,v=t.createElement("script");v.type="text/javascript";if(b.support.scriptEval)v.appendChild(t.createTextNode(j));else v.text=j;s.insertBefore(v,s.firstChild);s.removeChild(v)}},nodeName:function(j,s){return j.nodeName&&j.nodeName.toUpperCase()===s.toUpperCase()},each:function(j,s,v){var z,H=0,G=j.length,K=G===B||b.isFunction(j);if(v)if(K)for(z in j){if(s.apply(j[z],v)===false)break}else for(;H<G;){if(s.apply(j[H++],v)===false)break}else if(K)for(z in j){if(s.call(j[z], z,j[z])===false)break}else for(v=j[0];H<G&&s.call(v,H,v)!==false;v=j[++H]);return j},trim:O?function(j){return j==null?"":O.call(j)}:function(j){return j==null?"":j.toString().replace(k,"").replace(o,"")},makeArray:function(j,s){var v=s||[];if(j!=null){var z=b.type(j);j.length==null||z==="string"||z==="function"||z==="regexp"||b.isWindow(j)?M.call(v,j):b.merge(v,j)}return v},inArray:function(j,s){if(s.indexOf)return s.indexOf(j);for(var v=0,z=s.length;v<z;v++)if(s[v]===j)return v;return-1},merge:function(j, s){var v=j.length,z=0;if(typeof s.length==="number")for(var H=s.length;z<H;z++)j[v++]=s[z];else for(;s[z]!==B;)j[v++]=s[z++];j.length=v;return j},grep:function(j,s,v){var z=[],H;v=!!v;for(var G=0,K=j.length;G<K;G++){H=!!s(j[G],G);v!==H&&z.push(j[G])}return z},map:function(j,s,v){for(var z=[],H,G=0,K=j.length;G<K;G++){H=s(j[G],G,v);if(H!=null)z[z.length]=H}return z.concat.apply([],z)},guid:1,proxy:function(j,s,v){if(arguments.length===2)if(typeof s==="string"){v=j;j=v[s];s=B}else if(s&&!b.isFunction(s)){v= s;s=B}if(!s&&j)s=function(){return j.apply(v||this,arguments)};if(j)s.guid=j.guid=j.guid||s.guid||b.guid++;return s},access:function(j,s,v,z,H,G){var K=j.length;if(typeof s==="object"){for(var Q in s)b.access(j,Q,s[Q],z,H,v);return j}if(v!==B){z=!G&&z&&b.isFunction(v);for(Q=0;Q<K;Q++)H(j[Q],s,z?v.call(j[Q],Q,H(j[Q],s)):v,G);return j}return K?H(j[0],s):B},now:function(){return(new Date).getTime()},uaMatch:function(j){j=j.toLowerCase();j=L.exec(j)||g.exec(j)||i.exec(j)||j.indexOf("compatible")<0&&n.exec(j)|| [];return{browser:j[1]||"",version:j[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(j,s){R["[object "+s+"]"]=s.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version=m.version}if(b.browser.webkit)b.browser.safari=true;if(D)b.inArray=function(j,s){return D.call(s,j)};if(!/\s/.test("\u00a0")){k=/^[\s\xA0]+/;o=/[\s\xA0]+$/}f=b(t);if(t.addEventListener)u=function(){t.removeEventListener("DOMContentLoaded",u, false);b.ready()};else if(t.attachEvent)u=function(){if(t.readyState==="complete"){t.detachEvent("onreadystatechange",u);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=t.documentElement,b=t.createElement("script"),d=t.createElement("div"),e="script"+c.now();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],l=t.createElement("select"), k=l.appendChild(t.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")),hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:k.selected,deleteExpando:true,optDisabled:false,checkClone:false, scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};l.disabled=true;c.support.optDisabled=!k.disabled;b.type="text/javascript";try{b.appendChild(t.createTextNode("window."+e+"=1;"))}catch(o){}a.insertBefore(b,a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}try{delete b.test}catch(x){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function r(){c.support.noCloneEvent= false;d.detachEvent("onclick",r)});d.cloneNode(true).fireEvent("onclick")}d=t.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=t.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var r=t.createElement("div");r.style.width=r.style.paddingLeft="1px";t.body.appendChild(r);c.boxModel=c.support.boxModel=r.offsetWidth===2;if("zoom"in r.style){r.style.display="inline";r.style.zoom= 1;c.support.inlineBlockNeedsLayout=r.offsetWidth===2;r.style.display="";r.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=r.offsetWidth!==2}r.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var A=r.getElementsByTagName("td");c.support.reliableHiddenOffsets=A[0].offsetHeight===0;A[0].style.display="";A[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&A[0].offsetHeight===0;r.innerHTML="";t.body.removeChild(r).style.display= "none"});a=function(r){var A=t.createElement("div");r="on"+r;var C=r in A;if(!C){A.setAttribute(r,"return;");C=typeof A[r]==="function"}return C};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();var ra={},Ja=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?ra:a;var e=a.nodeType,f=e?a[c.expando]:null,h= c.cache;if(!(e&&!f&&typeof b==="string"&&d===B)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]=c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==B)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?ra:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando); else if(d)delete f[e];else for(var l in a)delete a[l]}},acceptData:function(a){if(a.nodeName){var b=c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){var d=null;if(typeof a==="undefined"){if(this.length){var e=this[0].attributes,f;d=c.data(this[0]);for(var h=0,l=e.length;h<l;h++){f=e[h].name;if(f.indexOf("data-")===0){f=f.substr(5);ka(this[0],f,d[f])}}}return d}else if(typeof a==="object")return this.each(function(){c.data(this, a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(b===B){d=this.triggerHandler("getData"+k[1]+"!",[k[0]]);if(d===B&&this.length){d=c.data(this[0],a);d=ka(this[0],a,d)}return d===B&&k[1]?this.data(k[0]):d}else return this.each(function(){var o=c(this),x=[k[0],b];o.triggerHandler("setData"+k[1]+"!",x);c.data(this,a,b);o.triggerHandler("changeData"+k[1]+"!",x)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e= c.data(a,b);if(!d)return e||[];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===B)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this, a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var sa=/[\n\t]/g,ha=/\s+/,Sa=/\r/g,Ta=/^(?:href|src|style)$/,Ua=/^(?:button|input)$/i,Va=/^(?:button|input|object|select|textarea)$/i,Wa=/^a(?:rea)?$/i,ta=/^(?:radio|checkbox)$/i;c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan", colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(x){var r=c(this);r.addClass(a.call(this,x,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType=== 1)if(f.className){for(var h=" "+f.className+" ",l=f.className,k=0,o=b.length;k<o;k++)if(h.indexOf(" "+b[k]+" ")<0)l+=" "+b[k];f.className=c.trim(l)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var x=c(this);x.removeClass(a.call(this,o,x.attr("class")))});if(a&&typeof a==="string"||a===B)for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(sa," "), l=0,k=b.length;l<k;l++)h=h.replace(" "+b[l]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this,f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,l=c(this),k=b,o=a.split(ha);f=o[h++];){k=e?k:!l.hasClass(f);l[k?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this, "__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(sa," ").indexOf(a)>-1)return true;return false},val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one"; if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var l=f[h];if(l.selected&&(c.support.optDisabled?!l.disabled:l.getAttribute("disabled")===null)&&(!l.parentNode.disabled||!c.nodeName(l.parentNode,"optgroup"))){a=c(l).val();if(b)return a;d.push(a)}}return d}if(ta.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Sa,"")}return B}var k=c.isFunction(a);return this.each(function(o){var x=c(this),r=a;if(this.nodeType===1){if(k)r= a.call(this,o,x.val());if(r==null)r="";else if(typeof r==="number")r+="";else if(c.isArray(r))r=c.map(r,function(C){return C==null?"":C+""});if(c.isArray(r)&&ta.test(this.type))this.checked=c.inArray(x.val(),r)>=0;else if(c.nodeName(this,"select")){var A=c.makeArray(r);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),A)>=0});if(!A.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true}, attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return B;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==B;b=e&&c.props[b]||b;var h=Ta.test(b);if((b in a||a[b]!==B)&&e&&!h){if(f){b==="type"&&Ua.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&& b.specified?b.value:Va.test(a.nodeName)||Wa.test(a.nodeName)&&a.href?0:B;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return B;a=!c.support.hrefNormalized&&e&&h?a.getAttribute(b,2):a.getAttribute(b);return a===null?B:a}});var X=/\.(.*)$/,ia=/^(?:textarea|input|select)$/i,La=/\./g,Ma=/ /g,Xa=/[^\w\s.|`]/g,Ya=function(a){return a.replace(Xa,"\\$&")},ua={focusin:0,focusout:0}; c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;else if(!d)return;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var l=a.nodeType?"events":"__events__",k=h[l],o=h.handle;if(typeof k==="function"){o=k.handle;k=k.events}else if(!k){a.nodeType||(h[l]=h=function(){});h.events=k={}}if(!o)h.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem, arguments):B};o.elem=a;b=b.split(" ");for(var x=0,r;l=b[x++];){h=f?c.extend({},f):{handler:d,data:e};if(l.indexOf(".")>-1){r=l.split(".");l=r.shift();h.namespace=r.slice(0).sort().join(".")}else{r=[];h.namespace=""}h.type=l;if(!h.guid)h.guid=d.guid;var A=k[l],C=c.event.special[l]||{};if(!A){A=k[l]=[];if(!C.setup||C.setup.call(a,e,r,o)===false)if(a.addEventListener)a.addEventListener(l,o,false);else a.attachEvent&&a.attachEvent("on"+l,o)}if(C.add){C.add.call(a,h);if(!h.handler.guid)h.handler.guid= d.guid}A.push(h);c.event.global[l]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,l=0,k,o,x,r,A,C,J=a.nodeType?"events":"__events__",w=c.data(a),I=w&&w[J];if(w&&I){if(typeof I==="function"){w=I;I=I.events}if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in I)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[l++];){r=f;k=f.indexOf(".")<0;o=[];if(!k){o=f.split(".");f=o.shift();x=RegExp("(^|\\.)"+ c.map(o.slice(0).sort(),Ya).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(A=I[f])if(d){r=c.event.special[f]||{};for(h=e||0;h<A.length;h++){C=A[h];if(d.guid===C.guid){if(k||x.test(C.namespace)){e==null&&A.splice(h--,1);r.remove&&r.remove.call(a,C)}if(e!=null)break}}if(A.length===0||e!=null&&A.length===1){if(!r.teardown||r.teardown.call(a,o)===false)c.removeEvent(a,f,w.handle);delete I[f]}}else for(h=0;h<A.length;h++){C=A[h];if(k||x.test(C.namespace)){c.event.remove(a,r,C.handler,h);A.splice(h--,1)}}}if(c.isEmptyObject(I)){if(b= w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,J);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type=f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType=== 8)return B;a.result=B;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)===false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){var l;e=a.target;var k=f.replace(X,""),o=c.nodeName(e,"a")&&k=== "click",x=c.event.special[k]||{};if((!x._default||x._default.call(d,a)===false)&&!o&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[k]){if(l=e["on"+k])e["on"+k]=null;c.event.triggered=true;e[k]()}}catch(r){}if(l)e["on"+k]=l;c.event.triggered=false}}},handle:function(a){var b,d,e,f;d=[];var h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+ d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var l=d.length;f<l;f++){var k=d[f];if(b||e.test(k.namespace)){a.handler=k.handler;a.data=k.data;a.handleObj=k;k=k.handler.apply(this,h);if(k!==B){a.result=k;if(k===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix:function(a){if(a[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||t;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=t.documentElement;d=t.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==B)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ka,guid:a.handler.guid}))},remove:function(a){c.event.remove(this, Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=t.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp= c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ca;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ca;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ca;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U}; var va=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},wa=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?wa:va,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?wa:va)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!== "form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=B;return la("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=B;return la("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V, xa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ia.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=xa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===B||f===e))if(e!=null||f){a.type="change";a.liveFired= B;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",xa(a))}},setup:function(){if(this.type=== "file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ia.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ia.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}t.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){ua[b]++===0&&t.addEventListener(a,d,true)},teardown:function(){--ua[b]=== 0&&t.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=B}var l=b==="one"?c.proxy(f,function(o){c(this).unbind(o,l);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var k=this.length;h<k;h++)c.event.add(this[h],d,l,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d, a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d= 1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var ya={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var l,k=0,o,x,r=h||this.selector;h=h?this:c(this.context);if(typeof d=== "object"&&!d.preventDefault){for(l in d)h[b](l,e,d[l],r);return this}if(c.isFunction(e)){f=e;e=B}for(d=(d||"").split(" ");(l=d[k++])!=null;){o=X.exec(l);x="";if(o){x=o[0];l=l.replace(X,"")}if(l==="hover")d.push("mouseenter"+x,"mouseleave"+x);else{o=l;if(l==="focus"||l==="blur"){d.push(ya[l]+x);l+=x}else l=(ya[l]||l)+x;if(b==="live"){x=0;for(var A=h.length;x<A;x++)c.event.add(h[x],"live."+Y(l,r),{data:e,selector:r,handler:f,origType:l,origHandler:f,preType:o})}else h.unbind("live."+Y(l,r),f)}}return this}}); c.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".split(" "),function(a,b){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}}); (function(){function a(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1&&!q){y.sizcache=n;y.sizset=p}if(y.nodeName.toLowerCase()===i){F=y;break}y=y[g]}m[p]=F}}}function b(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1){if(!q){y.sizcache=n;y.sizset=p}if(typeof i!=="string"){if(y===i){F=true;break}}else if(k.filter(i, [y]).length>0){F=y;break}}y=y[g]}m[p]=F}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,l=true;[0,0].sort(function(){l=false;return 0});var k=function(g,i,n,m){n=n||[];var p=i=i||t;if(i.nodeType!==1&&i.nodeType!==9)return[];if(!g||typeof g!=="string")return n;var q,u,y,F,M,N=true,O=k.isXML(i),D=[],R=g;do{d.exec("");if(q=d.exec(R)){R=q[3];D.push(q[1]);if(q[2]){F=q[3]; break}}}while(q);if(D.length>1&&x.exec(g))if(D.length===2&&o.relative[D[0]])u=L(D[0]+D[1],i);else for(u=o.relative[D[0]]?[i]:k(D.shift(),i);D.length;){g=D.shift();if(o.relative[g])g+=D.shift();u=L(g,u)}else{if(!m&&D.length>1&&i.nodeType===9&&!O&&o.match.ID.test(D[0])&&!o.match.ID.test(D[D.length-1])){q=k.find(D.shift(),i,O);i=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]}if(i){q=m?{expr:D.pop(),set:C(m)}:k.find(D.pop(),D.length===1&&(D[0]==="~"||D[0]==="+")&&i.parentNode?i.parentNode:i,O);u=q.expr?k.filter(q.expr, q.set):q.set;if(D.length>0)y=C(u);else N=false;for(;D.length;){q=M=D.pop();if(o.relative[M])q=D.pop();else M="";if(q==null)q=i;o.relative[M](y,q,O)}}else y=[]}y||(y=u);y||k.error(M||g);if(f.call(y)==="[object Array]")if(N)if(i&&i.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&k.contains(i,y[g])))n.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&n.push(u[g]);else n.push.apply(n,y);else C(y,n);if(F){k(F,p,n,m);k.uniqueSort(n)}return n};k.uniqueSort=function(g){if(w){h= l;g.sort(w);if(h)for(var i=1;i<g.length;i++)g[i]===g[i-1]&&g.splice(i--,1)}return g};k.matches=function(g,i){return k(g,null,null,i)};k.matchesSelector=function(g,i){return k(i,null,null,[g]).length>0};k.find=function(g,i,n){var m;if(!g)return[];for(var p=0,q=o.order.length;p<q;p++){var u,y=o.order[p];if(u=o.leftMatch[y].exec(g)){var F=u[1];u.splice(1,1);if(F.substr(F.length-1)!=="\\"){u[1]=(u[1]||"").replace(/\\/g,"");m=o.find[y](u,i,n);if(m!=null){g=g.replace(o.match[y],"");break}}}}m||(m=i.getElementsByTagName("*")); return{set:m,expr:g}};k.filter=function(g,i,n,m){for(var p,q,u=g,y=[],F=i,M=i&&i[0]&&k.isXML(i[0]);g&&i.length;){for(var N in o.filter)if((p=o.leftMatch[N].exec(g))!=null&&p[2]){var O,D,R=o.filter[N];D=p[1];q=false;p.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(F===y)y=[];if(o.preFilter[N])if(p=o.preFilter[N](p,F,n,y,m,M)){if(p===true)continue}else q=O=true;if(p)for(var j=0;(D=F[j])!=null;j++)if(D){O=R(D,p,j,F);var s=m^!!O;if(n&&O!=null)if(s)q=true;else F[j]=false;else if(s){y.push(D);q=true}}if(O!== B){n||(F=y);g=g.replace(o.match[N],"");if(!q)return[];break}}}if(g===u)if(q==null)k.error(g);else break;u=g}return F};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var o=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,i){var n=typeof i==="string",m=n&&!/\W/.test(i);n=n&&!m;if(m)i=i.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=n||q&&q.nodeName.toLowerCase()=== i?q||false:q===i}n&&k.filter(i,g,true)},">":function(g,i){var n,m=typeof i==="string",p=0,q=g.length;if(m&&!/\W/.test(i))for(i=i.toLowerCase();p<q;p++){if(n=g[p]){n=n.parentNode;g[p]=n.nodeName.toLowerCase()===i?n:false}}else{for(;p<q;p++)if(n=g[p])g[p]=m?n.parentNode:n.parentNode===i;m&&k.filter(i,g,true)}},"":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=i=i.toLowerCase();q=a}q("parentNode",i,p,g,m,n)},"~":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m= i=i.toLowerCase();q=a}q("previousSibling",i,p,g,m,n)}},find:{ID:function(g,i,n){if(typeof i.getElementById!=="undefined"&&!n)return(g=i.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,i){if(typeof i.getElementsByName!=="undefined"){for(var n=[],m=i.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&n.push(m[p]);return n.length===0?null:n}},TAG:function(g,i){return i.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,i,n,m,p,q){g=" "+g[1].replace(/\\/g, "")+" ";if(q)return g;q=0;for(var u;(u=i[q])!=null;q++)if(u)if(p^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))n||m.push(u);else if(n)i[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var i=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=i[1]+(i[2]||1)-0;g[3]=i[3]-0}g[0]=e++;return g},ATTR:function(g,i,n, m,p,q){i=g[1].replace(/\\/g,"");if(!q&&o.attrMap[i])g[1]=o.attrMap[i];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,i,n,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,i);else{g=k.filter(g[3],i,n,true^p);n||m.push.apply(m,g);return false}else if(o.match.POS.test(g[0])||o.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled=== true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,i,n){return!!k(n[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"=== g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,i){return i===0},last:function(g,i,n,m){return i===m.length-1},even:function(g,i){return i%2===0},odd:function(g,i){return i%2===1},lt:function(g,i,n){return i<n[3]-0},gt:function(g,i,n){return i>n[3]-0},nth:function(g,i,n){return n[3]- 0===i},eq:function(g,i,n){return n[3]-0===i}},filter:{PSEUDO:function(g,i,n,m){var p=i[1],q=o.filters[p];if(q)return q(g,n,i,m);else if(p==="contains")return(g.textContent||g.innerText||k.getText([g])||"").indexOf(i[3])>=0;else if(p==="not"){i=i[3];n=0;for(m=i.length;n<m;n++)if(i[n]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,i){var n=i[1],m=g;switch(n){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(n=== "first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":n=i[2];var p=i[3];if(n===1&&p===0)return true;var q=i[0],u=g.parentNode;if(u&&(u.sizcache!==q||!g.nodeIndex)){var y=0;for(m=u.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++y;u.sizcache=q}m=g.nodeIndex-p;return n===0?m===0:m%n===0&&m/n>=0}},ID:function(g,i){return g.nodeType===1&&g.getAttribute("id")===i},TAG:function(g,i){return i==="*"&&g.nodeType===1||g.nodeName.toLowerCase()=== i},CLASS:function(g,i){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(i)>-1},ATTR:function(g,i){var n=i[1];n=o.attrHandle[n]?o.attrHandle[n](g):g[n]!=null?g[n]:g.getAttribute(n);var m=n+"",p=i[2],q=i[4];return n==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&n!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,i,n,m){var p=o.setFilters[i[2]]; if(p)return p(g,n,i,m)}}},x=o.match.POS,r=function(g,i){return"\\"+(i-0+1)},A;for(A in o.match){o.match[A]=RegExp(o.match[A].source+/(?![^\[]*\])(?![^\(]*\))/.source);o.leftMatch[A]=RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[A].source.replace(/\\(\d+)/g,r))}var C=function(g,i){g=Array.prototype.slice.call(g,0);if(i){i.push.apply(i,g);return i}return g};try{Array.prototype.slice.call(t.documentElement.childNodes,0)}catch(J){C=function(g,i){var n=0,m=i||[];if(f.call(g)==="[object Array]")Array.prototype.push.apply(m, g);else if(typeof g.length==="number")for(var p=g.length;n<p;n++)m.push(g[n]);else for(;g[n];n++)m.push(g[n]);return m}}var w,I;if(t.documentElement.compareDocumentPosition)w=function(g,i){if(g===i){h=true;return 0}if(!g.compareDocumentPosition||!i.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(i)&4?-1:1};else{w=function(g,i){var n,m,p=[],q=[];n=g.parentNode;m=i.parentNode;var u=n;if(g===i){h=true;return 0}else if(n===m)return I(g,i);else if(n){if(!m)return 1}else return-1; for(;u;){p.unshift(u);u=u.parentNode}for(u=m;u;){q.unshift(u);u=u.parentNode}n=p.length;m=q.length;for(u=0;u<n&&u<m;u++)if(p[u]!==q[u])return I(p[u],q[u]);return u===n?I(g,q[u],-1):I(p[u],i,1)};I=function(g,i,n){if(g===i)return n;for(g=g.nextSibling;g;){if(g===i)return-1;g=g.nextSibling}return 1}}k.getText=function(g){for(var i="",n,m=0;g[m];m++){n=g[m];if(n.nodeType===3||n.nodeType===4)i+=n.nodeValue;else if(n.nodeType!==8)i+=k.getText(n.childNodes)}return i};(function(){var g=t.createElement("div"), i="script"+(new Date).getTime(),n=t.documentElement;g.innerHTML="<a name='"+i+"'/>";n.insertBefore(g,n.firstChild);if(t.getElementById(i)){o.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:B:[]};o.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}n.removeChild(g); n=g=null})();(function(){var g=t.createElement("div");g.appendChild(t.createComment(""));if(g.getElementsByTagName("*").length>0)o.find.TAG=function(i,n){var m=n.getElementsByTagName(i[1]);if(i[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")o.attrHandle.href=function(i){return i.getAttribute("href",2)};g=null})();t.querySelectorAll&& function(){var g=k,i=t.createElement("div");i.innerHTML="<p class='TEST'></p>";if(!(i.querySelectorAll&&i.querySelectorAll(".TEST").length===0)){k=function(m,p,q,u){p=p||t;m=m.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!u&&!k.isXML(p))if(p.nodeType===9)try{return C(p.querySelectorAll(m),q)}catch(y){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var F=p.getAttribute("id"),M=F||"__sizzle__";F||p.setAttribute("id",M);try{return C(p.querySelectorAll("#"+M+" "+m),q)}catch(N){}finally{F|| p.removeAttribute("id")}}return g(m,p,q,u)};for(var n in g)k[n]=g[n];i=null}}();(function(){var g=t.documentElement,i=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,n=false;try{i.call(t.documentElement,"[test!='']:sizzle")}catch(m){n=true}if(i)k.matchesSelector=function(p,q){q=q.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(p))try{if(n||!o.match.PSEUDO.test(q)&&!/!=/.test(q))return i.call(p,q)}catch(u){}return k(q,null,null,[p]).length>0}})();(function(){var g= t.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){o.order.splice(1,0,"CLASS");o.find.CLASS=function(i,n,m){if(typeof n.getElementsByClassName!=="undefined"&&!m)return n.getElementsByClassName(i[1])};g=null}}})();k.contains=t.documentElement.contains?function(g,i){return g!==i&&(g.contains?g.contains(i):true)}:t.documentElement.compareDocumentPosition? function(g,i){return!!(g.compareDocumentPosition(i)&16)}:function(){return false};k.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var L=function(g,i){for(var n,m=[],p="",q=i.nodeType?[i]:i;n=o.match.PSEUDO.exec(g);){p+=n[0];g=g.replace(o.match.PSEUDO,"")}g=o.relative[g]?g+"*":g;n=0;for(var u=q.length;n<u;n++)k(g,q[n],m);return k.filter(p,m)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=k.getText;c.isXMLDoc=k.isXML; c.contains=k.contains})();var Za=/Until$/,$a=/^(?:parents|prevUntil|prevAll)/,ab=/,/,Na=/^.[^:#\[\.,]*$/,bb=Array.prototype.slice,cb=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var l=0;l<d;l++)if(b[l]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})}, not:function(a){return this.pushStack(ma(this,a,false),"not",a)},filter:function(a){return this.pushStack(ma(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){var d=[],e,f,h=this[0];if(c.isArray(a)){var l,k={},o=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:o})}h= h.parentNode;o++}}return d}l=cb.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(l?l.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h||!h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context): c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a, 2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a, b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Za.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||ab.test(e))&&$a.test(a))f=f.reverse();return this.pushStack(f,a,bb.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===B||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&& e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var za=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,Aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Ba=/<([\w:]+)/,db=/<tbody/i,eb=/<|&#?\w+;/,Ca=/<(?:script|object|embed|option|style)/i,Da=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/\=([^="'>\s]+\/)>/g,P={option:[1, "<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};P.optgroup=P.option;P.tbody=P.tfoot=P.colgroup=P.caption=P.thead;P.th=P.td;if(!c.support.htmlSerialize)P._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==B)return this.empty().append((this[0]&&this[0].ownerDocument||t).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*"));c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(za,"").replace(fb,'="$1">').replace($,"")],e)[0]}else return this.cloneNode(true)});if(a===true){na(this,b);na(this.find("*"),b.find("*"))}return b},html:function(a){if(a===B)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(za,""):null; else if(typeof a==="string"&&!Ca.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!P[(Ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Aa,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)?this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d= c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){var e,f,h,l=a[0],k=[];if(!c.support.checkClone&&arguments.length===3&&typeof l==="string"&&Da.test(l))return this.each(function(){c(this).domManip(a, b,d,true)});if(c.isFunction(l))return this.each(function(x){var r=c(this);a[0]=l.call(this,x,b?r.html():B);r.domManip(a,b,d)});if(this[0]){e=l&&l.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);h=e.fragment;if(f=h.childNodes.length===1?h=h.firstChild:h.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var o=this.length;f<o;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")): this[f]:this[f],f>0||e.cacheable||this.length>1?h.cloneNode(true):h)}k.length&&c.each(k,Oa)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:t;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===t&&!Ca.test(a[0])&&(c.support.checkClone||!Da.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append", prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h=d.length;f<h;f++){var l=(f>0?this.clone(true):this).get();c(d[f])[b](l);e=e.concat(l)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||t;if(typeof b.createElement==="undefined")b=b.ownerDocument|| b[0]&&b[0].ownerDocument||t;for(var f=[],h=0,l;(l=a[h])!=null;h++){if(typeof l==="number")l+="";if(l){if(typeof l==="string"&&!eb.test(l))l=b.createTextNode(l);else if(typeof l==="string"){l=l.replace(Aa,"<$1></$2>");var k=(Ba.exec(l)||["",""])[1].toLowerCase(),o=P[k]||P._default,x=o[0],r=b.createElement("div");for(r.innerHTML=o[1]+l+o[2];x--;)r=r.lastChild;if(!c.support.tbody){x=db.test(l);k=k==="table"&&!x?r.firstChild&&r.firstChild.childNodes:o[1]==="<table>"&&!x?r.childNodes:[];for(o=k.length- 1;o>=0;--o)c.nodeName(k[o],"tbody")&&!k[o].childNodes.length&&k[o].parentNode.removeChild(k[o])}!c.support.leadingWhitespace&&$.test(l)&&r.insertBefore(b.createTextNode($.exec(l)[0]),r.firstChild);l=r.childNodes}if(l.nodeType)f.push(l);else f=c.merge(f,l)}}if(d)for(h=0;f[h];h++)if(e&&c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script")))); d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,l=0,k;(k=a[l])!=null;l++)if(!(k.nodeName&&c.noData[k.nodeName.toLowerCase()]))if(d=k[c.expando]){if((b=e[d])&&b.events)for(var o in b.events)f[o]?c.event.remove(k,o):c.removeEvent(k,o,b.handle);if(h)delete k[c.expando];else k.removeAttribute&&k.removeAttribute(c.expando);delete e[d]}}});var Ea=/alpha\([^)]*\)/i,gb=/opacity=([^)]*)/,hb=/-([a-z])/ig,ib=/([A-Z])/g,Fa=/^-?\d+(?:px)?$/i, jb=/^-?\d/,kb={position:"absolute",visibility:"hidden",display:"block"},Pa=["Left","Right"],Qa=["Top","Bottom"],W,Ga,aa,lb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===B)return this;return c.access(this,a,b,true,function(d,e,f){return f!==B?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true, zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),l=a.style,k=c.cssHooks[h];b=c.cssProps[h]||h;if(d!==B){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!k||!("set"in k)||(d=k.set(a,d))!==B)try{l[b]=d}catch(o){}}}else{if(k&&"get"in k&&(f=k.get(a,false,e))!==B)return f;return l[b]}}},css:function(a,b,d){var e,f=c.camelCase(b), h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==B)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]=e[f]},camelCase:function(a){return a.replace(hb,lb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=oa(d,b,f);else c.swap(d,kb,function(){h=oa(d,b,f)});if(h<=0){h=W(d,b,b);if(h==="0px"&&aa)h=aa(d,b,b); if(h!=null)return h===""||h==="auto"?"0px":h}if(h<0||h==null){h=d.style[b];return h===""||h==="auto"?"0px":h}return typeof h==="string"?h:h+"px"}},set:function(d,e){if(Fa.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return gb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f= d.filter||"";d.filter=Ea.test(f)?f.replace(Ea,e):d.filter+" "+e}};if(t.defaultView&&t.defaultView.getComputedStyle)Ga=function(a,b,d){var e;d=d.replace(ib,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return B;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};if(t.documentElement.currentStyle)aa=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b],h=a.style;if(!Fa.test(f)&&jb.test(f)){d=h.left; e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f===""?"auto":f};W=Ga||aa;if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var mb=c.now(),nb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ob=/^(?:select|textarea)/i,pb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,qb=/^(?:GET|HEAD)$/,Ra=/\[\]$/,T=/\=\?(&|$)/,ja=/\?/,rb=/([?&])_=[^&]*/,sb=/^(\w+:)?\/\/([^\/?#]+)/,tb=/%20/g,ub=/#.*$/,Ha=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ha)return Ha.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b=== "object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(l,k){if(k==="success"||k==="notmodified")h.html(f?c("<div>").append(l.responseText.replace(nb,"")).find(f):l.responseText);d&&h.each(d,[l.responseText,k,l])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&& !this.disabled&&(this.checked||ob.test(this.nodeName)||pb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})}, getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html", script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),l=qb.test(h);b.url=b.url.replace(ub,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ja.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data|| !T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+mb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var k=E[d];E[d]=function(m){if(c.isFunction(k))k(m);else{E[d]=B;try{delete E[d]}catch(p){}}f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);r&&r.removeChild(A)}}if(b.dataType==="script"&&b.cache===null)b.cache= false;if(b.cache===false&&l){var o=c.now(),x=b.url.replace(rb,"$1_="+o);b.url=x+(x===b.url?(ja.test(b.url)?"&":"?")+"_="+o:"")}if(b.data&&l)b.url+=(ja.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");o=(o=sb.exec(b.url))&&(o[1]&&o[1].toLowerCase()!==location.protocol||o[2].toLowerCase()!==location.host);if(b.dataType==="script"&&h==="GET"&&o){var r=t.getElementsByTagName("head")[0]||t.documentElement,A=t.createElement("script");if(b.scriptCharset)A.charset=b.scriptCharset; A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&a.contentType)w.setRequestHeader("Content-Type", b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}o||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(I){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&& c.triggerGlobal(b,"ajaxSend",[w,b]);var L=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){J||c.handleComplete(b,w,e,f);J=true;if(w)w.onreadystatechange=c.noop}else if(!J&&w&&(w.readyState===4||m==="timeout")){J=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d|| c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&Function.prototype.call.call(g,w);L("abort")}}catch(i){}b.async&&b.timeout>0&&setTimeout(function(){w&&!J&&L("timeout")},b.timeout);try{w.send(l||b.data==null?null:b.data)}catch(n){c.handleError(b,w,null,n);c.handleComplete(b,w,e,f)}b.async||L();return w}},param:function(a,b){var d=[],e=function(h,l){l=c.isFunction(l)?l():l;d[d.length]= encodeURIComponent(h)+"="+encodeURIComponent(l)};if(b===B)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)da(f,a[f],b,e);return d.join("&").replace(tb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess", [b,a])},handleComplete:function(a,b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"), e=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}}); if(E.ActiveXObject)c.ajaxSettings.xhr=function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var ea={},vb=/^(?:toggle|show|hide)$/,wb=/^([+\-]=)?([\d+.\-]+)(.*)$/,ba,pa=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show", 3),a,b,d);else{d=0;for(var e=this.length;d<e;d++){a=this[d];b=a.style.display;if(!c.data(a,"olddisplay")&&b==="none")b=a.style.display="";b===""&&c.css(a,"display")==="none"&&c.data(a,"olddisplay",qa(a.nodeName))}for(d=0;d<e;d++){a=this[d];b=a.style.display;if(b===""||b==="none")a.style.display=c.data(a,"olddisplay")||""}return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay", d)}for(a=0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b, d,e);if(c.isEmptyObject(a))return this.each(f.complete);return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),l,k=this.nodeType===1,o=k&&c(this).is(":hidden"),x=this;for(l in a){var r=c.camelCase(l);if(l!==r){a[r]=a[l];delete a[l];l=r}if(a[l]==="hide"&&o||a[l]==="show"&&!o)return h.complete.call(this);if(k&&(l==="height"||l==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(qa(this.nodeName)=== "inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[l])){(h.specialEasing=h.specialEasing||{})[l]=a[l][1];a[l]=a[l][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(A,C){var J=new c.fx(x,h,A);if(vb.test(C))J[C==="toggle"?o?"show":"hide":C](a);else{var w=wb.exec(C),I=J.cur()||0;if(w){var L=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(x,A,(L||1)+g);I=(L|| 1)/J.cur()*I;c.style(x,A,I+g)}if(w[1])L=(w[1]==="-="?-1:1)*L+I;J.custom(I,L,g)}else J.custom(I,C,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b, d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a* Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(l){return f.step(l)} var f=this,h=c.fx;this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;e.elem=this.elem;if(e()&&c.timers.push(e)&&!ba)ba=setInterval(h.tick,h.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true; this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(k,o){f.style["overflow"+o]=h.overflow[k]})}this.options.hide&&c(this.elem).hide();if(this.options.hide|| this.options.show)for(var l in this.options.curAnim)c.style(this.elem,l,this.options.orig[l]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a= c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(ba);ba=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a=== b.elem}).length};var xb=/^t(?:able|d|h)$/i,Ia=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in t.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(l){c.offset.setOffset(this,a,l)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=fa(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&& h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(x){c.offset.setOffset(this,a,x)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d,e=b.offsetParent,f=b.ownerDocument,h=f.documentElement,l=f.body;d=(f=f.defaultView)?f.getComputedStyle(b,null):b.currentStyle; for(var k=b.offsetTop,o=b.offsetLeft;(b=b.parentNode)&&b!==l&&b!==h;){if(c.offset.supportsFixedPosition&&d.position==="fixed")break;d=f?f.getComputedStyle(b,null):b.currentStyle;k-=b.scrollTop;o-=b.scrollLeft;if(b===e){k+=b.offsetTop;o+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&xb.test(b.nodeName))){k+=parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}e=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"){k+= parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}d=d}if(d.position==="relative"||d.position==="static"){k+=l.offsetTop;o+=l.offsetLeft}if(c.offset.supportsFixedPosition&&d.position==="fixed"){k+=Math.max(h.scrollTop,l.scrollTop);o+=Math.max(h.scrollLeft,l.scrollLeft)}return{top:k,left:o}};c.offset={initialize:function(){var a=t.body,b=t.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px", height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells= f.offsetTop===5;e.style.position="fixed";e.style.top="20px";this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15;e.style.position=e.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a, "marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),l=c.css(a,"top"),k=c.css(a,"left"),o=e==="absolute"&&c.inArray("auto",[l,k])>-1;e={};var x={};if(o)x=f.position();l=o?x.top:parseInt(l,10)||0;k=o?x.left:parseInt(k,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+l;if(b.left!=null)e.left=b.left-h.left+k;"using"in b?b.using.call(a, e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Ia.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||t.body;a&&!Ia.test(a.nodeName)&& c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==B)return this.each(function(){if(h=fa(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=fa(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase(); c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(l){var k=c(this);k[d](e.call(this,l,k[d]()))});if(c.isWindow(f))return f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b];else if(f.nodeType===9)return Math.max(f.documentElement["client"+ b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]);else if(e===B){f=c.css(f,d);var h=parseFloat(f);return c.isNaN(h)?f:h}else return this.css(d,typeof e==="string"?e:e+"px")}})})(window);
packages/arwes/src/Line/Line.js
romelperez/prhone-ui
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import AnimationComponent from '../Animation'; export default function Line(props) { const { theme, classes, Animation, animation, animate, show, layer, className, ...etc } = props; const cls = cx(classes.root, className); return ( <Animation animate={animate} show={show} timeout={theme.animTime} {...animation} > {anim => ( <div className={cx(cls, classes[anim.status])} {...etc}> <div className={classes.line} /> <div className={classes.left} /> <div className={classes.right} /> </div> )} </Animation> ); } Line.propTypes = { Animation: PropTypes.any.isRequired, theme: PropTypes.any.isRequired, classes: PropTypes.any.isRequired, animate: PropTypes.bool, show: PropTypes.bool, animation: PropTypes.object, layer: PropTypes.oneOf([ 'primary', 'secondary', 'header', 'control', 'success', 'alert', 'disabled' ]) }; Line.defaultProps = { Animation: AnimationComponent, show: true, layer: 'primary' };
ajax/libs/qooxdoo/2.1.2/q.js
fastest963/cdnjs
/** qooxdoo v.2.1.2 | (c) 2012 1&1 Internet AG 1und1.de | qooxdoo.org/license */ (function(){ if (!window.qx) window.qx = {}; var qx = window.qx; if (!qx.$$environment) qx.$$environment = {}; var envinfo = {"json":true,"qx.application":"library.Application","qx.debug":false,"qx.debug.databinding":false,"qx.debug.dispose":false,"qx.debug.io":false,"qx.debug.ui.queue":false,"qx.optimization.variants":true,"qx.revision":"","qx.theme":"qx.theme.Modern","qx.version":"2.1.2"}; for (var k in envinfo) qx.$$environment[k] = envinfo[k]; qx.$$packageData = {}; /** qooxdoo v.2.1.2 | (c) 2012 1&1 Internet AG 1und1.de | qooxdoo.org/license */ qx.$$packageData['0']={"locales":{},"resources":{},"translations":{"C":{},"en":{}}}; /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Martin Wittemann (martinwittemann) ************************************************************************ */ /* ************************************************************************ #ignore(qx.data) #ignore(qx.data.IListData) #ignore(qx.util.OOUtil) ************************************************************************ */ /** * Create namespace */ if(!window.qx){ window.qx = { }; }; /** * Bootstrap qx.Bootstrap to create myself later * This is needed for the API browser etc. to let them detect me */ qx.Bootstrap = { genericToString : function(){ return "[Class " + this.classname + "]"; }, createNamespace : function(name, object){ var splits = name.split("."); var parent = window; var part = splits[0]; for(var i = 0,len = splits.length - 1;i < len;i++,part = splits[i]){ if(!parent[part]){ parent = parent[part] = { }; } else { parent = parent[part]; }; }; // store object parent[part] = object; // return last part name (e.g. classname) return part; }, setDisplayName : function(fcn, classname, name){ fcn.displayName = classname + "." + name + "()"; }, setDisplayNames : function(functionMap, classname){ for(var name in functionMap){ var value = functionMap[name]; if(value instanceof Function){ value.displayName = classname + "." + name + "()"; }; }; }, define : function(name, config){ if(!config){ var config = { statics : { } }; }; var clazz; var proto = null; qx.Bootstrap.setDisplayNames(config.statics, name); if(config.members || config.extend){ qx.Bootstrap.setDisplayNames(config.members, name + ".prototype"); clazz = config.construct || new Function; if(config.extend){ this.extendClass(clazz, clazz, config.extend, name, basename); }; var statics = config.statics || { }; // use keys to include the shadowed in IE for(var i = 0,keys = qx.Bootstrap.keys(statics),l = keys.length;i < l;i++){ var key = keys[i]; clazz[key] = statics[key]; }; proto = clazz.prototype; var members = config.members || { }; // use keys to include the shadowed in IE for(var i = 0,keys = qx.Bootstrap.keys(members),l = keys.length;i < l;i++){ var key = keys[i]; proto[key] = members[key]; }; } else { clazz = config.statics || { }; }; // Create namespace var basename = name ? this.createNamespace(name, clazz) : ""; // Store names in constructor/object clazz.name = clazz.classname = name; clazz.basename = basename; // Store type info clazz.$$type = "Class"; // Attach toString if(!clazz.hasOwnProperty("toString")){ clazz.toString = this.genericToString; }; // Execute defer section if(config.defer){ config.defer(clazz, proto); }; // Store class reference in global class registry qx.Bootstrap.$$registry[name] = clazz; return clazz; } }; /** * Internal class that is responsible for bootstrapping the qooxdoo * framework at load time. * * Does support: * * * Construct * * Statics * * Members * * Extend * * Defer * * Does not support: * * * Super class calls * * Mixins, Interfaces, Properties, ... */ qx.Bootstrap.define("qx.Bootstrap", { statics : { /** Timestamp of qooxdoo based application startup */ LOADSTART : qx.$$start || new Date(), /** * Mapping for early use of the qx.debug environment setting. */ DEBUG : (function(){ // make sure to reflect all changes here to the environment class! var debug = true; if(qx.$$environment && qx.$$environment["qx.debug"] === false){ debug = false; }; return debug; })(), /** * Minimal accessor API for the environment settings given from the * generator. * * WARNING: This method only should be used if the * {@link qx.core.Environment} class is not loaded! * * @param key {String} The key to get the value from. * @return {var} The value of the setting or <code>undefined</code>. */ getEnvironmentSetting : function(key){ if(qx.$$environment){ return qx.$$environment[key]; }; }, /** * Minimal mutator for the environment settings given from the generator. * It checks for the existance of the environment settings and sets the * key if its not given from the generator. If a setting is available from * the generator, the setting will be ignored. * * WARNING: This method only should be used if the * {@link qx.core.Environment} class is not loaded! * * @param key {String} The key of the setting. * @param value {var} The value for the setting. */ setEnvironmentSetting : function(key, value){ if(!qx.$$environment){ qx.$$environment = { }; }; if(qx.$$environment[key] === undefined){ qx.$$environment[key] = value; }; }, /** * Creates a namespace and assigns the given object to it. * * @internal * @param name {String} The complete namespace to create. Typically, the last part is the class name itself * @param object {Object} The object to attach to the namespace * @return {Object} last part of the namespace (typically the class name) * @throws {Error} when the given object already exists. */ createNamespace : qx.Bootstrap.createNamespace, /** * Define a new class using the qooxdoo class system. * Lightweight version of {@link qx.Class#define} only used during bootstrap phase. * * @internal * @signature function(name, config) * @param name {String?} Name of the class. If null, the class will not be * attached to a namespace. * @param config {Map ? null} Class definition structure. * @return {Class} The defined class */ define : qx.Bootstrap.define, /** * Sets the display name of the given function * * @signature function(fcn, classname, name) * @param fcn {Function} the function to set the display name for * @param classname {String} the name of the class the function is defined in * @param name {String} the function name */ setDisplayName : qx.Bootstrap.setDisplayName, /** * Set the names of all functions defined in the given map * * @signature function(functionMap, classname) * @param functionMap {Object} a map with functions as values * @param classname {String} the name of the class, the functions are * defined in */ setDisplayNames : qx.Bootstrap.setDisplayNames, /** * This method will be attached to all classes to return * a nice identifier for them. * * @internal * @signature function() * @return {String} The class identifier */ genericToString : qx.Bootstrap.genericToString, /** * Inherit a clazz from a super class. * * This function differentiates between class and constructor because the * constructor written by the user might be wrapped and the <code>base</code> * property has to be attached to the constructor, while the <code>superclass</code> * property has to be attached to the wrapped constructor. * * @param clazz {Function} The class's wrapped constructor * @param construct {Function} The unwrapped constructor * @param superClass {Function} The super class * @param name {Function} fully qualified class name * @param basename {Function} the base name */ extendClass : function(clazz, construct, superClass, name, basename){ var superproto = superClass.prototype; // Use helper function/class to save the unnecessary constructor call while // setting up inheritance. var helper = new Function(); helper.prototype = superproto; var proto = new helper(); // Apply prototype to new helper instance clazz.prototype = proto; // Store names in prototype proto.name = proto.classname = name; proto.basename = basename; /* - Store base constructor to constructor- - Store reference to extend class */ construct.base = superClass; clazz.superclass = superClass; /* - Store statics/constructor onto constructor/prototype - Store correct constructor - Store statics onto prototype */ construct.self = clazz.constructor = proto.constructor = clazz; }, /** * Find a class by its name * * @param name {String} class name to resolve * @return {Class} the class */ getByName : function(name){ return qx.Bootstrap.$$registry[name]; }, /** {Map} Stores all defined classes */ $$registry : { }, /* --------------------------------------------------------------------------- OBJECT UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Get the number of own properties in the object. * * @param map {Object} the map * @return {Integer} number of objects in the map * @lint ignoreUnused(key) */ objectGetLength : function(map){ return qx.Bootstrap.keys(map).length; }, /** * Inserts all keys of the source object into the * target objects. Attention: The target map gets modified. * * @param target {Object} target object * @param source {Object} object to be merged * @param overwrite {Boolean ? true} If enabled existing keys will be overwritten * @return {Object} Target with merged values from the source object */ objectMergeWith : function(target, source, overwrite){ if(overwrite === undefined){ overwrite = true; }; for(var key in source){ if(overwrite || target[key] === undefined){ target[key] = source[key]; }; }; return target; }, /** * IE does not return "shadowed" keys even if they are defined directly * in the object. * * @internal */ __shadowedKeys : ["isPrototypeOf", "hasOwnProperty", "toLocaleString", "toString", "valueOf", "propertyIsEnumerable", "constructor"], /** * Get the keys of a map as array as returned by a "for ... in" statement. * * @deprecated {2.1.} Please use Object.keys instead. * @param map {Object} the map * @return {Array} array of the keys of the map */ getKeys : function(map){ if(qx.Bootstrap.DEBUG){ qx.Bootstrap.warn("'qx.Bootstrap.getKeys' is deprecated. " + "Please use the native 'Object.keys()' instead."); }; return qx.Bootstrap.keys(map); }, /** * Get the keys of a map as array as returned by a "for ... in" statement. * * @signature function(map) * @internal * @param map {Object} the map * @return {Array} array of the keys of the map */ keys : ({ "ES5" : Object.keys, "BROKEN_IE" : function(map){ if(map === null || (typeof map != "object" && typeof map != "function")){ throw new TypeError("Object.keys requires an object as argument."); }; var arr = []; var hasOwnProperty = Object.prototype.hasOwnProperty; for(var key in map){ if(hasOwnProperty.call(map, key)){ arr.push(key); }; }; // IE does not return "shadowed" keys even if they are defined directly // in the object. This is incompatible with the ECMA standard!! // This is why this checks are needed. var shadowedKeys = qx.Bootstrap.__shadowedKeys; for(var i = 0,a = shadowedKeys,l = a.length;i < l;i++){ if(hasOwnProperty.call(map, a[i])){ arr.push(a[i]); }; }; return arr; }, "default" : function(map){ if(map === null || (typeof map != "object" && typeof map != "function")){ throw new TypeError("Object.keys requires an object as argument."); }; var arr = []; var hasOwnProperty = Object.prototype.hasOwnProperty; for(var key in map){ if(hasOwnProperty.call(map, key)){ arr.push(key); }; }; return arr; } })[typeof (Object.keys) == "function" ? "ES5" : (function(){ for(var key in { toString : 1 }){ return key; }; })() !== "toString" ? "BROKEN_IE" : "default"], /** * Get the keys of a map as string * * @param map {Object} the map * @deprecated {2.1} Object.keys(map).join('\", "'). * @return {String} String of the keys of the map * The keys are separated by ", " */ getKeysAsString : function(map){ { }; var keys = qx.Bootstrap.keys(map); if(keys.length == 0){ return ""; }; return '"' + keys.join('\", "') + '"'; }, /** * Mapping from JavaScript string representation of objects to names * @internal */ __classToTypeMap : { "[object String]" : "String", "[object Array]" : "Array", "[object Object]" : "Object", "[object RegExp]" : "RegExp", "[object Number]" : "Number", "[object Boolean]" : "Boolean", "[object Date]" : "Date", "[object Function]" : "Function", "[object Error]" : "Error" }, /* --------------------------------------------------------------------------- FUNCTION UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Returns a function whose "this" is altered. * * *Syntax* * * <pre class='javascript'>qx.Bootstrap.bind(myFunction, [self, [varargs...]]);</pre> * * *Example* * * <pre class='javascript'> * function myFunction() * { * this.setStyle('color', 'red'); * // note that 'this' here refers to myFunction, not an element * // we'll need to bind this function to the element we want to alter * }; * * var myBoundFunction = qx.Bootstrap.bind(myFunction, myElement); * myBoundFunction(); // this will make the element myElement red. * </pre> * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Function} The bound function. */ bind : function(func, self, varargs){ var fixedArgs = Array.prototype.slice.call(arguments, 2, arguments.length); return function(){ var args = Array.prototype.slice.call(arguments, 0, arguments.length); return func.apply(self, fixedArgs.concat(args)); }; }, /* --------------------------------------------------------------------------- STRING UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Convert the first character of the string to upper case. * * @param str {String} the string * @return {String} the string with an upper case first character */ firstUp : function(str){ return str.charAt(0).toUpperCase() + str.substr(1); }, /** * Convert the first character of the string to lower case. * * @param str {String} the string * @return {String} the string with a lower case first character */ firstLow : function(str){ return str.charAt(0).toLowerCase() + str.substr(1); }, /* --------------------------------------------------------------------------- TYPE UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Get the internal class of the value. See * http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ * for details. * * @param value {var} value to get the class for * @return {String} the internal class of the value */ getClass : function(value){ var classString = Object.prototype.toString.call(value); return (qx.Bootstrap.__classToTypeMap[classString] || classString.slice(8, -1)); }, /** * Whether the value is a string. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a string. */ isString : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof String" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (typeof value === "string" || qx.Bootstrap.getClass(value) == "String" || value instanceof String || (!!value && !!value.$$isString))); }, /** * Whether the value is an array. * * @param value {var} Value to check. * @return {Boolean} Whether the value is an array. */ isArray : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Array" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (value instanceof Array || (value && qx.data && qx.data.IListData && qx.util.OOUtil.hasInterface(value.constructor, qx.data.IListData)) || qx.Bootstrap.getClass(value) == "Array" || (!!value && !!value.$$isArray))); }, /** * Whether the value is an object. Note that built-in types like Window are * not reported to be objects. * * @param value {var} Value to check. * @return {Boolean} Whether the value is an object. */ isObject : function(value){ return (value !== undefined && value !== null && qx.Bootstrap.getClass(value) == "Object"); }, /** * Whether the value is a function. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a function. */ isFunction : function(value){ return qx.Bootstrap.getClass(value) == "Function"; }, /* --------------------------------------------------------------------------- LOGGING UTILITY FUNCTIONS --------------------------------------------------------------------------- */ $$logs : [], /** * Sending a message at level "debug" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ debug : function(object, message){ qx.Bootstrap.$$logs.push(["debug", arguments]); }, /** * Sending a message at level "info" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ info : function(object, message){ qx.Bootstrap.$$logs.push(["info", arguments]); }, /** * Sending a message at level "warn" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ warn : function(object, message){ qx.Bootstrap.$$logs.push(["warn", arguments]); }, /** * Sending a message at level "error" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ error : function(object, message){ qx.Bootstrap.$$logs.push(["error", arguments]); }, /** * Prints the current stack trace at level "info" * * @param object {Object} Contextual object (either instance or static class) */ trace : function(object){ } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2005-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is the single point to access all settings that may be different * in different environments. This contains e.g. the browser name, engine * version but also qooxdoo or application specific settings. * * Its public API can be found in its four main methods. One pair of methods * is used to check the synchronous values of the environment. The other pair * of methods is used for asynchronous checks. * * The most often used method should be {@link #get}, which returns the * current value for a given environment check. * * All qooxdoo settings can be changed via the generator's config. See the manual * for more details about the environment key in the config. As you can see * from the methods API, there is no way to override an existing key. So if you * need to change a qooxdoo setting, you have to use the generator to do so. * * The following table shows the available checks. If you are * interested in more details, check the reference to the implementation of * each check. Please do not use those check implementations directly, as the * Environment class comes with a smart caching feature. * * <table border="0" cellspacing="10"> * <tbody> * <tr> * <td colspan="4"><h2>Synchronous checks</h2> * </td> * </tr> * <tr> * <th><h3>Key</h3></th> * <th><h3>Type</h3></th> * <th><h3>Example</h3></th> * <th><h3>Details</h3></th> * </tr> * <tr> * <td colspan="4"><b>browser</b></td> * </tr> * <tr> * <td>browser.documentmode</td><td><i>Integer</i></td><td><code>0</code></td> * <td>{@link qx.bom.client.Browser#getDocumentMode}</td> * </tr> * <tr> * <td>browser.name</td><td><i>String</i></td><td><code> chrome </code></td> * <td>{@link qx.bom.client.Browser#getName}</td> * </tr> * <tr> * <td>browser.quirksmode</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Browser#getQuirksMode}</td> * </tr> * <tr> * <td>browser.version</td><td><i>String</i></td><td><code>11.0</code></td> * <td>{@link qx.bom.client.Browser#getVersion}</td> * </tr> * <tr> * <td colspan="4"><b>runtime</b></td> * </tr> * <tr> * <td>runtime.name</td><td><i> String </i></td><td><code> node.js </code></td> * <td>{@link qx.bom.client.Runtime#getName}</td> * </tr> * <tr> * <td colspan="4"><b>css</b></td> * </tr> * <tr> * <td>css.borderradius</td><td><i>String</i> or <i>null</i></td><td><code>borderRadius</code></td> * <td>{@link qx.bom.client.Css#getBorderRadius}</td> * </tr> * <tr> * <td>css.borderimage</td><td><i>String</i> or <i>null</i></td><td><code>WebkitBorderImage</code></td> * <td>{@link qx.bom.client.Css#getBorderImage}</td> * </tr> * <tr> * <td>css.borderimage.standardsyntax</td><td><i>Boolean</i> or <i>null</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getBorderImageSyntax}</td> * </tr> * <tr> * <td>css.boxmodel</td><td><i>String</i></td><td><code>content</code></td> * <td>{@link qx.bom.client.Css#getBoxModel}</td> * </tr> * <tr> * <td>css.boxshadow</td><td><i>String</i> or <i>null</i></td><td><code>boxShadow</code></td> * <td>{@link qx.bom.client.Css#getBoxShadow}</td> * </tr> * <tr> * <td>css.gradient.linear</td><td><i>String</i> or <i>null</i></td><td><code>-moz-linear-gradient</code></td> * <td>{@link qx.bom.client.Css#getLinearGradient}</td> * </tr> * <tr> * <td>css.gradient.filter</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getFilterGradient}</td> * </tr> * <tr> * <td>css.gradient.radial</td><td><i>String</i> or <i>null</i></td><td><code>-moz-radial-gradient</code></td> * <td>{@link qx.bom.client.Css#getRadialGradient}</td> * </tr> * <tr> * <td>css.gradient.legacywebkit</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Css#getLegacyWebkitGradient}</td> * </tr> * <tr> * <td>css.placeholder</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getPlaceholder}</td> * </tr> * <tr> * <td>css.textoverflow</td><td><i>String</i> or <i>null</i></td><td><code>textOverflow</code></td> * <td>{@link qx.bom.client.Css#getTextOverflow}</td> * </tr> * <tr> * <td>css.rgba</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getRgba}</td> * </tr> * <tr> * <td>css.usermodify</td><td><i>String</i> or <i>null</i></td><td><code>WebkitUserModify</code></td> * <td>{@link qx.bom.client.Css#getUserModify}</td> * </tr> * <tr> * <td>css.appearance</td><td><i>String</i> or <i>null</i></td><td><code>WebkitAppearance</code></td> * <td>{@link qx.bom.client.Css#getAppearance}</td> * </tr> * <tr> * <td>css.float</td><td><i>String</i> or <i>null</i></td><td><code>cssFloat</code></td> * <td>{@link qx.bom.client.Css#getFloat}</td> * </tr> * <tr> * <td>css.userselect</td><td><i>String</i> or <i>null</i></td><td><code>WebkitUserSelect</code></td> * <td>{@link qx.bom.client.Css#getUserSelect}</td> * </tr> * <tr> * <td>css.userselect.none</td><td><i>String</i> or <i>null</i></td><td><code>-moz-none</code></td> * <td>{@link qx.bom.client.Css#getUserSelectNone}</td> * </tr> * <tr> * <td>css.boxsizing</td><td><i>String</i> or <i>null</i></td><td><code>boxSizing</code></td> * <td>{@link qx.bom.client.Css#getBoxSizing}</td> * </tr> * <tr> * <td>css.animation</td><td><i>Object</i> or <i>null</i></td><td><code>{end-event: "webkitAnimationEnd", keyframes: "@-webkit-keyframes", play-state: null, name: "WebkitAnimation"}</code></td> * <td>{@link qx.bom.client.CssAnimation#getSupport}</td> * </tr> * <tr> * <td>css.animation.requestframe</td><td><i>String</i> or <i>null</i></td><td><code>mozRequestAnimationFrame</code></td> * <td>{@link qx.bom.client.CssAnimation#getRequestAnimationFrame}</td> * </tr> * <tr> * <td>css.transform</td><td><i>Object</i> or <i>null</i></td><td><code>{3d: true, origin: "WebkitTransformOrigin", name: "WebkitTransform", style: "WebkitTransformStyle", perspective: "WebkitPerspective", perspective-origin: "WebkitPerspectiveOrigin", backface-visibility: "WebkitBackfaceVisibility"}</code></td> * <td>{@link qx.bom.client.CssTransform#getSupport}</td> * </tr> * <tr> * <td>css.transform.3d</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.CssTransform#get3D}</td> * </tr> * <tr> * <td>css.inlineblock</td><td><i>String</i> or <i>null</i></td><td><code>inline-block</code></td> * <td>{@link qx.bom.client.Css#getInlineBlock}</td> * </tr> * <tr> * <td>css.opacity</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getOpacity}</td> * </tr> * <tr> * <td>deprecated since 2.1: css.overflowxy</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getOverflowXY}</td> * </tr> * <tr> * <td>css.textShadow</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getTextShadow}</td> * </tr> * <tr> * <td>css.textShadow.filter</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getFilterTextShadow}</td> * </tr> * <tr> * <td colspan="4"><b>device</b></td> * </tr> * <tr> * <td>device.name</td><td><i>String</i></td><td><code>pc</code></td> * <td>{@link qx.bom.client.Device#getName}</td> * </tr> * <tr> * <td>device.type</td><td><i>String</i></td><td><code>mobile</code></td> * <td>{@link qx.bom.client.Device#getType}</td> * </tr> * <tr> * <td colspan="4"><b>ecmascript</b></td> * </tr> * <tr> * <td>ecmascript.error.stacktrace</td><td><i>String</i> or <i>null</i></td><td><code>stack</code></td> * <td>{@link qx.bom.client.EcmaScript#getStackTrace}</td> * </tr> * <tr> * <td>ecmascript.array.indexof<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayIndexOf}</td> * </tr> * <tr> * <td>ecmascript.array.lastindexof<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayLastIndexOf}</td> * </tr> * <tr> * <td>ecmascript.array.foreach<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayForEach}</td> * </tr> * <tr> * <td>ecmascript.array.filter<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayFilter}</td> * </tr> * <tr> * <td>ecmascript.array.map<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayMap}</td> * </tr> * <tr> * <td>ecmascript.array.some<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArraySome}</td> * </tr> * <tr> * <td>ecmascript.array.every<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayEvery}</td> * </tr> * <tr> * <td>ecmascript.array.reduce<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayReduce}</td> * </tr> * <tr> * <td>ecmascript.array.reduceright<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayReduceRight}</td> * </tr> * <tr> * <td>ecmascript.function.bind<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getFunctionBind}</td> * </tr> * <tr> * <td>ecmascript.object.keys<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getObjectKeys}</td> * </tr> * <tr> * <td>ecmascript.date.now<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getDateNow}</td> * </tr> * <tr> * <td>ecmascript.error.toString</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getErrorToString}</td> * </tr> * <tr> * <td>ecmascript.string.trim</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getStringTrim}</td> * </tr> * <tr> * <td colspan="4"><b>engine</b></td> * </tr> * <tr> * <td>engine.name</td><td><i>String</i></td><td><code>webkit</code></td> * <td>{@link qx.bom.client.Engine#getName}</td> * </tr> * <tr> * <td>engine.version</td><td><i>String</i></td><td><code>534.24</code></td> * <td>{@link qx.bom.client.Engine#getVersion}</td> * </tr> * <tr> * <td colspan="4"><b>event</b></td> * </tr> * <tr> * <td>event.pointer</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Event#getPointer}</td> * </tr> * <tr> * <td>event.mspointer</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Event#getMsPointer}</td> * </tr> * <tr> * <td>event.touch</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Event#getTouch}</td> * </tr> * <tr> * <td>event.help</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Event#getHelp}</td> * </tr> * <tr> * <td>event.hashchange</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Event#getHashChange}</td> * </tr> * <tr> * <td colspan="4"><b>html</b></td> * </tr> * <tr> * <td>html.audio</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getAudio}</td> * </tr> * <tr> * <td>html.audio.mp3</td><td><i>String</i></td><td><code>""</code></td> * <td>{@link qx.bom.client.Html#getAudioMp3}</td> * </tr> * <tr> * <td>html.audio.ogg</td><td><i>String</i></td><td><code>"maybe"</code></td> * <td>{@link qx.bom.client.Html#getAudioOgg}</td> * </tr> * <tr> * <td>html.audio.wav</td><td><i>String</i></td><td><code>"probably"</code></td> * <td>{@link qx.bom.client.Html#getAudioWav}</td> * </tr> * <tr> * <td>html.audio.au</td><td><i>String</i></td><td><code>"maybe"</code></td> * <td>{@link qx.bom.client.Html#getAudioAu}</td> * </tr> * <tr> * <td>html.audio.aif</td><td><i>String</i></td><td><code>"probably"</code></td> * <td>{@link qx.bom.client.Html#getAudioAif}</td> * </tr> * <tr> * <td>html.canvas</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getCanvas}</td> * </tr> * <tr> * <td>html.classlist</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getClassList}</td> * </tr> * <tr> * <td>html.geolocation</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getGeoLocation}</td> * </tr> * <tr> * <td>html.storage.local</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getLocalStorage}</td> * </tr> * <tr> * <td>html.storage.session</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getSessionStorage}</td> * </tr> * <tr> * <td>html.storage.userdata</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getUserDataStorage}</td> * </tr> * <tr> * <td>html.svg</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getSvg}</td> * </tr> * <tr> * <td>html.video</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getVideo}</td> * </tr> * <tr> * <td>html.video.h264</td><td><i>String</i></td><td><code>"probably"</code></td> * <td>{@link qx.bom.client.Html#getVideoH264}</td> * </tr> * <tr> * <td>html.video.ogg</td><td><i>String</i></td><td><code>""</code></td> * <td>{@link qx.bom.client.Html#getVideoOgg}</td> * </tr> * <tr> * <td>html.video.webm</td><td><i>String</i></td><td><code>"maybe"</code></td> * <td>{@link qx.bom.client.Html#getVideoWebm}</td> * </tr> * <tr> * <td>html.vml</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Html#getVml}</td> * </tr> * <tr> * <td>html.webworker</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getWebWorker}</td> * <tr> * <td>html.filereader</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getFileReader}</td> * </tr> * <tr> * <td>html.xpath</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getXPath}</td> * </tr> * <tr> * <td>html.xul</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getXul}</td> * </tr> * <tr> * <td>html.console</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getConsole}</td> * </tr> * <tr> * <td>html.element.contains</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getContains}</td> * </tr> * <tr> * <td>html.element.compareDocumentPosition</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getCompareDocumentPosition}</td> * </tr> * <tr> * <td>html.element.textContent</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getTextContent}</td> * </tr> * <tr> * <td>html.image.naturaldimensions</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getNaturalDimensions}</td> * </tr> * <tr> * <td>html.history.state</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getHistoryState}</td> * </tr> * <tr> * <td>html.selection</td><td><i>String</i></td><td><code>getSelection</code></td> * <td>{@link qx.bom.client.Html#getSelection}</td> * </tr> * <tr> * <td colspan="4"><b>XML</b></td> * </tr> * <tr> * <td>xml.implementation</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getImplementation}</td> * </tr> * <tr> * <td>xml.domparser</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getDomParser}</td> * </tr> * <tr> * <td>xml.selectsinglenode</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getSelectSingleNode}</td> * </tr> * <tr> * <td>xml.selectnodes</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getSelectNodes}</td> * </tr> * <tr> * <td>xml.getelementsbytagnamens</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getElementsByTagNameNS}</td> * </tr> * <tr> * <td>xml.domproperties</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getDomProperties}</td> * </tr> * <tr> * <td>xml.attributens</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getAttributeNS}</td> * </tr> * <tr> * <td>xml.createelementns</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getCreateElementNS}</td> * </tr> * <tr> * <td>xml.createnode</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getCreateNode}</td> * </tr> * <tr> * <td>xml.getqualifieditem</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getQualifiedItem}</td> * </tr> * <tr> * <td colspan="4"><b>Stylesheets</b></td> * </tr> * <tr> * <td>html.stylesheet.createstylesheet</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Stylesheet#getCreateStyleSheet}</td> * </tr> * <tr> * <td>html.stylesheet.insertrule</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Stylesheet#getInsertRule}</td> * </tr> * <tr> * <td>html.stylesheet.deleterule</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Stylesheet#getDeleteRule}</td> * </tr> * <tr> * <td>html.stylesheet.addimport</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Stylesheet#getAddImport}</td> * </tr> * <tr> * <td>html.stylesheet.removeimport</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Stylesheet#getRemoveImport}</td> * </tr> * <tr> * <td colspan="4"><b>io</b></td> * </tr> * <tr> * <td>io.maxrequests</td><td><i>Integer</i></td><td><code>4</code></td> * <td>{@link qx.bom.client.Transport#getMaxConcurrentRequestCount}</td> * </tr> * <tr> * <td>io.ssl</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Transport#getSsl}</td> * </tr> * <tr> * <td>io.xhr</td><td><i>String</i></td><td><code>xhr</code></td> * <td>{@link qx.bom.client.Transport#getXmlHttpRequest}</td> * </tr> * <tr> * <td colspan="4"><b>locale</b></td> * </tr> * <tr> * <td>locale</td><td><i>String</i></td><td><code>de</code></td> * <td>{@link qx.bom.client.Locale#getLocale}</td> * </tr> * <tr> * <td>locale.variant</td><td><i>String</i></td><td><code>de</code></td> * <td>{@link qx.bom.client.Locale#getVariant}</td> * </tr> * <tr> * <td colspan="4"><b>os</b></td> * </tr> * <tr> * <td>os.name</td><td><i>String</i></td><td><code>osx</code></td> * <td>{@link qx.bom.client.OperatingSystem#getName}</td> * </tr> * <tr> * <td>os.version</td><td><i>String</i></td><td><code>10.6</code></td> * <td>{@link qx.bom.client.OperatingSystem#getVersion}</td> * </tr> * <tr> * <td>os.scrollBarOverlayed</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Scroll#scrollBarOverlayed}</td> * </tr> * <tr> * <td colspan="4"><b>phonegap</b></td> * </tr> * <tr> * <td>phonegap</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.PhoneGap#getPhoneGap}</td> * </tr> * <tr> * <td>phonegap.notification</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.PhoneGap#getNotification}</td> * </tr> * <tr> * <td colspan="4"><b>plugin</b></td> * </tr> * <tr> * <td>plugin.divx</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getDivX}</td> * </tr> * <tr> * <td>plugin.divx.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getDivXVersion}</td> * </tr> * <tr> * <td>plugin.flash</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Flash#isAvailable}</td> * </tr> * <tr> * <td>plugin.flash.express</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Flash#getExpressInstall}</td> * </tr> * <tr> * <td>plugin.flash.strictsecurity</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Flash#getStrictSecurityModel}</td> * </tr> * <tr> * <td>plugin.flash.version</td><td><i>String</i></td><td><code>10.2.154</code></td> * <td>{@link qx.bom.client.Flash#getVersion}</td> * </tr> * <tr> * <td>plugin.gears</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getGears}</td> * </tr> * <tr> * <td>plugin.activex</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getActiveX}</td> * </tr> * <tr> * <td>plugin.skype</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getSkype}</td> * </tr> * <tr> * <td>plugin.pdf</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getPdf}</td> * </tr> * <tr> * <td>plugin.pdf.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getPdfVersion}</td> * </tr> * <tr> * <td>plugin.quicktime</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Plugin#getQuicktime}</td> * </tr> * <tr> * <td>plugin.quicktime.version</td><td><i>String</i></td><td><code>7.6</code></td> * <td>{@link qx.bom.client.Plugin#getQuicktimeVersion}</td> * </tr> * <tr> * <td>plugin.silverlight</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getSilverlight}</td> * </tr> * <tr> * <td>plugin.silverlight.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getSilverlightVersion}</td> * </tr> * <tr> * <td>plugin.windowsmedia</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getWindowsMedia}</td> * </tr> * <tr> * <td>plugin.windowsmedia.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getWindowsMediaVersion}</td> * </tr> * <tr> * <td colspan="4"><b>qx</b></td> * </tr> * <tr> * <td>qx.allowUrlSettings</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.allowUrlVariants</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.application</td><td><i>String</i></td><td><code>name.space</code></td> * <td><i>default:</i> <code>&lt;&lt;application name&gt;&gt;</code></td> * </tr> * <tr> * <td>qx.aspects</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.debug.databinding</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug.dispose</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug.dispose.level</td><td><i>Integer</i></td><td><code>0</code></td> * <td><i>default:</i> <code>0</code></td> * </tr> * <tr> * <td>qx.debug.io</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <tr> * <td>qx.debug.io.remote</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <tr> * <td>qx.debug.io.remote.data</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug.property.level</td><td><i>Integer</i></td><td><code>0</code></td> * <td><i>default:</i> <code>0</code></td> * </tr> * <tr> * <td>qx.debug.ui.queue</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.dynamicmousewheel</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.dynlocale</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.globalErrorHandling</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.mobile.emulatetouch</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.mobile.nativescroll</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.optimization.basecalls</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.comments</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.privates</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.strings</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.variables</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.variants</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.revision</td><td><i>String</i></td><td><code>27348</code></td> * </tr> * <tr> * <td>qx.theme</td><td><i>String</i></td><td><code>qx.theme.Modern</code></td> * <td><i>default:</i> <code>&lt;&lt;initial theme name&gt;&gt;</code></td> * </tr> * <tr> * <td>qx.version</td><td><i>String</i></td><td><code>${qxversion}</code></td> * </tr> * <tr> * <td>qx.blankpage</td><td><i>String</i></td><td><code>URI to blank.html page</code></td> * </tr> * <tr> * <td colspan="4"><b>module</b></td> * </tr> * <tr> * <td>module.databinding</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>module.logger</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>module.property</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>module.events</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td colspan="4"><h3>Asynchronous checks</h3> * </td> * </tr> * <tr> * <td>html.dataurl</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getDataUrl}</td> * </tr> * </tbody> * </table> * */ qx.Bootstrap.define("qx.core.Environment", { statics : { /** Map containing the synchronous check functions. */ _checks : { }, /** Map containing the asynchronous check functions. */ _asyncChecks : { }, /** Internal cache for all checks. */ __cache : { }, /** Internal map for environment keys to check methods. */ _checksMap : { "engine.version" : "qx.bom.client.Engine.getVersion", "engine.name" : "qx.bom.client.Engine.getName", "browser.name" : "qx.bom.client.Browser.getName", "browser.version" : "qx.bom.client.Browser.getVersion", "browser.documentmode" : "qx.bom.client.Browser.getDocumentMode", "browser.quirksmode" : "qx.bom.client.Browser.getQuirksMode", "runtime.name" : "qx.bom.client.Runtime.getName", "device.name" : "qx.bom.client.Device.getName", "device.type" : "qx.bom.client.Device.getType", "locale" : "qx.bom.client.Locale.getLocale", "locale.variant" : "qx.bom.client.Locale.getVariant", "os.name" : "qx.bom.client.OperatingSystem.getName", "os.version" : "qx.bom.client.OperatingSystem.getVersion", "os.scrollBarOverlayed" : "qx.bom.client.Scroll.scrollBarOverlayed", "plugin.gears" : "qx.bom.client.Plugin.getGears", "plugin.activex" : "qx.bom.client.Plugin.getActiveX", "plugin.skype" : "qx.bom.client.Plugin.getSkype", "plugin.quicktime" : "qx.bom.client.Plugin.getQuicktime", "plugin.quicktime.version" : "qx.bom.client.Plugin.getQuicktimeVersion", "plugin.windowsmedia" : "qx.bom.client.Plugin.getWindowsMedia", "plugin.windowsmedia.version" : "qx.bom.client.Plugin.getWindowsMediaVersion", "plugin.divx" : "qx.bom.client.Plugin.getDivX", "plugin.divx.version" : "qx.bom.client.Plugin.getDivXVersion", "plugin.silverlight" : "qx.bom.client.Plugin.getSilverlight", "plugin.silverlight.version" : "qx.bom.client.Plugin.getSilverlightVersion", "plugin.flash" : "qx.bom.client.Flash.isAvailable", "plugin.flash.version" : "qx.bom.client.Flash.getVersion", "plugin.flash.express" : "qx.bom.client.Flash.getExpressInstall", "plugin.flash.strictsecurity" : "qx.bom.client.Flash.getStrictSecurityModel", "plugin.pdf" : "qx.bom.client.Plugin.getPdf", "plugin.pdf.version" : "qx.bom.client.Plugin.getPdfVersion", "io.maxrequests" : "qx.bom.client.Transport.getMaxConcurrentRequestCount", "io.ssl" : "qx.bom.client.Transport.getSsl", "io.xhr" : "qx.bom.client.Transport.getXmlHttpRequest", "event.touch" : "qx.bom.client.Event.getTouch", "event.pointer" : "qx.bom.client.Event.getPointer", "event.help" : "qx.bom.client.Event.getHelp", "event.hashchange" : "qx.bom.client.Event.getHashChange", "ecmascript.stacktrace" : "qx.bom.client.EcmaScript.getStackTrace", // @deprecated {2.1} "ecmascript.error.stacktrace" : "qx.bom.client.EcmaScript.getStackTrace", "ecmascript.array.indexof" : "qx.bom.client.EcmaScript.getArrayIndexOf", "ecmascript.array.lastindexof" : "qx.bom.client.EcmaScript.getArrayLastIndexOf", "ecmascript.array.foreach" : "qx.bom.client.EcmaScript.getArrayForEach", "ecmascript.array.filter" : "qx.bom.client.EcmaScript.getArrayFilter", "ecmascript.array.map" : "qx.bom.client.EcmaScript.getArrayMap", "ecmascript.array.some" : "qx.bom.client.EcmaScript.getArraySome", "ecmascript.array.every" : "qx.bom.client.EcmaScript.getArrayEvery", "ecmascript.array.reduce" : "qx.bom.client.EcmaScript.getArrayReduce", "ecmascript.array.reduceright" : "qx.bom.client.EcmaScript.getArrayReduceRight", "ecmascript.function.bind" : "qx.bom.client.EcmaScript.getFunctionBind", "ecmascript.object.keys" : "qx.bom.client.EcmaScript.getObjectKeys", "ecmascript.date.now" : "qx.bom.client.EcmaScript.getDateNow", "ecmascript.error.toString" : "qx.bom.client.EcmaScript.getErrorToString", "ecmascript.string.trim" : "qx.bom.client.EcmaScript.getStringTrim", "html.webworker" : "qx.bom.client.Html.getWebWorker", "html.filereader" : "qx.bom.client.Html.getFileReader", "html.geolocation" : "qx.bom.client.Html.getGeoLocation", "html.audio" : "qx.bom.client.Html.getAudio", "html.audio.ogg" : "qx.bom.client.Html.getAudioOgg", "html.audio.mp3" : "qx.bom.client.Html.getAudioMp3", "html.audio.wav" : "qx.bom.client.Html.getAudioWav", "html.audio.au" : "qx.bom.client.Html.getAudioAu", "html.audio.aif" : "qx.bom.client.Html.getAudioAif", "html.video" : "qx.bom.client.Html.getVideo", "html.video.ogg" : "qx.bom.client.Html.getVideoOgg", "html.video.h264" : "qx.bom.client.Html.getVideoH264", "html.video.webm" : "qx.bom.client.Html.getVideoWebm", "html.storage.local" : "qx.bom.client.Html.getLocalStorage", "html.storage.session" : "qx.bom.client.Html.getSessionStorage", "html.storage.userdata" : "qx.bom.client.Html.getUserDataStorage", "html.classlist" : "qx.bom.client.Html.getClassList", "html.xpath" : "qx.bom.client.Html.getXPath", "html.xul" : "qx.bom.client.Html.getXul", "html.canvas" : "qx.bom.client.Html.getCanvas", "html.svg" : "qx.bom.client.Html.getSvg", "html.vml" : "qx.bom.client.Html.getVml", "html.dataset" : "qx.bom.client.Html.getDataset", "html.dataurl" : "qx.bom.client.Html.getDataUrl", "html.console" : "qx.bom.client.Html.getConsole", "html.stylesheet.createstylesheet" : "qx.bom.client.Stylesheet.getCreateStyleSheet", "html.stylesheet.insertrule" : "qx.bom.client.Stylesheet.getInsertRule", "html.stylesheet.deleterule" : "qx.bom.client.Stylesheet.getDeleteRule", "html.stylesheet.addimport" : "qx.bom.client.Stylesheet.getAddImport", "html.stylesheet.removeimport" : "qx.bom.client.Stylesheet.getRemoveImport", "html.element.contains" : "qx.bom.client.Html.getContains", "html.element.compareDocumentPosition" : "qx.bom.client.Html.getCompareDocumentPosition", "html.element.textcontent" : "qx.bom.client.Html.getTextContent", "html.image.naturaldimensions" : "qx.bom.client.Html.getNaturalDimensions", "html.history.state" : "qx.bom.client.Html.getHistoryState", "html.selection" : "qx.bom.client.Html.getSelection", "json" : "qx.bom.client.Json.getJson", "css.textoverflow" : "qx.bom.client.Css.getTextOverflow", "css.placeholder" : "qx.bom.client.Css.getPlaceholder", "css.borderradius" : "qx.bom.client.Css.getBorderRadius", "css.borderimage" : "qx.bom.client.Css.getBorderImage", "css.borderimage.standardsyntax" : "qx.bom.client.Css.getBorderImageSyntax", "css.boxshadow" : "qx.bom.client.Css.getBoxShadow", "css.gradient.linear" : "qx.bom.client.Css.getLinearGradient", "css.gradient.filter" : "qx.bom.client.Css.getFilterGradient", "css.gradient.radial" : "qx.bom.client.Css.getRadialGradient", "css.gradient.legacywebkit" : "qx.bom.client.Css.getLegacyWebkitGradient", "css.boxmodel" : "qx.bom.client.Css.getBoxModel", "css.rgba" : "qx.bom.client.Css.getRgba", "css.userselect" : "qx.bom.client.Css.getUserSelect", "css.userselect.none" : "qx.bom.client.Css.getUserSelectNone", "css.usermodify" : "qx.bom.client.Css.getUserModify", "css.appearance" : "qx.bom.client.Css.getAppearance", "css.float" : "qx.bom.client.Css.getFloat", "css.boxsizing" : "qx.bom.client.Css.getBoxSizing", "css.animation" : "qx.bom.client.CssAnimation.getSupport", "css.animation.requestframe" : "qx.bom.client.CssAnimation.getRequestAnimationFrame", "css.transform" : "qx.bom.client.CssTransform.getSupport", "css.transform.3d" : "qx.bom.client.CssTransform.get3D", "css.inlineblock" : "qx.bom.client.Css.getInlineBlock", "css.opacity" : "qx.bom.client.Css.getOpacity", "css.overflowxy" : "qx.bom.client.Css.getOverflowXY", // @deprecated {2.1} "css.textShadow" : "qx.bom.client.Css.getTextShadow", "css.textShadow.filter" : "qx.bom.client.Css.getFilterTextShadow", "phonegap" : "qx.bom.client.PhoneGap.getPhoneGap", "phonegap.notification" : "qx.bom.client.PhoneGap.getNotification", "xml.implementation" : "qx.bom.client.Xml.getImplementation", "xml.domparser" : "qx.bom.client.Xml.getDomParser", "xml.selectsinglenode" : "qx.bom.client.Xml.getSelectSingleNode", "xml.selectnodes" : "qx.bom.client.Xml.getSelectNodes", "xml.getelementsbytagnamens" : "qx.bom.client.Xml.getElementsByTagNameNS", "xml.domproperties" : "qx.bom.client.Xml.getDomProperties", "xml.attributens" : "qx.bom.client.Xml.getAttributeNS", "xml.createnode" : "qx.bom.client.Xml.getCreateNode", "xml.getqualifieditem" : "qx.bom.client.Xml.getQualifiedItem", "xml.createelementns" : "qx.bom.client.Xml.getCreateElementNS" }, /** * The default accessor for the checks. It returns the value the current * environment has for the given key. The key could be something like * "qx.debug", "css.textoverflow" or "io.ssl". A complete list of * checks can be found in the class comment of this class. * * Please keep in mind that the result is cached. If you want to run the * check function again in case something could have been changed, take a * look at the {@link #invalidateCacheKey} function. * * @param key {String} The name of the check you want to query. * @return {var} The stored value depending on the given key. * (Details in the class doc) */ get : function(key){ if(qx.Bootstrap.DEBUG){ // @deprecated {2.1} if(key == "css.overflowxy"){ qx.Bootstrap.warn("The environment key 'css.overflowxy' is deprecated."); }; // @deprecated {2.1} if(key == "ecmascript.stacktrace"){ qx.Bootstrap.warn("The environment key 'ecmascript.stacktrace' is now 'ecmascript.error.stacktrace'."); key = "ecmascript.error.stacktrace"; }; }; // check the cache if(this.__cache[key] != undefined){ return this.__cache[key]; }; // search for a matching check var check = this._checks[key]; if(check){ // execute the check and write the result in the cache var value = check(); this.__cache[key] = value; return value; }; // try class lookup var classAndMethod = this._getClassNameFromEnvKey(key); if(classAndMethod[0] != undefined){ var clazz = classAndMethod[0]; var method = classAndMethod[1]; var value = clazz[method](); // call the check method this.__cache[key] = value; return value; }; // debug flag if(qx.Bootstrap.DEBUG){ qx.Bootstrap.warn(key + " is not a valid key. Please see the API-doc of " + "qx.core.Environment for a list of predefined keys."); qx.Bootstrap.trace(this); }; }, /** * Maps an environment key to a check class and method name. * * @param key {String} The name of the check you want to query. * @return {Array} [className, methodName] of * the corresponding implementation. */ _getClassNameFromEnvKey : function(key){ var envmappings = this._checksMap; if(envmappings[key] != undefined){ var implementation = envmappings[key]; // separate class from method var lastdot = implementation.lastIndexOf("."); if(lastdot > -1){ var classname = implementation.slice(0, lastdot); var methodname = implementation.slice(lastdot + 1); var clazz = qx.Bootstrap.getByName(classname); if(clazz != undefined){ return [clazz, methodname]; }; }; }; return [undefined, undefined]; }, /** * Invokes the callback as soon as the check has been done. If no check * could be found, a warning will be printed. * * @param key {String} The key of the asynchronous check. * @param callback {Function} The function to call as soon as the check is * done. The function should have one argument which is the result of the * check. * @param self {var} The context to use when invoking the callback. */ getAsync : function(key, callback, self){ // check the cache var env = this; if(this.__cache[key] != undefined){ // force async behavior window.setTimeout(function(){ callback.call(self, env.__cache[key]); }, 0); return; }; var check = this._asyncChecks[key]; if(check){ check(function(result){ env.__cache[key] = result; callback.call(self, result); }); return; }; // try class lookup var classAndMethod = this._getClassNameFromEnvKey(key); if(classAndMethod[0] != undefined){ var clazz = classAndMethod[0]; var method = classAndMethod[1]; clazz[method](function(result){ // call the check method env.__cache[key] = result; callback.call(self, result); }); return; }; // debug flag if(qx.Bootstrap.DEBUG){ qx.Bootstrap.warn(key + " is not a valid key. Please see the API-doc of " + "qx.core.Environment for a list of predefined keys."); qx.Bootstrap.trace(this); }; }, /** * Returns the proper value dependent on the check for the given key. * * @param key {String} The name of the check the select depends on. * @param values {Map} A map containing the values which should be returned * in any case. The "default" key could be used as a catch all statement. * @return {var} The value which is stored in the map for the given * check of the key. */ select : function(key, values){ return this.__pickFromValues(this.get(key), values); }, /** * Selects the proper function dependent on the asynchronous check. * * @param key {String} The key for the async check. * @param values {Map} A map containing functions. The map keys should * contain all possibilities which could be returned by the given check * key. The "default" key could be used as a catch all statement. * The called function will get one parameter, the result of the query. * @param self {var} The context which should be used when calling the * method in the values map. */ selectAsync : function(key, values, self){ this.getAsync(key, function(result){ var value = this.__pickFromValues(key, values); value.call(self, result); }, this); }, /** * Internal helper which tries to pick the given key from the given values * map. If that key is not found, it tries to use a key named "default". * If there is also no default key, it prints out a warning and returns * undefined. * * @param key {String} The key to search for in the values. * @param values {Map} A map containing some keys. * @return {var} The value stored as values[key] usually. */ __pickFromValues : function(key, values){ var value = values[key]; if(values.hasOwnProperty(key)){ return value; }; // check for piped values for(var id in values){ if(id.indexOf("|") != -1){ var ids = id.split("|"); for(var i = 0;i < ids.length;i++){ if(ids[i] == key){ return values[id]; }; }; }; }; if(values["default"] !== undefined){ return values["default"]; }; if(qx.Bootstrap.DEBUG){ throw new Error('No match for variant "' + key + '" (' + (typeof key) + ' type)' + ' in variants [' + qx.Bootstrap.keys(values) + '] found, and no default ("default") given'); }; }, /** * Takes a given map containing the check names as keys and converts * the map to an array only containing the values for check evaluating * to <code>true</code>. This is especially handy for conditional * includes of mixins. * @param map {Map} A map containing check names as keys and values. * @return {Array} An array containing the values. */ filter : function(map){ var returnArray = []; for(var check in map){ if(this.get(check)){ returnArray.push(map[check]); }; }; return returnArray; }, /** * Invalidates the cache for the given key. * * @param key {String} The key of the check. */ invalidateCacheKey : function(key){ delete this.__cache[key]; }, /** * Add a check to the environment class. If there is already a check * added for the given key, the add will be ignored. * * @param key {String} The key for the check e.g. html.featurexyz. * @param check {var} It could be either a function or a simple value. * The function should be responsible for the check and should return the * result of the check. */ add : function(key, check){ // ignore already added checks. if(this._checks[key] == undefined){ // add functions directly if(check instanceof Function){ this._checks[key] = check; } else { this._checks[key] = this.__createCheck(check); }; }; }, /** * Adds an asynchronous check to the environment. If there is already a check * added for the given key, the add will be ignored. * * @param key {String} The key of the check e.g. html.featureabc * @param check {Function} A function which should check for a specific * environment setting in an asynchronous way. The method should take two * arguments. First one is the callback and the second one is the context. */ addAsync : function(key, check){ if(this._checks[key] == undefined){ this._asyncChecks[key] = check; }; }, /** * Returns all currently defined synchronous checks. * * @internal * @return {Map} The map of synchronous checks */ getChecks : function(){ return this._checks; }, /** * Returns all currently defined asynchronous checks. * * @internal * @return {Map} The map of asynchronous checks */ getAsyncChecks : function(){ return this._asyncChecks; }, /** * Initializer for the default values of the framework settings. */ _initDefaultQxValues : function(){ // an always-true key (e.g. for use in qx.core.Environment.filter() calls) this.add("true", function(){ return true; }); // old settings this.add("qx.allowUrlSettings", function(){ return false; }); this.add("qx.allowUrlVariants", function(){ return false; }); this.add("qx.debug.property.level", function(){ return 0; }); // old variants // make sure to reflect all changes to qx.debug here in the bootstrap class! this.add("qx.debug", function(){ return true; }); this.add("qx.debug.ui.queue", function(){ return true; }); this.add("qx.aspects", function(){ return false; }); this.add("qx.dynlocale", function(){ return true; }); this.add("qx.mobile.emulatetouch", function(){ return false; }); this.add("qx.mobile.nativescroll", function(){ return false; }); this.add("qx.blankpage", function(){ return "qx/static/blank.html"; }); this.add("qx.dynamicmousewheel", function(){ return true; }); this.add("qx.debug.databinding", function(){ return false; }); this.add("qx.debug.dispose", function(){ return false; }); // generator optimization vectors this.add("qx.optimization.basecalls", function(){ return false; }); this.add("qx.optimization.comments", function(){ return false; }); this.add("qx.optimization.privates", function(){ return false; }); this.add("qx.optimization.strings", function(){ return false; }); this.add("qx.optimization.variables", function(){ return false; }); this.add("qx.optimization.variants", function(){ return false; }); // qooxdoo modules this.add("module.databinding", function(){ return true; }); this.add("module.logger", function(){ return true; }); this.add("module.property", function(){ return true; }); this.add("module.events", function(){ return true; }); this.add("qx.nativeScrollBars", function(){ return false; }); }, /** * Import checks from global qx.$$environment into the Environment class. */ __importFromGenerator : function(){ // import the environment map if(qx && qx.$$environment){ for(var key in qx.$$environment){ var value = qx.$$environment[key]; this._checks[key] = this.__createCheck(value); }; }; }, /** * Checks the URL for environment settings and imports these into the * Environment class. */ __importFromUrl : function(){ if(window.document && window.document.location){ var urlChecks = window.document.location.search.slice(1).split("&"); for(var i = 0;i < urlChecks.length;i++){ var check = urlChecks[i].split(":"); if(check.length != 3 || check[0] != "qxenv"){ continue; }; var key = check[1]; var value = decodeURIComponent(check[2]); // implicit type conversion if(value == "true"){ value = true; } else if(value == "false"){ value = false; } else if(/^(\d|\.)+$/.test(value)){ value = parseFloat(value); };; this._checks[key] = this.__createCheck(value); }; }; }, /** * Internal helper which creates a function returning the given value. * * @param value {var} The value which should be returned. * @return {Function} A function which could be used by a test. */ __createCheck : function(value){ return qx.Bootstrap.bind(function(value){ return value; }, null, value); } }, defer : function(statics){ // create default values for the environment class statics._initDefaultQxValues(); // load the checks from the generator statics.__importFromGenerator(); // load the checks from the url if(statics.get("qx.allowUrlSettings") === true){ statics.__importFromUrl(); }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Martin Wittemann (martinwittemann) ====================================================================== This class contains code from: Copyright: 2011 Pocket Widget S.L., Spain, http://www.pocketwidget.com License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php Authors: * Javier Martinez Villacampa ************************************************************************ */ /** * This class comes with all relevant information regarding * the client's engine. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Engine", { // General: http://en.wikipedia.org/wiki/Browser_timeline // Webkit: https://developer.apple.com/internet/safari/uamatrix.html // Firefox: http://en.wikipedia.org/wiki/History_of_Mozilla_Firefox // Maple: http://www.scribd.com/doc/46675822/2011-SDK2-0-Maple-Browser-Specification-V1-00 statics : { /** * Returns the version of the engine. * * @return {String} The version number of the current engine. * @internal */ getVersion : function(){ var agent = window.navigator.userAgent; var version = ""; if(qx.bom.client.Engine.__isOpera()){ // Opera has a special versioning scheme, where the second part is combined // e.g. 8.54 which should be handled like 8.5.4 to be compatible to the // common versioning system used by other browsers if(/Opera[\s\/]([0-9]+)\.([0-9])([0-9]*)/.test(agent)){ // opera >= 10 has as a first verison 9.80 and adds the proper version // in a separate "Version/" postfix // http://my.opera.com/chooseopera/blog/2009/05/29/changes-in-operas-user-agent-string-format if(agent.indexOf("Version/") != -1){ var match = agent.match(/Version\/(\d+)\.(\d+)/); // ignore the first match, its the whole version string version = match[1] + "." + match[2].charAt(0) + "." + match[2].substring(1, match[2].length); } else { version = RegExp.$1 + "." + RegExp.$2; if(RegExp.$3 != ""){ version += "." + RegExp.$3; }; }; }; } else if(qx.bom.client.Engine.__isWebkit()){ if(/AppleWebKit\/([^ ]+)/.test(agent)){ version = RegExp.$1; // We need to filter these invalid characters var invalidCharacter = RegExp("[^\\.0-9]").exec(version); if(invalidCharacter){ version = version.slice(0, invalidCharacter.index); }; }; } else if(qx.bom.client.Engine.__isGecko() || qx.bom.client.Engine.__isMaple()){ // Parse "rv" section in user agent string if(/rv\:([^\);]+)(\)|;)/.test(agent)){ version = RegExp.$1; }; } else if(qx.bom.client.Engine.__isMshtml()){ var isTrident = /Trident\/([^\);]+)(\)|;)/.test(agent); if(/MSIE\s+([^\);]+)(\)|;)/.test(agent)){ version = RegExp.$1; // If the IE8 or IE9 is running in the compatibility mode, the MSIE value // is set to an older version, but we need the correct version. The only // way is to compare the trident version. if(version < 8 && isTrident){ if(RegExp.$1 == "4.0"){ version = "8.0"; } else if(RegExp.$1 == "5.0"){ version = "9.0"; }; }; } else if(isTrident){ // IE 11 dropped the "MSIE" string var match = /\brv\:(\d+?\.\d+?)\b/.exec(agent); if(match){ version = match[1]; }; }; } else { var failFunction = window.qxFail; if(failFunction && typeof failFunction === "function"){ version = failFunction().FULLVERSION; } else { version = "1.9.0.0"; qx.Bootstrap.warn("Unsupported client: " + agent + "! Assumed gecko version 1.9.0.0 (Firefox 3.0)."); }; };;; return version; }, /** * Returns the name of the engine. * * @return {String} The name of the current engine. * @internal */ getName : function(){ var name; if(qx.bom.client.Engine.__isOpera()){ name = "opera"; } else if(qx.bom.client.Engine.__isWebkit()){ name = "webkit"; } else if(qx.bom.client.Engine.__isGecko() || qx.bom.client.Engine.__isMaple()){ name = "gecko"; } else if(qx.bom.client.Engine.__isMshtml()){ name = "mshtml"; } else { // check for the fallback var failFunction = window.qxFail; if(failFunction && typeof failFunction === "function"){ name = failFunction().NAME; } else { name = "gecko"; qx.Bootstrap.warn("Unsupported client: " + window.navigator.userAgent + "! Assumed gecko version 1.9.0.0 (Firefox 3.0)."); }; };;; return name; }, /** * Internal helper for checking for opera. * @return {Boolean} true, if its opera. */ __isOpera : function(){ return window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]"; }, /** * Internal helper for checking for webkit. * @return {Boolean} true, if its webkit. */ __isWebkit : function(){ return window.navigator.userAgent.indexOf("AppleWebKit/") != -1; }, /** * Internal helper for checking for Maple . * Maple is used in Samsung SMART TV 2010-2011 models. It's based on Gecko * engine 1.8.1.11. * @return {Boolean} true, if its maple. */ __isMaple : function(){ return window.navigator.userAgent.indexOf("Maple") != -1; }, /** * Internal helper for checking for gecko. * @return {Boolean} true, if its gecko. */ __isGecko : function(){ return window.controllers && window.navigator.product === "Gecko" && window.navigator.userAgent.indexOf("Maple") == -1 && window.navigator.userAgent.indexOf("Trident") == -1; }, /** * Internal helper to check for MSHTML. * @return {Boolean} true, if its MSHTML. */ __isMshtml : function(){ return window.navigator.cpuClass && (/MSIE\s+([^\);]+)(\)|;)/.test(window.navigator.userAgent) || /Trident\/\d+?\.\d+?/.test(window.navigator.userAgent)); } }, defer : function(statics){ qx.core.Environment.add("engine.version", statics.getVersion); qx.core.Environment.add("engine.name", statics.getName); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The main purpose of this class to hold all checks about ECMAScript. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.EcmaScript", { statics : { /** * Returns the name of the Error object property that holds stack trace * information or null if the client does not provide any. * * @internal * @return {String|null} <code>stack</code>, <code>stacktrace</code> or * <code>null</code> */ getStackTrace : function(){ var propName; var e = new Error("e"); propName = e.stack ? "stack" : e.stacktrace ? "stacktrace" : null; // only thrown errors have the stack property in IE10 and PhantomJS if(!propName){ try{ throw e; } catch(ex) { e = ex; }; }; return e.stacktrace ? "stacktrace" : e.stack ? "stack" : null; }, /** * Checks if 'indexOf' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayIndexOf : function(){ return !!Array.prototype.indexOf; }, /** * Checks if 'lastIndexOf' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayLastIndexOf : function(){ return !!Array.prototype.lastIndexOf; }, /** * Checks if 'forEach' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayForEach : function(){ return !!Array.prototype.forEach; }, /** * Checks if 'filter' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayFilter : function(){ return !!Array.prototype.filter; }, /** * Checks if 'map' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayMap : function(){ return !!Array.prototype.map; }, /** * Checks if 'some' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArraySome : function(){ return !!Array.prototype.some; }, /** * Checks if 'every' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayEvery : function(){ return !!Array.prototype.every; }, /** * Checks if 'reduce' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayReduce : function(){ return !!Array.prototype.reduce; }, /** * Checks if 'reduceRight' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayReduceRight : function(){ return !!Array.prototype.reduceRight; }, /** * Checks if 'toString' is supported on the Error object and * its working as expected. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getErrorToString : function(){ return typeof Error.prototype.toString == "function" && Error.prototype.toString() !== "[object Error]"; }, /** * Checks if 'bind' is supported on the Function object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getFunctionBind : function(){ return typeof Function.prototype.bind === "function"; }, /** * Checks if 'keys' is supported on the Object object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getObjectKeys : function(){ return !!Object.keys; }, /** * Checks if 'now' is supported on the Date object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getDateNow : function(){ return !!Date.now; }, /** * Checks if 'trim' is supported on the String object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getStringTrim : function(){ return typeof String.prototype.trim === "function"; } }, defer : function(statics){ // array polyfill qx.core.Environment.add("ecmascript.array.indexof", statics.getArrayIndexOf); qx.core.Environment.add("ecmascript.array.lastindexof", statics.getArrayLastIndexOf); qx.core.Environment.add("ecmascript.array.foreach", statics.getArrayForEach); qx.core.Environment.add("ecmascript.array.filter", statics.getArrayFilter); qx.core.Environment.add("ecmascript.array.map", statics.getArrayMap); qx.core.Environment.add("ecmascript.array.some", statics.getArraySome); qx.core.Environment.add("ecmascript.array.every", statics.getArrayEvery); qx.core.Environment.add("ecmascript.array.reduce", statics.getArrayReduce); qx.core.Environment.add("ecmascript.array.reduceright", statics.getArrayReduceRight); // date polyfill qx.core.Environment.add("ecmascript.date.now", statics.getDateNow); // error bugfix qx.core.Environment.add("ecmascript.error.toString", statics.getErrorToString); qx.core.Environment.add("ecmascript.error.stacktrace", statics.getStackTrace); // function polyfill qx.core.Environment.add("ecmascript.function.bind", statics.getFunctionBind); // object polyfill qx.core.Environment.add("ecmascript.object.keys", statics.getObjectKeys); // string polyfill qx.core.Environment.add("ecmascript.string.trim", statics.getStringTrim); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Array' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *indexOf*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.14">Annotated ES5 Spec</a> * * *lastIndexOf*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/lastIndexOf">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.15">Annotated ES5 Spec</a> * * *forEach*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.18">Annotated ES5 Spec</a> * * *filter*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.20">Annotated ES5 Spec</a> * * *map*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.19">Annotated ES5 Spec</a> * * *some*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/some">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.17">Annotated ES5 Spec</a> * * *every*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/every">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.16">Annotated ES5 Spec</a> * * *reduce*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/reduce">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.21">Annotated ES5 Spec</a> * * *reduceRight*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/reduceRight">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.22">Annotated ES5 Spec</a> * * Here is a little sample of how to use <code>indexOf</code> e.g. * <pre class="javascript">var a = ["a", "b", "c"]; * a.indexOf("b"); // returns 1</pre> */ qx.Bootstrap.define("qx.lang.normalize.Array", { defer : function(){ // fix indexOf if(!qx.core.Environment.get("ecmascript.array.indexof")){ Array.prototype.indexOf = function(searchElement, fromIndex){ if(fromIndex == null){ fromIndex = 0; } else if(fromIndex < 0){ fromIndex = Math.max(0, this.length + fromIndex); }; for(var i = fromIndex;i < this.length;i++){ if(this[i] === searchElement){ return i; }; }; return -1; }; }; // lastIndexOf if(!qx.core.Environment.get("ecmascript.array.lastindexof")){ Array.prototype.lastIndexOf = function(searchElement, fromIndex){ if(fromIndex == null){ fromIndex = this.length - 1; } else if(fromIndex < 0){ fromIndex = Math.max(0, this.length + fromIndex); }; for(var i = fromIndex;i >= 0;i--){ if(this[i] === searchElement){ return i; }; }; return -1; }; }; // forEach if(!qx.core.Environment.get("ecmascript.array.foreach")){ Array.prototype.forEach = function(callback, obj){ var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ callback.call(obj || window, value, i, this); }; }; }; }; // filter if(!qx.core.Environment.get("ecmascript.array.filter")){ Array.prototype.filter = function(callback, obj){ var res = []; var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ if(callback.call(obj || window, value, i, this)){ res.push(this[i]); }; }; }; return res; }; }; // map if(!qx.core.Environment.get("ecmascript.array.map")){ Array.prototype.map = function(callback, obj){ var res = []; var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ res[i] = callback.call(obj || window, value, i, this); }; }; return res; }; }; // some if(!qx.core.Environment.get("ecmascript.array.some")){ Array.prototype.some = function(callback, obj){ var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ if(callback.call(obj || window, value, i, this)){ return true; }; }; }; return false; }; }; // every if(!qx.core.Environment.get("ecmascript.array.every")){ Array.prototype.every = function(callback, obj){ var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ if(!callback.call(obj || window, value, i, this)){ return false; }; }; }; return true; }; }; // reduce if(!qx.core.Environment.get("ecmascript.array.reduce")){ Array.prototype.reduce = function(callback, init){ if(typeof callback !== "function"){ throw new TypeError("First argument is not callable"); }; if(init === undefined && this.length === 0){ throw new TypeError("Length is 0 and no second argument given"); }; var ret = init === undefined ? this[0] : init; for(var i = init === undefined ? 1 : 0;i < this.length;i++){ if(i in this){ ret = callback.call(undefined, ret, this[i], i, this); }; }; return ret; }; }; // reduceRight if(!qx.core.Environment.get("ecmascript.array.reduceright")){ Array.prototype.reduceRight = function(callback, init){ if(typeof callback !== "function"){ throw new TypeError("First argument is not callable"); }; if(init === undefined && this.length === 0){ throw new TypeError("Length is 0 and no second argument given"); }; var ret = init === undefined ? this[this.length - 1] : init; for(var i = init === undefined ? this.length - 2 : this.length - 1;i >= 0;i--){ if(i in this){ ret = callback.call(undefined, ret, this[i], i, this); }; }; return ret; }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2007-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ====================================================================== This class uses ideas and code snipplets presented at http://webreflection.blogspot.com/2008/05/habemus-array-unlocked-length-in-ie8.html http://webreflection.blogspot.com/2008/05/stack-and-arrayobject-how-to-create.html Author: Andrea Giammarchi License: MIT: http://www.opensource.org/licenses/mit-license.php ====================================================================== This class uses documentation of the native Array methods from the MDC documentation of Mozilla. License: CC Attribution-Sharealike License: http://creativecommons.org/licenses/by-sa/2.5/ ************************************************************************ */ /* ************************************************************************ #require(qx.bom.client.Engine) #require(qx.lang.normalize.Array) ************************************************************************ */ /** * This class is the common superclass for most array classes in * qooxdoo. It supports all of the shiny 1.6 JavaScript array features * like <code>forEach</code> and <code>map</code>. * * This class may be instantiated instead of the native Array if * one wants to work with a feature-unified Array instead of the native * one. This class uses native features whereever possible but fills * all missing implementations with custom ones. * * Through the ability to extend from this class one could add even * more utility features on top of it. */ qx.Bootstrap.define("qx.type.BaseArray", { extend : Array, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * Creates a new Array with the given length or the listed elements. * * <pre class="javascript"> * var arr1 = new qx.type.BaseArray(arrayLength); * var arr2 = new qx.type.BaseArray(item0, item1, ..., itemN); * </pre> * * * <code>arrayLength</code>: The initial length of the array. You can access * this value using the length property. If the value specified is not a * number, an array of length 1 is created, with the first element having * the specified value. The maximum length allowed for an * array is 2^32-1, i.e. 4,294,967,295. * * <code>itemN</code>: A value for the element in that position in the * array. When this form is used, the array is initialized with the specified * values as its elements, and the array's length property is set to the * number of arguments. * * @param length_or_items {Integer|var?null} The initial length of the array * OR an argument list of values. */ construct : function(length_or_items){ }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Converts a base array to a native Array * * @signature function() * @return {Array} The native array */ toArray : null, /** * Returns the current number of items stored in the Array * * @signature function() * @return {Integer} number of items */ valueOf : null, /** * Removes the last element from an array and returns that element. * * This method modifies the array. * * @signature function() * @return {var} The last element of the array. */ pop : null, /** * Adds one or more elements to the end of an array and returns the new length of the array. * * This method modifies the array. * * @signature function(varargs) * @param varargs {var} The elements to add to the end of the array. * @return {Integer} The new array's length */ push : null, /** * Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first. * * This method modifies the array. * * @signature function() * @return {Array} Returns the modified array (works in place) */ reverse : null, /** * Removes the first element from an array and returns that element. * * This method modifies the array. * * @signature function() * @return {var} The first element of the array. */ shift : null, /** * Sorts the elements of an array. * * This method modifies the array. * * @signature function(compareFunction) * @param compareFunction {Function?null} Specifies a function that defines the sort order. If omitted, * the array is sorted lexicographically (in dictionary order) according to the string conversion of each element. * @return {Array} Returns the modified array (works in place) */ sort : null, /** * Adds and/or removes elements from an array. * * @signature function(index, howMany, varargs) * @param index {Integer} Index at which to start changing the array. If negative, will begin * that many elements from the end. * @param howMany {Integer} An integer indicating the number of old array elements to remove. * If <code>howMany</code> is 0, no elements are removed. In this case, you should specify * at least one new element. * @param varargs {var?null} The elements to add to the array. If you don't specify any elements, * splice simply removes elements from the array. * @return {BaseArray} New array with the removed elements. */ splice : null, /** * Adds one or more elements to the front of an array and returns the new length of the array. * * This method modifies the array. * * @signature function(varargs) * @param varargs {var} The elements to add to the front of the array. * @return {Integer} The new array's length */ unshift : null, /** * Returns a new array comprised of this array joined with other array(s) and/or value(s). * * This method does not modify the array and returns a modified copy of the original. * * @signature function(varargs) * @param varargs {Array|var} Arrays and/or values to concatenate to the resulting array. * @return {qx.type.BaseArray} New array built of the given arrays or values. */ concat : null, /** * Joins all elements of an array into a string. * * @signature function(separator) * @param separator {String} Specifies a string to separate each element of the array. The separator is * converted to a string if necessary. If omitted, the array elements are separated with a comma. * @return {String} The stringified values of all elements divided by the given separator. */ join : null, /** * Extracts a section of an array and returns a new array. * * @signature function(begin, end) * @param begin {Integer} Zero-based index at which to begin extraction. As a negative index, start indicates * an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element * in the sequence. * @param end {Integer?length} Zero-based index at which to end extraction. slice extracts up to but not including end. * <code>slice(1,4)</code> extracts the second element through the fourth element (elements indexed 1, 2, and 3). * As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. * If end is omitted, slice extracts to the end of the sequence. * @return {BaseArray} An new array which contains a copy of the given region. */ slice : null, /** * Returns a string representing the array and its elements. Overrides the Object.prototype.toString method. * * @signature function() * @return {String} The string representation of the array. */ toString : null, /** * Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. * * @signature function(searchElement, fromIndex) * @param searchElement {var} Element to locate in the array. * @param fromIndex {Integer?0} The index at which to begin the search. Defaults to 0, i.e. the * whole array will be searched. If the index is greater than or equal to the length of the * array, -1 is returned, i.e. the array will not be searched. If negative, it is taken as * the offset from the end of the array. Note that even when the index is negative, the array * is still searched from front to back. If the calculated index is less than 0, the whole * array will be searched. * @return {Integer} The index of the given element */ indexOf : null, /** * Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. * * @signature function(searchElement, fromIndex) * @param searchElement {var} Element to locate in the array. * @param fromIndex {Integer?length} The index at which to start searching backwards. Defaults to * the array's length, i.e. the whole array will be searched. If the index is greater than * or equal to the length of the array, the whole array will be searched. If negative, it * is taken as the offset from the end of the array. Note that even when the index is * negative, the array is still searched from back to front. If the calculated index is * less than 0, -1 is returned, i.e. the array will not be searched. * @return {Integer} The index of the given element */ lastIndexOf : null, /** * Executes a provided function once per array element. * * <code>forEach</code> executes the provided function (<code>callback</code>) once for each * element present in the array. <code>callback</code> is invoked only for indexes of the array * which have assigned values; it is not invoked for indexes which have been deleted or which * have never been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index * of the element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>forEach</code>, it will be used * as the <code>this</code> for each invocation of the <code>callback</code>. If it is not * provided, or is <code>null</code>, the global object associated with <code>callback</code> * is used instead. * * <code>forEach</code> does not mutate the array on which it is called. * * The range of elements processed by <code>forEach</code> is set before the first invocation of * <code>callback</code>. Elements which are appended to the array after the call to * <code>forEach</code> begins will not be visited by <code>callback</code>. If existing elements * of the array are changed, or deleted, their value as passed to <code>callback</code> will be * the value at the time <code>forEach</code> visits them; elements that are deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to execute for each element. * @param obj {Object} Object to use as this when executing callback. */ forEach : null, /** * Creates a new array with all elements that pass the test implemented by the provided * function. * * <code>filter</code> calls a provided <code>callback</code> function once for each * element in an array, and constructs a new array of all the values for which * <code>callback</code> returns a true value. <code>callback</code> is invoked only * for indexes of the array which have assigned values; it is not invoked for indexes * which have been deleted or which have never been assigned values. Array elements which * do not pass the <code>callback</code> test are simply skipped, and are not included * in the new array. * * <code>callback</code> is invoked with three arguments: the value of the element, the * index of the element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>filter</code>, it will * be used as the <code>this</code> for each invocation of the <code>callback</code>. * If it is not provided, or is <code>null</code>, the global object associated with * <code>callback</code> is used instead. * * <code>filter</code> does not mutate the array on which it is called. The range of * elements processed by <code>filter</code> is set before the first invocation of * <code>callback</code>. Elements which are appended to the array after the call to * <code>filter</code> begins will not be visited by <code>callback</code>. If existing * elements of the array are changed, or deleted, their value as passed to <code>callback</code> * will be the value at the time <code>filter</code> visits them; elements that are deleted * are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to test each element of the array. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {BaseArray} The newly created array with all matching elements */ filter : null, /** * Creates a new array with the results of calling a provided function on every element in this array. * * <code>map</code> calls a provided <code>callback</code> function once for each element in an array, * in order, and constructs a new array from the results. <code>callback</code> is invoked only for * indexes of the array which have assigned values; it is not invoked for indexes which have been * deleted or which have never been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index of the * element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>map</code>, it will be used as the * <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, or is * <code>null</code>, the global object associated with <code>callback</code> is used instead. * * <code>map</code> does not mutate the array on which it is called. * * The range of elements processed by <code>map</code> is set before the first invocation of * <code>callback</code>. Elements which are appended to the array after the call to <code>map</code> * begins will not be visited by <code>callback</code>. If existing elements of the array are changed, * or deleted, their value as passed to <code>callback</code> will be the value at the time * <code>map</code> visits them; elements that are deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function produce an element of the new Array from an element of the current one. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {BaseArray} A new array which contains the return values of every item executed through the given function */ map : null, /** * Tests whether some element in the array passes the test implemented by the provided function. * * <code>some</code> executes the <code>callback</code> function once for each element present in * the array until it finds one where <code>callback</code> returns a true value. If such an element * is found, <code>some</code> immediately returns <code>true</code>. Otherwise, <code>some</code> * returns <code>false</code>. <code>callback</code> is invoked only for indexes of the array which * have assigned values; it is not invoked for indexes which have been deleted or which have never * been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index of the * element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>some</code>, it will be used as the * <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, or is * <code>null</code>, the global object associated with <code>callback</code> is used instead. * * <code>some</code> does not mutate the array on which it is called. * * The range of elements processed by <code>some</code> is set before the first invocation of * <code>callback</code>. Elements that are appended to the array after the call to <code>some</code> * begins will not be visited by <code>callback</code>. If an existing, unvisited element of the array * is changed by <code>callback</code>, its value passed to the visiting <code>callback</code> will * be the value at the time that <code>some</code> visits that element's index; elements that are * deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to test for each element. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {Boolean} Whether at least one elements passed the test */ some : null, /** * Tests whether all elements in the array pass the test implemented by the provided function. * * <code>every</code> executes the provided <code>callback</code> function once for each element * present in the array until it finds one where <code>callback</code> returns a false value. If * such an element is found, the <code>every</code> method immediately returns <code>false</code>. * Otherwise, if <code>callback</code> returned a true value for all elements, <code>every</code> * will return <code>true</code>. <code>callback</code> is invoked only for indexes of the array * which have assigned values; it is not invoked for indexes which have been deleted or which have * never been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index of * the element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>every</code>, it will be used as * the <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, * or is <code>null</code>, the global object associated with <code>callback</code> is used instead. * * <code>every</code> does not mutate the array on which it is called. The range of elements processed * by <code>every</code> is set before the first invocation of <code>callback</code>. Elements which * are appended to the array after the call to <code>every</code> begins will not be visited by * <code>callback</code>. If existing elements of the array are changed, their value as passed * to <code>callback</code> will be the value at the time <code>every</code> visits them; elements * that are deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to test for each element. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {Boolean} Whether all elements passed the test */ every : null } }); (function(){ function createStackConstructor(stack){ // In IE don't inherit from Array but use an empty object as prototype // and copy the methods from Array if((qx.core.Environment.get("engine.name") == "mshtml")){ Stack.prototype = { length : 0, $$isArray : true }; var args = "pop.push.reverse.shift.sort.splice.unshift.join.slice".split("."); for(var length = args.length;length;){ Stack.prototype[args[--length]] = Array.prototype[args[length]]; }; }; // Remember Array's slice method var slice = Array.prototype.slice; // Fix "concat" method Stack.prototype.concat = function(){ var constructor = this.slice(0); for(var i = 0,length = arguments.length;i < length;i++){ var copy; if(arguments[i] instanceof Stack){ copy = slice.call(arguments[i], 0); } else if(arguments[i] instanceof Array){ copy = arguments[i]; } else { copy = [arguments[i]]; }; constructor.push.apply(constructor, copy); }; return constructor; }; // Fix "toString" method Stack.prototype.toString = function(){ return slice.call(this, 0).toString(); }; // Fix "toLocaleString" Stack.prototype.toLocaleString = function(){ return slice.call(this, 0).toLocaleString(); }; // Fix constructor Stack.prototype.constructor = Stack; // Add JS 1.6 Array features Stack.prototype.indexOf = Array.prototype.indexOf; Stack.prototype.lastIndexOf = Array.prototype.lastIndexOf; Stack.prototype.forEach = Array.prototype.forEach; Stack.prototype.some = Array.prototype.some; Stack.prototype.every = Array.prototype.every; var filter = Array.prototype.filter; var map = Array.prototype.map; // Fix methods which generates a new instance // to return an instance of the same class Stack.prototype.filter = function(){ var ret = new this.constructor; ret.push.apply(ret, filter.apply(this, arguments)); return ret; }; Stack.prototype.map = function(){ var ret = new this.constructor; ret.push.apply(ret, map.apply(this, arguments)); return ret; }; Stack.prototype.slice = function(){ var ret = new this.constructor; ret.push.apply(ret, Array.prototype.slice.apply(this, arguments)); return ret; }; Stack.prototype.splice = function(){ var ret = new this.constructor; ret.push.apply(ret, Array.prototype.splice.apply(this, arguments)); return ret; }; // Add new "toArray" method for convert a base array to a native Array Stack.prototype.toArray = function(){ return Array.prototype.slice.call(this, 0); }; // Add valueOf() to return the length Stack.prototype.valueOf = function(){ return this.length; }; // Return final class return Stack; }; function Stack(length){ if(arguments.length === 1 && typeof length === "number"){ this.length = -1 < length && length === length >> .5 ? length : this.push(length); } else if(arguments.length){ this.push.apply(this, arguments); }; }; function PseudoArray(){ }; PseudoArray.prototype = []; Stack.prototype = new PseudoArray; Stack.prototype.length = 0; qx.type.BaseArray = createStackConstructor(Stack); })(); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #ignore(q) ************************************************************************ */ /** * The Core module's responsibility is to query the DOM for elements and offer * these elements as a collection. The Core module itself does not offer any methods to * work with the collection. These methods are added by the other included modules, * such as Manipulating or Attributes. * * Core also provides the plugin API which allows modules to attach either * static functions to the global <code>q</code> object or define methods on the * collection it returns. * * By default, the core module is assigned to a global module named <code>q</code>. * In case <code>q</code> is already defined, the name <code>qxWeb</code> * is used instead. * * For further details, take a look at the documentation in the * <a href='http://manual.qooxdoo.org/${qxversion}/pages/website.html' target='_blank'>user manual</a>. */ qx.Bootstrap.define("qxWeb", { extend : qx.type.BaseArray, statics : { // internal storage for all initializers __init : [], // internal reference to the used qx namespace $$qx : qx, /** * Internal helper to initialize collections. * * @param arg {var} An array of Elements which will * be initialized as {@link q}. All items in the array which are not * either a window object or a node object will be ignored. * @return {q} A new initialized collection. */ $init : function(arg){ var clean = []; for(var i = 0;i < arg.length;i++){ var isNode = !!(arg[i] && arg[i].nodeType != null); if(isNode){ clean.push(arg[i]); continue; }; var isWindow = !!(arg[i] && arg[i].history && arg[i].location && arg[i].document); if(isWindow){ clean.push(arg[i]); }; }; // check for node or window object var col = qx.lang.Array.cast(clean, qxWeb); for(var i = 0;i < qxWeb.__init.length;i++){ qxWeb.__init[i].call(col); }; return col; }, /** * This is an API for module development and can be used to attach new methods * to {@link q}. * * @param module {Map} A map containing the methods to attach. */ $attach : function(module){ for(var name in module){ { }; qxWeb.prototype[name] = module[name]; }; }, /** * This is an API for module development and can be used to attach new methods * to {@link q}. * * @param module {Map} A map containing the methods to attach. */ $attachStatic : function(module){ for(var name in module){ { }; qxWeb[name] = module[name]; }; }, /** * This is an API for module development and can be used to attach new initialization * methods to {@link q} which will be called when a new collection is * created. * * @param init {Function} The initialization method for a module. */ $attachInit : function(init){ this.__init.push(init); }, /** * Define a new class using the qooxdoo class system. * * @signature function(name, config) * @param name {String?} Name of the class. If null, the class will not be * attached to a namespace. * @param config {Map} Class definition structure. * @return {Function} The defined class. */ define : function(name, config){ if(config == undefined){ config = name; name = null; }; return qx.Bootstrap.define.call(qx.Bootstrap, name, config); } }, /** * Accepts a selector string and returns a set of found items. The optional context * element can be used to reduce the amount of found elements to children of the * context element. * * <a href="http://sizzlejs.com/" target="_blank">Sizzle</a> is used as selector engine. * Check out the <a href="https://github.com/jquery/sizzle/wiki/Sizzle-Home" target="_blank">documentation</a> * for more details. * * @param selector {String|Element|Array} Valid selector (CSS3 + extensions) * or DOM element or Array of DOM Elements. * @param context {Element} Only the children of this element are considered. * @return {q} A collection of DOM elements. */ construct : function(selector, context){ if(!selector && this instanceof qxWeb){ return this; }; if(qx.Bootstrap.isString(selector)){ selector = qx.bom.Selector.query(selector, context); } else if(!(qx.Bootstrap.isArray(selector))){ selector = [selector]; }; return qxWeb.$init(selector); }, members : { /** * Gets a new collection containing only those elements that passed the * given filter. This can be either a selector expression or a filter * function. * * @param selector {String|Function} Selector expression or filter function * @return {q} New collection containing the elements that passed the filter */ filter : function(selector){ if(qx.lang.Type.isFunction(selector)){ return qxWeb.$init(Array.prototype.filter.call(this, selector)); }; return qxWeb.$init(qx.bom.Selector.matches(selector, this)); }, /** * Returns a copy of the collection within the given range. * * @param begin {Number} The index to begin. * @param end {Number?} The index to end. * @return {q} A new collection containing a slice of the original collection. */ slice : function(begin, end){ // Old IEs return an empty array if the second argument is undefined if(end){ return qxWeb.$init(Array.prototype.slice.call(this, begin, end)); } else { return qxWeb.$init(Array.prototype.slice.call(this, begin)); }; }, /** * Removes the given number of items and returns the removed items as a new collection. * This method can also add items. Take a look at the * <a href='https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice' target='_blank'>documentation of MDN</a> for more details. * * @param index {Number} The index to begin. * @param howMany {Number} the amount of items to remove. * @param varargs {var} As many items as you want to add. * @return {q} A new collection containing the removed items. */ splice : function(index, howMany, varargs){ return qxWeb.$init(Array.prototype.splice.apply(this, arguments)); }, /** * Returns a new collection containing the modified elements. For more details, check out the * <a href='https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map' target='_blank'>MDN documentation</a>. * * @param callback {Function} Function which produces the new element. * @param thisarg {var} Context of the callback. * @return {q} New collection containing the elements that passed the filter */ map : function(callback, thisarg){ return qxWeb.$init(Array.prototype.map.apply(this, arguments)); }, /** * Returns a copy of the collection including the given elements. * * @param varargs {var} As many items as you want to add. * @return {q} A new collection containing all items. */ concat : function(varargs){ var clone = Array.prototype.slice.call(this, 0); for(var i = 0;i < arguments.length;i++){ if(arguments[i] instanceof qxWeb){ clone = clone.concat(Array.prototype.slice.call(arguments[i], 0)); } else { clone.push(arguments[i]); }; }; return qxWeb.$init(clone); } }, /** * @lint ignoreUndefined(q) */ defer : function(statics){ if(window.q == undefined){ q = statics; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Date' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *now*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/now">MDN documentation</a> | * <a href="http://es5.github.com/#x15.9.4.4">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Date", { defer : function(){ // Date.now if(!qx.core.Environment.get("ecmascript.date.now")){ Date.now = function(){ return +new Date(); }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * jQuery http://jquery.com Version 1.3.1 Copyright: 2009 John Resig License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #ignore(qx.data.IListData) #ignore(qx.Class) #require(qx.lang.normalize.Date) ************************************************************************ */ /** * Static helper functions for arrays with a lot of often used convenience * methods like <code>remove</code> or <code>contains</code>. * * The native JavaScript Array is not modified by this class. However, * there are modifications to the native Array in {@link qx.lang.normalize.Array} for * browsers that do not support certain JavaScript features natively . */ qx.Bootstrap.define("qx.lang.Array", { statics : { /** * Converts array like constructions like the <code>argument</code> object, * node collections like the ones returned by <code>getElementsByTagName</code> * or extended array objects like <code>qx.type.BaseArray</code> to an * native Array instance. * * @deprecated {2.1} Please use cast with 'Array' as constructor. * @param object {var} any array like object * @param offset {Integer?0} position to start from * @return {Array} New array with the content of the incoming object */ toArray : function(object, offset){ { }; return this.cast(object, Array, offset); }, /** * Converts an array like object to any other array like * object. * * Attention: The returned array may be same * instance as the incoming one if the constructor is identical! * * @param object {var} any array-like object * @param constructor {Function} constructor of the new instance * @param offset {Integer?0} position to start from * @return {Array} the converted array */ cast : function(object, constructor, offset){ if(object.constructor === constructor){ return object; }; if(qx.data && qx.data.IListData){ if(qx.Class && qx.Class.hasInterface(object, qx.data.IListData)){ var object = object.toArray(); }; }; // Create from given constructor var ret = new constructor; // Some collections in mshtml are not able to be sliced. // These lines are a special workaround for this client. if((qx.core.Environment.get("engine.name") == "mshtml")){ if(object.item){ for(var i = offset || 0,l = object.length;i < l;i++){ ret.push(object[i]); }; return ret; }; }; // Copy over items if(Object.prototype.toString.call(object) === "[object Array]" && offset == null){ ret.push.apply(ret, object); } else { ret.push.apply(ret, Array.prototype.slice.call(object, offset || 0)); }; return ret; }, /** * Convert an arguments object into an array. * * @param args {arguments} arguments object * @param offset {Integer?0} position to start from * @return {Array} a newly created array (copy) with the content of the arguments object. */ fromArguments : function(args, offset){ return Array.prototype.slice.call(args, offset || 0); }, /** * Convert a (node) collection into an array * * @param coll {var} node collection * @return {Array} a newly created array (copy) with the content of the node collection. */ fromCollection : function(coll){ // The native Array.slice cannot be used with some Array-like objects // including NodeLists in older IEs if((qx.core.Environment.get("engine.name") == "mshtml")){ if(coll.item){ var arr = []; for(var i = 0,l = coll.length;i < l;i++){ arr[i] = coll[i]; }; return arr; }; }; return Array.prototype.slice.call(coll, 0); }, /** * Expand shorthand definition to a four element list. * This is an utility function for padding/margin and all other shorthand handling. * * @param input {Array} arr with one to four elements * @return {Array} an arr with four elements */ fromShortHand : function(input){ var len = input.length; var result = qx.lang.Array.clone(input); // Copy Values (according to the length) switch(len){case 1: result[1] = result[2] = result[3] = result[0]; break;case 2: result[2] = result[0];// no break here case 3: result[3] = result[1];}; // Return list with 4 items return result; }, /** * Return a copy of the given array * * @param arr {Array} the array to copy * @return {Array} copy of the array */ clone : function(arr){ return arr.concat(); }, /** * Insert an element at a given position into the array * * @param arr {Array} the array * @param obj {var} the element to insert * @param i {Integer} position where to insert the element into the array * @return {Array} the array */ insertAt : function(arr, obj, i){ arr.splice(i, 0, obj); return arr; }, /** * Insert an element into the array before a given second element. * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 before this object * @return {Array} the array */ insertBefore : function(arr, obj, obj2){ var i = arr.indexOf(obj2); if(i == -1){ arr.push(obj); } else { arr.splice(i, 0, obj); }; return arr; }, /** * Insert an element into the array after a given second element. * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 after this object * @return {Array} the array */ insertAfter : function(arr, obj, obj2){ var i = arr.indexOf(obj2); if(i == -1 || i == (arr.length - 1)){ arr.push(obj); } else { arr.splice(i + 1, 0, obj); }; return arr; }, /** * Remove an element from the array at the given index * * @param arr {Array} the array * @param i {Integer} index of the element to be removed * @return {var} The removed element. */ removeAt : function(arr, i){ return arr.splice(i, 1)[0]; }, /** * Remove all elements from the array * * @param arr {Array} the array * @return {Array} empty array */ removeAll : function(arr){ arr.length = 0; return this; }, /** * Append the elements of an array to the array * * @param arr1 {Array} the array * @param arr2 {Array} the elements of this array will be appended to other one * @return {Array} The modified array. * @throws {Error} if one of the arguments is not an array */ append : function(arr1, arr2){ { }; Array.prototype.push.apply(arr1, arr2); return arr1; }, /** * Modifies the first array as it removes all elements * which are listed in the second array as well. * * @param arr1 {Array} the array * @param arr2 {Array} the elements of this array will be excluded from the other one * @return {Array} The modified array. * @throws {Error} if one of the arguments is not an array */ exclude : function(arr1, arr2){ { }; for(var i = 0,il = arr2.length,index;i < il;i++){ index = arr1.indexOf(arr2[i]); if(index != -1){ arr1.splice(index, 1); }; }; return arr1; }, /** * Remove an element from the array. * * @param arr {Array} the array * @param obj {var} element to be removed from the array * @return {var} the removed element */ remove : function(arr, obj){ var i = arr.indexOf(obj); if(i != -1){ arr.splice(i, 1); return obj; }; }, /** * Whether the array contains the given element * * @param arr {Array} the array * @param obj {var} object to look for * @return {Boolean} whether the arr contains the element */ contains : function(arr, obj){ return arr.indexOf(obj) !== -1; }, /** * Check whether the two arrays have the same content. Checks only the * equality of the arrays' content. * * @param arr1 {Array} first array * @param arr2 {Array} second array * @return {Boolean} Whether the two arrays are equal */ equals : function(arr1, arr2){ var length = arr1.length; if(length !== arr2.length){ return false; }; for(var i = 0;i < length;i++){ if(arr1[i] !== arr2[i]){ return false; }; }; return true; }, /** * Returns the sum of all values in the given array. Supports * numeric values only. * * @param arr {Number[]} Array to process * @return {Number} The sum of all values. */ sum : function(arr){ var result = 0; for(var i = 0,l = arr.length;i < l;i++){ result += arr[i]; }; return result; }, /** * Returns the highest value in the given array. Supports * numeric values only. * * @param arr {Number[]} Array to process * @return {Number | null} The highest of all values or undefined if array is empty. */ max : function(arr){ { }; var i,len = arr.length,result = arr[0]; for(i = 1;i < len;i++){ if(arr[i] > result){ result = arr[i]; }; }; return result === undefined ? null : result; }, /** * Returns the lowest value in the given array. Supports * numeric values only. * * @param arr {Number[]} Array to process * @return {Number | null} The lowest of all values or undefined if array is empty. */ min : function(arr){ { }; var i,len = arr.length,result = arr[0]; for(i = 1;i < len;i++){ if(arr[i] < result){ result = arr[i]; }; }; return result === undefined ? null : result; }, /** * Recreates an array which is free of all duplicate elements from the original. * * This method do not modifies the original array! * * Keep in mind that this methods deletes undefined indexes. * * @param arr {Array} Incoming array * @return {Array} Returns a copy with no duplicates or the original array if no duplicates were found */ unique : function(arr){ var ret = [],doneStrings = { },doneNumbers = { },doneObjects = { }; var value,count = 0; var key = "qx" + Date.now(); var hasNull = false,hasFalse = false,hasTrue = false; // Rebuild array and omit duplicates for(var i = 0,len = arr.length;i < len;i++){ value = arr[i]; // Differ between null, primitives and reference types if(value === null){ if(!hasNull){ hasNull = true; ret.push(value); }; } else if(value === undefined){ } else if(value === false){ if(!hasFalse){ hasFalse = true; ret.push(value); }; } else if(value === true){ if(!hasTrue){ hasTrue = true; ret.push(value); }; } else if(typeof value === "string"){ if(!doneStrings[value]){ doneStrings[value] = 1; ret.push(value); }; } else if(typeof value === "number"){ if(!doneNumbers[value]){ doneNumbers[value] = 1; ret.push(value); }; } else { var hash = value[key]; if(hash == null){ hash = value[key] = count++; }; if(!doneObjects[hash]){ doneObjects[hash] = value; ret.push(value); }; };;;;; }; // Clear object hashs for(var hash in doneObjects){ try{ // TODO: The following delete seems to fail in IE7 delete doneObjects[hash][key]; } catch(ex) { try{ doneObjects[hash][key] = null; } catch(ex1) { throw new Error("Cannot clean-up map entry doneObjects[" + hash + "][" + key + "]"); }; }; }; return ret; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2008-2010 Sebastian Werner, http://sebastian-werner.net License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * Sizzle CSS Selector Engine - v1.8.2 Homepage: http://sizzlejs.com/ Documentation: http://wiki.github.com/jeresig/sizzle Discussion: http://groups.google.com/group/sizzlejs Code: http://github.com/jeresig/sizzle/tree Copyright: (c) 2009, The Dojo Foundation License: MIT: http://www.opensource.org/licenses/mit-license.php ---------------------------------------------------------------------- Copyright (c) 2009 John Resig 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. ---------------------------------------------------------------------- Version: Snapshot taken on 2012-10-02, latest Sizzle commit on 2012-09-20: commit 41a7c2ce9be6c66e0c9b8b15e0a29c8e3ca6fb31 ************************************************************************ */ /** * The selector engine supports virtually all CSS 3 Selectors – this even * includes some parts that are infrequently implemented such as escaped * selectors (<code>.foo\\+bar</code>), Unicode selectors, and results returned * in document order. There are a few notable exceptions to the CSS 3 selector * support: * * * <code>:root</code> * * <code>:target</code> * * <code>:nth-last-child</code> * * <code>:nth-of-type</code> * * <code>:nth-last-of-type</code> * * <code>:first-of-type</code> * * <code>:last-of-type</code> * * <code>:only-of-type</code> * * <code>:lang()</code> * * In addition to the CSS 3 Selectors the engine supports the following * additional selectors or conventions. * * *Changes* * * * <code>:not(a.b)</code>: Supports non-simple selectors in <code>:not()</code> (most browsers only support <code>:not(a)</code>, for example). * * <code>:not(div > p)</code>: Supports full selectors in <code>:not()</code>. * * <code>:not(div, p)</code>: Supports multiple selectors in <code>:not()</code>. * * <code>[NAME=VALUE]</code>: Doesn't require quotes around the specified value in an attribute selector. * * *Additions* * * * <code>[NAME!=VALUE]</code>: Finds all elements whose <code>NAME</code> attribute doesn't match the specified value. Is equivalent to doing <code>:not([NAME=VALUE])</code>. * * <code>:contains(TEXT)</code>: Finds all elements whose textual context contains the word <code>TEXT</code> (case sensitive). * * <code>:header</code>: Finds all elements that are a header element (h1, h2, h3, h4, h5, h6). * * <code>:parent</code>: Finds all elements that contains another element. * * *Positional Selector Additions* * * * <code>:first</code>/</code>:last</code>: Finds the first or last matching element on the page. (e.g. <code>div:first</code> would find the first div on the page, in document order) * * <code>:even</code>/<code>:odd</code>: Finds every other element on the page (counting begins at 0, so <code>:even</code> would match the first element). * * <code>:eq</code>/<code>:nth</code>: Finds the Nth element on the page (e.g. <code>:eq(5)</code> finds the 6th element on the page). * * <code>:lt</code>/<code>:gt</code>: Finds all elements at positions less than or greater than the specified positions. * * *Form Selector Additions* * * * <code>:input</code>: Finds all input elements (includes textareas, selects, and buttons). * * <code>:text</code>, <code>:checkbox</code>, <code>:file</code>, <code>:password</code>, <code>:submit</code>, <code>:image</code>, <code>:reset</code>, <code>:button</code>: Finds the input element with the specified input type (<code>:button</code> also finds button elements). * * Based on Sizzle by John Resig, see: * * * http://sizzlejs.com/ * * For further usage details also have a look at the wiki page at: * * * https://github.com/jquery/sizzle/wiki/Sizzle-Home */ qx.Bootstrap.define("qx.bom.Selector", { statics : { /** * Queries the document for the given selector. Supports all CSS3 selectors * plus some extensions as mentioned in the class description. * * @signature function(selector, context) * @param selector {String} Valid selector (CSS3 + extensions) * @param context {Element} Context element (result elements must be children of this element) * @return {Array} Matching elements */ query : null, /** * Returns an reduced array which only contains the elements from the given * array which matches the given selector * * @signature function(selector, set) * @param selector {String} Selector to filter given set * @param set {Array} List to filter according to given selector * @return {Array} New array containing matching elements */ matches : null } }); /** * Below is the original Sizzle code. Snapshot date is mentioned in the head of * this file. * @lint ignoreUnused(j, rnot, rendsWithNot) */ /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function(window, undefined){ var cachedruns,assertGetIdNotName,Expr,getText,isXML,contains,compile,sortOrder,hasDuplicate,outermostContext,baseHasDuplicate = true,strundefined = "undefined",expando = ("sizcache" + Math.random()).replace(".", ""),Token = String,document = window.document,docElem = document.documentElement,dirruns = 0,done = 0,pop = [].pop,push = [].push,slice = [].slice,// Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function(elem){ var i = 0,len = this.length; for(;i < len;i++){ if(this[i] === elem){ return i; }; }; return -1; },// Augment a function for special use by Sizzle markFunction = function(fn, value){ fn[expando] = value == null || value; return fn; },createCache = function(){ var cache = { },keys = []; return markFunction(function(key, value){ // Only keep the most recent entries if(keys.push(key) > Expr.cacheLength){ delete cache[keys.shift()]; }; return (cache[key] = value); }, cache); },classCache = createCache(),tokenCache = createCache(),compilerCache = createCache(),// Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]",// http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",// Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace("w", "w#"),// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)",attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",// Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",// For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"),rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"),rcombinators = new RegExp("^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*"),rpseudo = new RegExp(pseudos),// Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,rnot = /^:not/,rsibling = /[\x20\t\r\n\f]*[+~]/,rendsWithNot = /:not\($/,rheader = /h\d/i,rinputs = /input|select|textarea|button/i,rbackslash = /\\(?!\\)/g,matchExpr = { "ID" : new RegExp("^#(" + characterEncoding + ")"), "CLASS" : new RegExp("^\\.(" + characterEncoding + ")"), "NAME" : new RegExp("^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]"), "TAG" : new RegExp("^(" + characterEncoding.replace("w", "w*") + ")"), "ATTR" : new RegExp("^" + attributes), "PSEUDO" : new RegExp("^" + pseudos), "POS" : new RegExp(pos, "i"), "CHILD" : new RegExp("^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"), // For use in libraries implementing .is() "needsContext" : new RegExp("^" + whitespace + "*[>+~]|" + pos, "i") },// Support // Used for testing something on an element assert = function(fn){ var div = document.createElement("div"); try{ return fn(div); } catch(e) { return false; }finally{ // release memory in IE div = null; }; },// Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function(div){ div.appendChild(document.createComment("")); return !div.getElementsByTagName("*").length; }),// Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function(div){ div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }),// Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function(div){ div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }),// Check if getElementsByClassName can be trusted assertUsableClassName = assert(function(div){ // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if(!div.getElementsByClassName || !div.getElementsByClassName("e").length){ return false; }; // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }),// Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function(div){ // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore(div, docElem.firstChild); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName(expando).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName(expando + 0).length; assertGetIdNotName = !document.getElementById(expando); // Cleanup docElem.removeChild(div); return pass; }); // If slice is not available, provide a backup try{ slice.call(docElem.childNodes, 0)[0].nodeType; } catch(e) { slice = function(i){ var elem,results = []; for(;(elem = this[i]);i++){ results.push(elem); }; return results; }; }; function Sizzle(selector, context, results, seed){ results = results || []; context = context || document; var match,elem,xml,m,nodeType = context.nodeType; if(!selector || typeof selector !== "string"){ return results; }; if(nodeType !== 1 && nodeType !== 9){ return []; }; xml = isXML(context); if(!xml && !seed){ if((match = rquickExpr.exec(selector))){ // Speed-up: Sizzle("#ID") if((m = match[1])){ if(nodeType === 9){ elem = context.getElementById(m); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if(elem && elem.parentNode){ // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if(elem.id === m){ results.push(elem); return results; }; } else { return results; }; } else { // Context is not a document if(context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m){ results.push(elem); return results; }; }; } else if(match[2]){ push.apply(results, slice.call(context.getElementsByTagName(selector), 0)); return results; } else if((m = match[3]) && assertUsableClassName && context.getElementsByClassName){ push.apply(results, slice.call(context.getElementsByClassName(m), 0)); return results; };; }; }; // All others return select(selector.replace(rtrim, "$1"), context, results, seed, xml); }; Sizzle.matches = function(expr, elements){ return Sizzle(expr, null, null, elements); }; Sizzle.matchesSelector = function(elem, expr){ return Sizzle(expr, null, null, [elem]).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo(type){ return function(elem){ var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; }; // Returns a function to use in pseudos for buttons function createButtonPseudo(type){ return function(elem){ var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; }; // Returns a function to use in pseudos for positionals function createPositionalPseudo(fn){ return markFunction(function(argument){ argument = +argument; return markFunction(function(seed, matches){ var j,matchIndexes = fn([], seed.length, argument),i = matchIndexes.length; // Match elements found at the specified indexes while(i--){ if(seed[(j = matchIndexes[i])]){ seed[j] = !(matches[j] = seed[j]); }; }; }); }); }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function(elem){ var node,ret = "",i = 0,nodeType = elem.nodeType; if(nodeType){ if(nodeType === 1 || nodeType === 9 || nodeType === 11){ // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if(typeof elem.textContent === "string"){ return elem.textContent; } else { // Traverse its children for(elem = elem.firstChild;elem;elem = elem.nextSibling){ ret += getText(elem); }; }; } else if(nodeType === 3 || nodeType === 4){ return elem.nodeValue; }; } else { // If no nodeType, this is expected to be an array for(;(node = elem[i]);i++){ // Do not traverse comment nodes ret += getText(node); }; }; return ret; }; isXML = Sizzle.isXML = function(elem){ // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function(a, b){ var adown = a.nodeType === 9 ? a.documentElement : a,bup = b && b.parentNode; return a === bup || !!(bup && bup.nodeType === 1 && adown.contains && adown.contains(bup)); } : docElem.compareDocumentPosition ? function(a, b){ return b && !!(a.compareDocumentPosition(b) & 16); } : function(a, b){ while((b = b.parentNode)){ if(b === a){ return true; }; }; return false; }; Sizzle.attr = function(elem, name){ var val,xml = isXML(elem); if(!xml){ name = name.toLowerCase(); }; if((val = Expr.attrHandle[name])){ return val(elem); }; if(xml || assertAttributes){ return elem.getAttribute(name); }; val = elem.getAttributeNode(name); return val ? typeof elem[name] === "boolean" ? elem[name] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength : 50, createPseudo : markFunction, match : matchExpr, // IE6/7 return a modified href attrHandle : assertHrefNotNormalized ? { } : { "href" : function(elem){ return elem.getAttribute("href", 2); }, "type" : function(elem){ return elem.getAttribute("type"); } }, find : { "ID" : assertGetIdNotName ? function(id, context, xml){ if(typeof context.getElementById !== strundefined && !xml){ var m = context.getElementById(id); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; }; } : function(id, context, xml){ if(typeof context.getElementById !== strundefined && !xml){ var m = context.getElementById(id); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; }; }, "TAG" : assertTagNameNoComments ? function(tag, context){ if(typeof context.getElementsByTagName !== strundefined){ return context.getElementsByTagName(tag); }; } : function(tag, context){ var results = context.getElementsByTagName(tag); // Filter out possible comments if(tag === "*"){ var elem,tmp = [],i = 0; for(;(elem = results[i]);i++){ if(elem.nodeType === 1){ tmp.push(elem); }; }; return tmp; }; return results; }, "NAME" : assertUsableName && function(tag, context){ if(typeof context.getElementsByName !== strundefined){ return context.getElementsByName(name); }; }, "CLASS" : assertUsableClassName && function(className, context, xml){ if(typeof context.getElementsByClassName !== strundefined && !xml){ return context.getElementsByClassName(className); }; } }, relative : { ">" : { dir : "parentNode", first : true }, " " : { dir : "parentNode" }, "+" : { dir : "previousSibling", first : true }, "~" : { dir : "previousSibling" } }, preFilter : { "ATTR" : function(match){ match[1] = match[1].replace(rbackslash, ""); // Move the given value to match[3] whether quoted or unquoted match[3] = (match[4] || match[5] || "").replace(rbackslash, ""); if(match[2] === "~="){ match[3] = " " + match[3] + " "; }; return match.slice(0, 4); }, "CHILD" : function(match){ /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if(match[1] === "nth"){ // nth-child requires argument if(!match[2]){ Sizzle.error(match[0]); }; // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +(match[3] ? match[4] + (match[5] || 1) : 2 * (match[2] === "even" || match[2] === "odd")); match[4] = +((match[6] + match[7]) || match[2] === "odd"); } else if(match[2]){ Sizzle.error(match[0]); }; return match; }, "PSEUDO" : function(match){ var unquoted,excess; if(matchExpr["CHILD"].test(match[0])){ return null; }; if(match[3]){ match[2] = match[3]; } else if((unquoted = match[4])){ // Only check arguments that contain a pseudo if(rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize(unquoted, true)) && // advance to the next closing parenthesis (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)){ // excess is a negative index unquoted = unquoted.slice(0, excess); match[0] = match[0].slice(0, excess); }; match[2] = unquoted; }; // Return only captures needed by the pseudo filter method (type and argument) return match.slice(0, 3); } }, filter : { "ID" : assertGetIdNotName ? function(id){ id = id.replace(rbackslash, ""); return function(elem){ return elem.getAttribute("id") === id; }; } : function(id){ id = id.replace(rbackslash, ""); return function(elem){ var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG" : function(nodeName){ if(nodeName === "*"){ return function(){ return true; }; }; nodeName = nodeName.replace(rbackslash, "").toLowerCase(); return function(elem){ return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS" : function(className){ var pattern = classCache[expando][className]; if(!pattern){ pattern = classCache(className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")); }; return function(elem){ return pattern.test(elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || ""); }; }, "ATTR" : function(name, operator, check){ return function(elem, context){ var result = Sizzle.attr(elem, name); if(result == null){ return operator === "!="; }; if(!operator){ return true; }; result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf(check) === 0 : operator === "*=" ? check && result.indexOf(check) > -1 : operator === "$=" ? check && result.substr(result.length - check.length) === check : operator === "~=" ? (" " + result + " ").indexOf(check) > -1 : operator === "|=" ? result === check || result.substr(0, check.length + 1) === check + "-" : false; }; }, "CHILD" : function(type, argument, first, last){ if(type === "nth"){ return function(elem){ var node,diff,parent = elem.parentNode; if(first === 1 && last === 0){ return true; }; if(parent){ diff = 0; for(node = parent.firstChild;node;node = node.nextSibling){ if(node.nodeType === 1){ diff++; if(elem === node){ break; }; }; }; }; // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || (diff % first === 0 && diff / first >= 0); }; }; return function(elem){ var node = elem; switch(type){case "only":case "first": while((node = node.previousSibling)){ if(node.nodeType === 1){ return false; }; }; if(type === "first"){ return true; }; node = elem;/* falls through */ case "last": while((node = node.nextSibling)){ if(node.nodeType === 1){ return false; }; }; return true;}; }; }, "PSEUDO" : function(pseudo, argument){ // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args,fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if(fn[expando]){ return fn(argument); }; // But maintain support for old signatures if(fn.length > 1){ args = [pseudo, pseudo, "", argument]; return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function(seed, matches){ var idx,matched = fn(seed, argument),i = matched.length; while(i--){ idx = indexOf.call(seed, matched[i]); seed[idx] = !(matches[idx] = matched[i]); }; }) : function(elem){ return fn(elem, 0, args); }; }; return fn; } }, pseudos : { "not" : markFunction(function(selector){ // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [],results = [],matcher = compile(selector.replace(rtrim, "$1")); return matcher[expando] ? markFunction(function(seed, matches, context, xml){ var elem,unmatched = matcher(seed, null, xml, []),i = seed.length; // Match elements unmatched by `matcher` while(i--){ if((elem = unmatched[i])){ seed[i] = !(matches[i] = elem); }; }; }) : function(elem, context, xml){ input[0] = elem; matcher(input, null, xml, results); return !results.pop(); }; }), "has" : markFunction(function(selector){ return function(elem){ return Sizzle(selector, elem).length > 0; }; }), "contains" : markFunction(function(text){ return function(elem){ return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1; }; }), "enabled" : function(elem){ return elem.disabled === false; }, "disabled" : function(elem){ return elem.disabled === true; }, "checked" : function(elem){ // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected" : function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly if(elem.parentNode){ elem.parentNode.selectedIndex; }; return elem.selected === true; }, "parent" : function(elem){ return !Expr.pseudos["empty"](elem); }, "empty" : function(elem){ // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while(elem){ if(elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4){ return false; }; elem = elem.nextSibling; }; return true; }, "header" : function(elem){ return rheader.test(elem.nodeName); }, "text" : function(elem){ var type,attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type); }, // Input types "radio" : createInputPseudo("radio"), "checkbox" : createInputPseudo("checkbox"), "file" : createInputPseudo("file"), "password" : createInputPseudo("password"), "image" : createInputPseudo("image"), "submit" : createButtonPseudo("submit"), "reset" : createButtonPseudo("reset"), "button" : function(elem){ var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input" : function(elem){ return rinputs.test(elem.nodeName); }, "focus" : function(elem){ var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); }, "active" : function(elem){ return elem === elem.ownerDocument.activeElement; }, // Positional types "first" : createPositionalPseudo(function(matchIndexes, length, argument){ return [0]; }), "last" : createPositionalPseudo(function(matchIndexes, length, argument){ return [length - 1]; }), "eq" : createPositionalPseudo(function(matchIndexes, length, argument){ return [argument < 0 ? argument + length : argument]; }), "even" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = 0;i < length;i += 2){ matchIndexes.push(i); }; return matchIndexes; }), "odd" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = 1;i < length;i += 2){ matchIndexes.push(i); }; return matchIndexes; }), "lt" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = argument < 0 ? argument + length : argument;--i >= 0;){ matchIndexes.push(i); }; return matchIndexes; }), "gt" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = argument < 0 ? argument + length : argument;++i < length;){ matchIndexes.push(i); }; return matchIndexes; }) } }; function siblingCheck(a, b, ret){ if(a === b){ return ret; }; var cur = a.nextSibling; while(cur){ if(cur === b){ return -1; }; cur = cur.nextSibling; }; return 1; }; sortOrder = docElem.compareDocumentPosition ? function(a, b){ if(a === b){ hasDuplicate = true; return 0; }; return (!a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4) ? -1 : 1; } : function(a, b){ // The nodes are identical, we can exit early if(a === b){ hasDuplicate = true; return 0; } else if(a.sourceIndex && b.sourceIndex){ return a.sourceIndex - b.sourceIndex; }; var al,bl,ap = [],bp = [],aup = a.parentNode,bup = b.parentNode,cur = aup; // If the nodes are siblings (or identical) we can do a quick check if(aup === bup){ return siblingCheck(a, b); } else if(!aup){ return -1; } else if(!bup){ return 1; };; // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while(cur){ ap.unshift(cur); cur = cur.parentNode; }; cur = bup; while(cur){ bp.unshift(cur); cur = cur.parentNode; }; al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for(var i = 0;i < al && i < bl;i++){ if(ap[i] !== bp[i]){ return siblingCheck(ap[i], bp[i]); }; }; // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck(a, bp[i], -1) : siblingCheck(ap[i], b, 1); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort(sortOrder); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function(results){ var elem,i = 1; hasDuplicate = baseHasDuplicate; results.sort(sortOrder); if(hasDuplicate){ for(;(elem = results[i]);i++){ if(elem === results[i - 1]){ results.splice(i--, 1); }; }; }; return results; }; Sizzle.error = function(msg){ throw new Error("Syntax error, unrecognized expression: " + msg); }; function tokenize(selector, parseOnly){ var matched,match,tokens,type,soFar,groups,preFilters,cached = tokenCache[expando][selector]; if(cached){ return parseOnly ? 0 : cached.slice(0); }; soFar = selector; groups = []; preFilters = Expr.preFilter; while(soFar){ // Comma and first run if(!matched || (match = rcomma.exec(soFar))){ if(match){ soFar = soFar.slice(match[0].length); }; groups.push(tokens = []); }; matched = false; // Combinators if((match = rcombinators.exec(soFar))){ tokens.push(matched = new Token(match.shift())); soFar = soFar.slice(matched.length); // Cast descendant combinators to space matched.type = match[0].replace(rtrim, " "); }; // Filters for(type in Expr.filter){ if((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || // The last two arguments here are (context, xml) for backCompat (match = preFilters[type](match, document, true)))){ tokens.push(matched = new Token(match.shift())); soFar = soFar.slice(matched.length); matched.type = type; matched.matches = match; }; }; if(!matched){ break; }; }; // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : // Cache the tokens tokenCache(selector, groups).slice(0); }; function addCombinator(matcher, combinator, base){ var dir = combinator.dir,checkNonElements = base && combinator.dir === "parentNode",doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function(elem, context, xml){ while((elem = elem[dir])){ if(checkNonElements || elem.nodeType === 1){ return matcher(elem, context, xml); }; }; } : // Check against all ancestor/preceding elements function(elem, context, xml){ // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if(!xml){ var cache,dirkey = dirruns + " " + doneName + " ",cachedkey = dirkey + cachedruns; while((elem = elem[dir])){ if(checkNonElements || elem.nodeType === 1){ if((cache = elem[expando]) === cachedkey){ return elem.sizset; } else if(typeof cache === "string" && cache.indexOf(dirkey) === 0){ if(elem.sizset){ return elem; }; } else { elem[expando] = cachedkey; if(matcher(elem, context, xml)){ elem.sizset = true; return elem; }; elem.sizset = false; }; }; }; } else { while((elem = elem[dir])){ if(checkNonElements || elem.nodeType === 1){ if(matcher(elem, context, xml)){ return elem; }; }; }; }; }; }; function elementMatcher(matchers){ return matchers.length > 1 ? function(elem, context, xml){ var i = matchers.length; while(i--){ if(!matchers[i](elem, context, xml)){ return false; }; }; return true; } : matchers[0]; }; function condense(unmatched, map, filter, context, xml){ var elem,newUnmatched = [],i = 0,len = unmatched.length,mapped = map != null; for(;i < len;i++){ if((elem = unmatched[i])){ if(!filter || filter(elem, context, xml)){ newUnmatched.push(elem); if(mapped){ map.push(i); }; }; }; }; return newUnmatched; }; function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector){ if(postFilter && !postFilter[expando]){ postFilter = setMatcher(postFilter); }; if(postFinder && !postFinder[expando]){ postFinder = setMatcher(postFinder, postSelector); }; return markFunction(function(seed, results, context, xml){ // Positional selectors apply to seed elements, so it is invalid to follow them with relative ones if(seed && postFinder){ return; }; var i,elem,postFilterIn,preMap = [],postMap = [],preexisting = results.length,// Get initial elements from seed or context elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, [], seed),// Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems,matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || (seed ? preFilter : preexisting || postFilter) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if(matcher){ matcher(matcherIn, matcherOut, context, xml); }; // Apply postFilter if(postFilter){ postFilterIn = condense(matcherOut, postMap); postFilter(postFilterIn, [], context, xml); // Un-match failing elements by moving them back to matcherIn i = postFilterIn.length; while(i--){ if((elem = postFilterIn[i])){ matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem); }; }; }; // Keep seed and results synchronized if(seed){ // Ignore postFinder because it can't coexist with seed i = preFilter && matcherOut.length; while(i--){ if((elem = matcherOut[i])){ seed[preMap[i]] = !(results[preMap[i]] = elem); }; }; } else { matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut); if(postFinder){ postFinder(null, results, matcherOut, xml); } else { push.apply(results, matcherOut); }; }; }); }; function matcherFromTokens(tokens){ var checkContext,matcher,j,len = tokens.length,leadingRelative = Expr.relative[tokens[0].type],implicitRelative = leadingRelative || Expr.relative[" "],i = leadingRelative ? 1 : 0,// The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator(function(elem){ return elem === checkContext; }, implicitRelative, true),matchAnyContext = addCombinator(function(elem){ return indexOf.call(checkContext, elem) > -1; }, implicitRelative, true),matchers = [function(elem, context, xml){ return (!leadingRelative && (xml || context !== outermostContext)) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml)); }]; for(;i < len;i++){ if((matcher = Expr.relative[tokens[i].type])){ matchers = [addCombinator(elementMatcher(matchers), matcher)]; } else { // The concatenated values are (context, xml) for backCompat matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches); // Return special upon seeing a positional matcher if(matcher[expando]){ // Find the next relative operator (if any) for proper handling j = ++i; for(;j < len;j++){ if(Expr.relative[tokens[j].type]){ break; }; }; return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && tokens.slice(0, i - 1).join("").replace(rtrim, "$1"), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens((tokens = tokens.slice(j))), j < len && tokens.join("")); }; matchers.push(matcher); }; }; return elementMatcher(matchers); }; function matcherFromGroupMatchers(elementMatchers, setMatchers){ var bySet = setMatchers.length > 0,byElement = elementMatchers.length > 0,superMatcher = function(seed, context, xml, results, expandContext){ var elem,j,matcher,setMatched = [],matchedCount = 0,i = "0",unmatched = seed && [],outermost = expandContext != null,contextBackup = outermostContext,// We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]("*", expandContext && context.parentNode || context),// Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if(outermost){ outermostContext = context !== document && context; cachedruns = superMatcher.el; }; // Add elements passing elementMatchers directly to results for(;(elem = elems[i]) != null;i++){ if(byElement && elem){ for(j = 0;(matcher = elementMatchers[j]);j++){ if(matcher(elem, context, xml)){ results.push(elem); break; }; }; if(outermost){ dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; }; }; // Track unmatched elements for set filters if(bySet){ // They will have gone through all possible matchers if((elem = !matcher && elem)){ matchedCount--; }; // Lengthen the array for every element, matched or not if(seed){ unmatched.push(elem); }; }; }; // Apply set filters to unmatched elements matchedCount += i; if(bySet && i !== matchedCount){ for(j = 0;(matcher = setMatchers[j]);j++){ matcher(unmatched, setMatched, context, xml); }; if(seed){ // Reintegrate element matches to eliminate the need for sorting if(matchedCount > 0){ while(i--){ if(!(unmatched[i] || setMatched[i])){ setMatched[i] = pop.call(results); }; }; }; // Discard index placeholder values to get only actual matches setMatched = condense(setMatched); }; // Add matches to results push.apply(results, setMatched); // Seedless set matches succeeding multiple successful matchers stipulate sorting if(outermost && !seed && setMatched.length > 0 && (matchedCount + setMatchers.length) > 1){ Sizzle.uniqueSort(results); }; }; // Override manipulation of globals by nested matchers if(outermost){ dirruns = dirrunsUnique; outermostContext = contextBackup; }; return unmatched; }; superMatcher.el = 0; return bySet ? markFunction(superMatcher) : superMatcher; }; compile = Sizzle.compile = function(selector, group){ var i,setMatchers = [],elementMatchers = [],cached = compilerCache[expando][selector]; if(!cached){ // Generate a function of recursive functions that can be used to check each element if(!group){ group = tokenize(selector); }; i = group.length; while(i--){ cached = matcherFromTokens(group[i]); if(cached[expando]){ setMatchers.push(cached); } else { elementMatchers.push(cached); }; }; // Cache the compiled function cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers)); }; return cached; }; function multipleContexts(selector, contexts, results, seed){ var i = 0,len = contexts.length; for(;i < len;i++){ Sizzle(selector, contexts[i], results, seed); }; return results; }; function select(selector, context, results, seed, xml){ var i,tokens,token,type,find,match = tokenize(selector),j = match.length; if(!seed){ // Try to minimize operations if there is only one group if(match.length === 1){ // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice(0); if(tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !xml && Expr.relative[tokens[1].type]){ context = Expr.find["ID"](token.matches[0].replace(rbackslash, ""), context, xml)[0]; if(!context){ return results; }; selector = selector.slice(tokens.shift().length); }; // Fetch a seed set for right-to-left matching for(i = matchExpr["POS"].test(selector) ? -1 : tokens.length - 1;i >= 0;i--){ token = tokens[i]; // Abort if we hit a combinator if(Expr.relative[(type = token.type)]){ break; }; if((find = Expr.find[type])){ // Search, expanding context for leading sibling combinators if((seed = find(token.matches[0].replace(rbackslash, ""), rsibling.test(tokens[0].type) && context.parentNode || context, xml))){ // If seed is empty or no tokens remain, we can return early tokens.splice(i, 1); selector = seed.length && tokens.join(""); if(!selector){ push.apply(results, slice.call(seed, 0)); return results; }; break; }; }; }; }; }; // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile(selector, match)(seed, context, xml, results, rsibling.test(selector)); return results; }; if(document.querySelectorAll){ (function(){ var disconnectedMatch,oldSelect = select,rescape = /'|\\/g,rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,// qSa(:focus) reports false when true (Chrome 21), // A support test would require too much code (would include document ready) rbuggyQSA = [":focus"],// matchesSelector(:focus) reports false when true (Chrome 21), // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [":active", ":focus"],matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function(div){ // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if(!div.querySelectorAll("[selected]").length){ rbuggyQSA.push("\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)"); }; // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if(!div.querySelectorAll(":checked").length){ rbuggyQSA.push(":checked"); }; }); assert(function(div){ // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if(div.querySelectorAll("[test^='']").length){ rbuggyQSA.push("[*^$]=" + whitespace + "*(?:\"\"|'')"); }; // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if(!div.querySelectorAll(":enabled").length){ rbuggyQSA.push(":enabled", ":disabled"); }; }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp(rbuggyQSA.join("|")); select = function(selector, context, results, seed, xml){ // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if(!seed && !xml && (!rbuggyQSA || !rbuggyQSA.test(selector))){ var groups,i,old = true,nid = expando,newContext = context,newSelector = context.nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if(context.nodeType === 1 && context.nodeName.toLowerCase() !== "object"){ groups = tokenize(selector); if((old = context.getAttribute("id"))){ nid = old.replace(rescape, "\\$&"); } else { context.setAttribute("id", nid); }; nid = "[id='" + nid + "'] "; i = groups.length; while(i--){ groups[i] = nid + groups[i].join(""); }; newContext = rsibling.test(selector) && context.parentNode || context; newSelector = groups.join(","); }; if(newSelector){ try{ push.apply(results, slice.call(newContext.querySelectorAll(newSelector), 0)); return results; } catch(qsaError) { }finally{ if(!old){ context.removeAttribute("id"); }; }; }; }; return oldSelect(selector, context, results, seed, xml); }; if(matches){ assert(function(div){ // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call(div, "div"); // This should fail with an exception // Gecko does not error, returns false instead try{ matches.call(div, "[test!='']:sizzle"); rbuggyMatches.push("!=", pseudos); } catch(e) { }; }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp(rbuggyMatches.join("|")); Sizzle.matchesSelector = function(elem, expr){ // Make sure that attribute selectors are quoted expr = expr.replace(rattributeQuotes, "='$1']"); // rbuggyMatches always contains :active, so no need for an existence check if(!isXML(elem) && !rbuggyMatches.test(expr) && (!rbuggyQSA || !rbuggyQSA.test(expr))){ try{ var ret = matches.call(elem, expr); // IE 9's matchesSelector returns false on disconnected nodes if(ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11){ return ret; }; } catch(e) { }; }; return Sizzle(expr, null, null, [elem]).length > 0; }; }; })(); }; // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters(){ }; Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // EXPOSE qooxdoo variant qx.bom.Selector.query = function(selector, context){ return Sizzle(selector, context); }; qx.bom.Selector.matches = function(selector, set){ return Sizzle(selector, null, null, set); }; })(window); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2007-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Utility class with type check for all native JavaScript data types. */ qx.Bootstrap.define("qx.lang.Type", { statics : { /** * Get the internal class of the value. See * http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ * for details. * * @signature function(value) * @param value {var} value to get the class for * @return {String} the internal class of the value */ getClass : qx.Bootstrap.getClass, /** * Whether the value is a string. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is a string. */ isString : qx.Bootstrap.isString, /** * Whether the value is an array. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is an array. */ isArray : qx.Bootstrap.isArray, /** * Whether the value is an object. Note that built-in types like Window are * not reported to be objects. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is an object. */ isObject : qx.Bootstrap.isObject, /** * Whether the value is a function. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is a function. */ isFunction : qx.Bootstrap.isFunction, /** * Whether the value is a regular expression. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a regular expression. */ isRegExp : function(value){ return this.getClass(value) == "RegExp"; }, /** * Whether the value is a number. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a number. */ isNumber : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Number" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Number" || value instanceof Number)); }, /** * Whether the value is a boolean. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a boolean. */ isBoolean : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Boolean" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Boolean" || value instanceof Boolean)); }, /** * Whether the value is a date. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a date. */ isDate : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Date" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Date" || value instanceof Date)); }, /** * Whether the value is a Error. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a Error. */ isError : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Error" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Error" || value instanceof Error)); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This module offers a cross browser storage implementation. The API is aligned * with the API of the HTML web storage (http://www.w3.org/TR/webstorage/) which is * also the preferred implementation used. As fallback for IE < 8, we use user data. * If both techniques are unsupported, we supply a in memory storage, which is * of course, not persistent. */ qx.Bootstrap.define("qx.module.Storage", { statics : { /** * Store an item in the storage. * * @attachStatic {qxWeb, localStorage.setItem} * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setLocalItem : function(key, value){ qx.bom.Storage.getLocal().setItem(key, value); }, /** * Returns the stored item. * * @attachStatic {qxWeb, localStorage.getItem} * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getLocalItem : function(key){ return qx.bom.Storage.getLocal().getItem(key); }, /** * Removes an item form the storage. * @attachStatic {qxWeb, localStorage.removeItem} * @param key {String} The identifier. */ removeLocalItem : function(key){ qx.bom.Storage.getLocal().removeItem(key); }, /** * Returns the amount of key-value pairs stored. * @attachStatic {qxWeb, localStorage.getLength} * @return {Number} The length of the storage. */ getLocalLength : function(){ return qx.bom.Storage.getLocal().getLength(); }, /** * Returns the named key at the given index. * @attachStatic {qxWeb, localStorage.getKey} * @param index {Number} The index in the storage. * @return {String} The key stored at the given index. */ getLocalKey : function(index){ return qx.bom.Storage.getLocal().getKey(index); }, /** * Deletes every stored item in the storage. * @attachStatic {qxWeb, localStorage.clear} */ clearLocal : function(){ qx.bom.Storage.getLocal().clear(); }, /** * Helper to access every stored item. * * @attachStatic {qxWeb, localStorage.forEach} * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEachLocal : function(callback, scope){ qx.bom.Storage.getLocal().forEach(callback, scope); }, /** * Store an item in the storage. * * @attachStatic {qxWeb, sessionStorage.setItem} * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setSessionItem : function(key, value){ qx.bom.Storage.getSession().setItem(key, value); }, /** * Returns the stored item. * * @attachStatic {qxWeb, sessionStorage.getItem} * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getSessionItem : function(key){ return qx.bom.Storage.getSession().getItem(key); }, /** * Removes an item form the storage. * @attachStatic {qxWeb, sessionStorage.removeItem} * @param key {String} The identifier. */ removeSessionItem : function(key){ qx.bom.Storage.getSession().removeItem(key); }, /** * Returns the amount of key-value pairs stored. * @attachStatic {qxWeb, sessionStorage.getLength} * @return {Number} The length of the storage. */ getSessionLength : function(){ return qx.bom.Storage.getSession().getLength(); }, /** * Returns the named key at the given index. * @attachStatic {qxWeb, sessionStorage.getKey} * @param index {Number} The index in the storage. * @return {String} The key stored at the given index. */ getSessionKey : function(index){ return qx.bom.Storage.getSession().getKey(index); }, /** * Deletes every stored item in the storage. * @attachStatic {qxWeb, sessionStorage.clear} */ clearSession : function(){ qx.bom.Storage.getSession().clear(); }, /** * Helper to access every stored item. * * @attachStatic {qxWeb, sessionStorage.forEach} * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEachSession : function(callback, scope){ qx.bom.Storage.getSession().forEach(callback, scope); } }, defer : function(statics){ qxWeb.$attachStatic({ "localStorage" : { setItem : statics.setLocalItem, getItem : statics.getLocalItem, removeItem : statics.removeLocalItem, getLength : statics.getLocalLength, getKey : statics.getLocalKey, clear : statics.clearLocal, forEach : statics.forEachLocal }, "sessionStorage" : { setItem : statics.setSessionItem, getItem : statics.getSessionItem, removeItem : statics.removeSessionItem, getLength : statics.getSessionLength, getKey : statics.getSessionKey, clear : statics.clearSession, forEach : statics.forEachSession } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This is a cross browser storage implementation. The API is aligned with the * API of the HTML web storage (http://www.w3.org/TR/webstorage/) which is also * the preferred implementation used. As fallback for IE < 8, we use user data. * If both techniques are unsupported, we supply a in memory storage, which is * of course, not persistent. */ qx.Bootstrap.define("qx.bom.Storage", { statics : { __impl : null, /** * Get an instance of a local storage. * @return {qx.bom.storage.Web|qx.bom.storage.UserData|qx.bom.storage.Memory} * An instance of a storage implementation. */ getLocal : function(){ // always use HTML5 web storage if available if(qx.core.Environment.get("html.storage.local")){ return qx.bom.storage.Web.getLocal(); } else if(qx.core.Environment.get("html.storage.userdata")){ // IE <8 fallback // as fallback,use the userdata storage for IE5.5 - 8 return qx.bom.storage.UserData.getLocal(); }; // as last fallback, use a in memory storage (this one is not persistent) return qx.bom.storage.Memory.getLocal(); }, /** * Get an instance of a session storage. * @return {qx.bom.storage.Web|qx.bom.storage.UserData|qx.bom.storage.Memory} * An instance of a storage implementation. */ getSession : function(){ // always use HTML5 web storage if available if(qx.core.Environment.get("html.storage.local")){ return qx.bom.storage.Web.getSession(); } else if(qx.core.Environment.get("html.storage.userdata")){ // IE <8 fallback // as fallback,use the userdata storage for IE5.5 - 8 return qx.bom.storage.UserData.getSession(); }; // as last fallback, use a in memory storage (this one is not persistent) return qx.bom.storage.Memory.getSession(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Internal class which contains the checks used by {@link qx.core.Environment}. * All checks in here are marked as internal which means you should never use * them directly. * * This class should contain all checks about HTML. * * @internal */ qx.Bootstrap.define("qx.bom.client.Html", { statics : { /** * Whether the client supports Web Workers. * * @internal * @return {Boolean} <code>true</code> if webworkers are supported */ getWebWorker : function(){ return window.Worker != null; }, /** * Whether the client supports File Readers * * @internal * @return {Boolean} <code>true</code> if FileReaders are supported */ getFileReader : function(){ return window.FileReader != null; }, /** * Whether the client supports Geo Location. * * @internal * @return {Boolean} <code>true</code> if geolocation supported */ getGeoLocation : function(){ return navigator.geolocation != null; }, /** * Whether the client supports audio. * * @internal * @return {Boolean} <code>true</code> if audio is supported */ getAudio : function(){ return !!document.createElement('audio').canPlayType; }, /** * Whether the client can play ogg audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioOgg : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/ogg"); }, /** * Whether the client can play mp3 audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioMp3 : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/mpeg"); }, /** * Whether the client can play wave audio wave format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioWav : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/x-wav"); }, /** * Whether the client can play au audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioAu : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/basic"); }, /** * Whether the client can play aif audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioAif : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/x-aiff"); }, /** * Whether the client supports video. * * @internal * @return {Boolean} <code>true</code> if video is supported */ getVideo : function(){ return !!document.createElement('video').canPlayType; }, /** * Whether the client supports ogg video. * * @internal * @return {String} "" or "maybe" or "probably" */ getVideoOgg : function(){ if(!qx.bom.client.Html.getVideo()){ return ""; }; var v = document.createElement("video"); return v.canPlayType('video/ogg; codecs="theora, vorbis"'); }, /** * Whether the client supports mp4 video. * * @internal * @return {String} "" or "maybe" or "probably" */ getVideoH264 : function(){ if(!qx.bom.client.Html.getVideo()){ return ""; }; var v = document.createElement("video"); return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'); }, /** * Whether the client supports webm video. * * @internal * @return {String} "" or "maybe" or "probably" */ getVideoWebm : function(){ if(!qx.bom.client.Html.getVideo()){ return ""; }; var v = document.createElement("video"); return v.canPlayType('video/webm; codecs="vp8, vorbis"'); }, /** * Whether the client supports local storage. * * @internal * @return {Boolean} <code>true</code> if local storage is supported */ getLocalStorage : function(){ try{ return window.localStorage != null; } catch(exc) { // Firefox Bug: Local execution of window.sessionStorage throws error // see https://bugzilla.mozilla.org/show_bug.cgi?id=357323 return false; }; }, /** * Whether the client supports session storage. * * @internal * @return {Boolean} <code>true</code> if session storage is supported */ getSessionStorage : function(){ try{ return window.sessionStorage != null; } catch(exc) { // Firefox Bug: Local execution of window.sessionStorage throws error // see https://bugzilla.mozilla.org/show_bug.cgi?id=357323 return false; }; }, /** * Whether the client supports user data to persist data. This is only * relevant for IE < 8. * * @internal * @return {Boolean} <code>true</code> if the user data is supported. */ getUserDataStorage : function(){ var el = document.createElement("div"); el.style["display"] = "none"; document.getElementsByTagName("head")[0].appendChild(el); var supported = false; try{ el.addBehavior("#default#userdata"); el.load("qxtest"); supported = true; } catch(e) { }; document.getElementsByTagName("head")[0].removeChild(el); return supported; }, /** * Whether the browser supports CSS class lists. * https://developer.mozilla.org/en-US/docs/DOM/element.classList * * @internal * @return {Boolean} <code>true</code> if class list is supported. */ getClassList : function(){ return !!(document.documentElement.classList && qx.Bootstrap.getClass(document.documentElement.classList) === "DOMTokenList"); }, /** * Checks if XPath could be used. * * @internal * @return {Boolean} <code>true</code> if xpath is supported. */ getXPath : function(){ return !!document.evaluate; }, /** * Checks if XUL could be used. * * @internal * @return {Boolean} <code>true</code> if XUL is supported. */ getXul : function(){ try{ document.createElementNS("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "label"); return true; } catch(e) { return false; }; }, /** * Checks if SVG could be used * * @internal * @return {Boolean} <code>true</code> if SVG is supported. */ getSvg : function(){ return document.implementation && document.implementation.hasFeature && (document.implementation.hasFeature("org.w3c.dom.svg", "1.0") || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, /** * Checks if VML is supported * * @internal * @return {Boolean} <code>true</code> if VML is supported. */ getVml : function(){ var el = document.createElement("div"); document.body.appendChild(el); el.innerHTML = '<v:shape id="vml_flag1" adj="1" />'; el.firstChild.style.behavior = "url(#default#VML)"; var hasVml = typeof el.firstChild.adj == "object"; document.body.removeChild(el); return hasVml; }, /** * Checks if canvas could be used * * @internal * @return {Boolean} <code>true</code> if canvas is supported. */ getCanvas : function(){ return !!window.CanvasRenderingContext2D; }, /** * Asynchronous check for using data urls. * * @internal * @param callback {Function} The function which should be executed as * soon as the check is done. */ getDataUrl : function(callback){ var data = new Image(); data.onload = data.onerror = function(){ // wrap that into a timeout because IE might execute it synchronously window.setTimeout(function(){ callback.call(null, (data.width == 1 && data.height == 1)); }, 0); }; data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; }, /** * Checks if dataset could be used * * @internal * @return {Boolean} <code>true</code> if dataset is supported. */ getDataset : function(){ return !!document.documentElement.dataset; }, /** * Check for element.contains * * @internal * @return {Boolean} <code>true</code> if element.contains is supported */ getContains : function(){ // "object" in IE6/7/8, "function" in IE9 return (typeof document.documentElement.contains !== "undefined"); }, /** * Check for element.compareDocumentPosition * * @internal * @return {Boolean} <code>true</code> if element.compareDocumentPosition is supported */ getCompareDocumentPosition : function(){ return (typeof document.documentElement.compareDocumentPosition === "function"); }, /** * Check for element.textContent. Legacy IEs do not support this, use * innerText instead. * * @internal * @return {Boolean} <code>true</code> if textContent is supported */ getTextContent : function(){ var el = document.createElement("span"); return (typeof el.textContent !== "undefined"); }, /** * Check for a console object. * * @internal * @return {Boolean} <code>true</code> if a console is available. */ getConsole : function(){ return typeof window.console !== "undefined"; }, /** * Check for the <code>naturalHeight</code> and <code>naturalWidth</code> * image element attributes. * * @internal * @return {Boolean} <code>true</code> if both attributes are supported */ getNaturalDimensions : function(){ var img = document.createElement("img"); return typeof img.naturalHeight === "number" && typeof img.naturalWidth === "number"; }, /** * Check for HTML5 history manipulation support. * @internal * @return {Boolean} <code>true</code> if the HTML5 history API is supported */ getHistoryState : function(){ return (typeof window.onpopstate !== "undefined" && typeof window.history.replaceState !== "undefined" && typeof window.history.pushState !== "undefined"); }, /** * Returns the name of the native object/function used to access the * document's text selection. * * @return {String|null} <code>getSelection</code> if the standard window.getSelection * function is available; <code>selection</code> if the MS-proprietary * document.selection object is available; <code>null</code> if no known * text selection API is available. */ getSelection : function(){ if(typeof window.getSelection === "function"){ return "getSelection"; }; if(typeof document.selection === "object"){ return "selection"; }; return null; } }, defer : function(statics){ qx.core.Environment.add("html.webworker", statics.getWebWorker); qx.core.Environment.add("html.filereader", statics.getFileReader); qx.core.Environment.add("html.geolocation", statics.getGeoLocation); qx.core.Environment.add("html.audio", statics.getAudio); qx.core.Environment.add("html.audio.ogg", statics.getAudioOgg); qx.core.Environment.add("html.audio.mp3", statics.getAudioMp3); qx.core.Environment.add("html.audio.wav", statics.getAudioWav); qx.core.Environment.add("html.audio.au", statics.getAudioAu); qx.core.Environment.add("html.audio.aif", statics.getAudioAif); qx.core.Environment.add("html.video", statics.getVideo); qx.core.Environment.add("html.video.ogg", statics.getVideoOgg); qx.core.Environment.add("html.video.h264", statics.getVideoH264); qx.core.Environment.add("html.video.webm", statics.getVideoWebm); qx.core.Environment.add("html.storage.local", statics.getLocalStorage); qx.core.Environment.add("html.storage.session", statics.getSessionStorage); qx.core.Environment.add("html.storage.userdata", statics.getUserDataStorage); qx.core.Environment.add("html.classlist", statics.getClassList); qx.core.Environment.add("html.xpath", statics.getXPath); qx.core.Environment.add("html.xul", statics.getXul); qx.core.Environment.add("html.canvas", statics.getCanvas); qx.core.Environment.add("html.svg", statics.getSvg); qx.core.Environment.add("html.vml", statics.getVml); qx.core.Environment.add("html.dataset", statics.getDataset); qx.core.Environment.addAsync("html.dataurl", statics.getDataUrl); qx.core.Environment.add("html.element.contains", statics.getContains); qx.core.Environment.add("html.element.compareDocumentPosition", statics.getCompareDocumentPosition); qx.core.Environment.add("html.element.textcontent", statics.getTextContent); qx.core.Environment.add("html.console", statics.getConsole); qx.core.Environment.add("html.image.naturaldimensions", statics.getNaturalDimensions); qx.core.Environment.add("html.history.state", statics.getHistoryState); qx.core.Environment.add("html.selection", statics.getSelection); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.storage.Web#getLength) #require(qx.bom.storage.Web#setItem) #require(qx.bom.storage.Web#getItem) #require(qx.bom.storage.Web#removeItem) #require(qx.bom.storage.Web#clear) #require(qx.bom.storage.Web#getKey) #require(qx.bom.storage.Web#forEach) ************************************************************************ */ /** * Storage implementation using HTML web storage: * http://www.w3.org/TR/webstorage/ */ qx.Bootstrap.define("qx.bom.storage.Web", { statics : { __local : null, __session : null, /** * Static accessor for the local storage. * @return {qx.bom.storage.Web} An instance of a local storage. */ getLocal : function(){ if(this.__local){ return this.__local; }; return this.__local = new qx.bom.storage.Web("local"); }, /** * Static accessor for the session storage. * @return {qx.bom.storage.Web} An instance of a session storage. */ getSession : function(){ if(this.__session){ return this.__session; }; return this.__session = new qx.bom.storage.Web("session"); } }, /** * Create a new instance. Usually, you should take the static * accessors to get your instance. * * @param type {String} type of storage, either * <code>local</code> or <code>session</code>. */ construct : function(type){ this.__type = type; }, members : { __type : null, /** * Returns the internal used storage (the native object). * * @internal * @return {Storage} The native storage implementation. */ getStorage : function(){ return window[this.__type + "Storage"]; }, /** * Returns the amount of key-value pairs stored. * @return {Integer} The length of the storage. */ getLength : function(){ return this.getStorage(this.__type).length; }, /** * Store an item in the storage. * * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setItem : function(key, value){ value = qx.lang.Json.stringify(value); try{ this.getStorage(this.__type).setItem(key, value); } catch(e) { throw new Error("Storage full."); }; }, /** * Returns the stored item. * * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getItem : function(key){ var item = this.getStorage(this.__type).getItem(key); if(qx.lang.Type.isString(item)){ item = qx.lang.Json.parse(item); } else if(item && item.value && qx.lang.Type.isString(item.value)){ item = qx.lang.Json.parse(item.value); }; return item; }, /** * Removes an item form the storage. * @param key {String} The identifier. */ removeItem : function(key){ this.getStorage(this.__type).removeItem(key); }, /** * Deletes every stored item in the storage. */ clear : function(){ var storage = this.getStorage(this.__type); if(!storage.clear){ for(var i = storage.length - 1;i >= 0;i--){ storage.removeItem(storage.key(i)); }; } else { storage.clear(); }; }, /** * Returns the named key at the given index. * @param index {Integer} The index in the storage. * @return {String} The key stored at the given index. */ getKey : function(index){ return this.getStorage(this.__type).key(index); }, /** * Helper to access every stored item. * * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEach : function(callback, scope){ var length = this.getLength(); for(var i = 0;i < length;i++){ var key = this.getKey(i); callback.call(scope, key, this.getItem(key)); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ________________________________________________________________________ This class contains code based on the following work: http://www.JSON.org/json2.js 2009-06-29 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html ************************************************************************ */ /** * Pure JavaScript implementation of the EcmaScript 3.1 JSON object. This class * is used, if the browser does not support it natively. * * @internal */ qx.Bootstrap.define("qx.lang.JsonImpl", { extend : Object, construct : function(){ // bind parse and stringify so they can be called without a context. this.stringify = qx.lang.Function.bind(this.stringify, this); this.parse = qx.lang.Function.bind(this.parse, this); }, members : { __gap : null, __indent : null, __rep : null, __stack : null, /** * This method produces a JSON text from a JavaScript value. * * @param value {var} any JavaScript value, usually an object or array. * * @param replacer {Function?} an optional parameter that determines how * object values are stringified for objects. It can be a function or an * array of strings. * * @param space {String?} an optional parameter that specifies the * indentation of nested structures. If it is omitted, the text will * be packed without extra whitespace. If it is a number, it will specify * the number of spaces to indent at each level. If it is a string * (such as '\t' or '&nbsp;'), it contains the characters used to indent * at each level. * * @return {String} The JSON string of the value */ stringify : function(value, replacer, space){ this.__gap = ''; this.__indent = ''; this.__stack = []; if(qx.lang.Type.isNumber(space)){ // If the space parameter is a number, make an indent string containing that // many spaces. var space = Math.min(10, Math.floor(space)); for(var i = 0;i < space;i += 1){ this.__indent += ' '; }; } else if(qx.lang.Type.isString(space)){ if(space.length > 10){ space = space.slice(0, 10); }; // If the space parameter is a string, it will be used as the indent string. this.__indent = space; }; // If there is a replacer, it must be a function or an array. // Otherwise, ignore it. if(replacer && (qx.lang.Type.isFunction(replacer) || qx.lang.Type.isArray(replacer))){ this.__rep = replacer; } else { this.__rep = null; }; // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return this.__str('', { '' : value }); }, /** * Produce a string from holder[key]. * * @param key {String} the map key * @param holder {Object} an object with the given key * @return {String} The string representation of holder[key] */ __str : function(key, holder){ var mind = this.__gap,partial,value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if(value && qx.lang.Type.isFunction(value.toJSON)){ value = value.toJSON(key); } else if(qx.lang.Type.isDate(value)){ value = this.dateToJSON(value); }; // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if(typeof this.__rep === 'function'){ value = this.__rep.call(holder, key, value); }; if(value === null){ return 'null'; }; if(value === undefined){ return undefined; }; // What happens next depends on the value's type. switch(qx.lang.Type.getClass(value)){case 'String': return this.__quote(value);case 'Number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null';case 'Boolean': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value);case 'Array': // Make an array to hold the partial results of stringifying this array value. this.__gap += this.__indent; partial = []; if(this.__stack.indexOf(value) !== -1){ throw new TypeError("Cannot stringify a recursive object."); }; this.__stack.push(value); // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. var length = value.length; for(var i = 0;i < length;i += 1){ partial[i] = this.__str(i, value) || 'null'; }; this.__stack.pop(); // Join all of the elements together, separated with commas, and wrap them in // brackets. if(partial.length === 0){ var string = '[]'; } else if(this.__gap){ string = '[\n' + this.__gap + partial.join(',\n' + this.__gap) + '\n' + mind + ']'; } else { string = '[' + partial.join(',') + ']'; }; this.__gap = mind; return string;case 'Object': // Make an array to hold the partial results of stringifying this object value. this.__gap += this.__indent; partial = []; if(this.__stack.indexOf(value) !== -1){ throw new TypeError("Cannot stringify a recursive object."); }; this.__stack.push(value); // If the replacer is an array, use it to select the members to be stringified. if(this.__rep && typeof this.__rep === 'object'){ var length = this.__rep.length; for(var i = 0;i < length;i += 1){ var k = this.__rep[i]; if(typeof k === 'string'){ var v = this.__str(k, value); if(v){ partial.push(this.__quote(k) + (this.__gap ? ': ' : ':') + v); }; }; }; } else { // Otherwise, iterate through all of the keys in the object. for(var k in value){ if(Object.hasOwnProperty.call(value, k)){ var v = this.__str(k, value); if(v){ partial.push(this.__quote(k) + (this.__gap ? ': ' : ':') + v); }; }; }; }; this.__stack.pop(); // Join all of the member texts together, separated with commas, // and wrap them in braces. if(partial.length === 0){ var string = '{}'; } else if(this.__gap){ string = '{\n' + this.__gap + partial.join(',\n' + this.__gap) + '\n' + mind + '}'; } else { string = '{' + partial.join(',') + '}'; }; this.__gap = mind; return string;}; }, /** * Convert a date to JSON * * @param date {Date} The date to convert * @return {String} The JSON representation of the date */ dateToJSON : function(date){ // Format integers to have at least two digits. var f2 = function(n){ return n < 10 ? '0' + n : n; }; var f3 = function(n){ var value = f2(n); return n < 100 ? '0' + value : value; }; return isFinite(date.valueOf()) ? date.getUTCFullYear() + '-' + f2(date.getUTCMonth() + 1) + '-' + f2(date.getUTCDate()) + 'T' + f2(date.getUTCHours()) + ':' + f2(date.getUTCMinutes()) + ':' + f2(date.getUTCSeconds()) + '.' + f3(date.getUTCMilliseconds()) + 'Z' : null; }, /** * If the string contains no control characters, no quote characters, and no * backslash characters, then we can safely slap some quotes around it. * Otherwise we must also replace the offending characters with safe escape * sequences. * * @param string {String} The string to quote * @return {String} The quoted string */ __quote : function(string){ var meta = { // table of character substitutions '\b' : '\\b', '\t' : '\\t', '\n' : '\\n', '\f' : '\\f', '\r' : '\\r', '"' : '\\"', '\\' : '\\\\' }; var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; escapable.lastIndex = 0; if(escapable.test(string)){ return '"' + string.replace(escapable, function(a){ var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"'; } else { return '"' + string + '"'; }; }, /** * This method parses a JSON text to produce an object or array. * It can throw a SyntaxError exception. * * @param text {String} JSON string to parse * * @param reviver {Function?} Optional reviver function to filter and * transform the results * * @return {Object} The parsed JSON object * * @lint ignoreDeprecated(eval) */ parse : function(text, reviver){ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; cx.lastIndex = 0; // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. if(cx.test(text)){ text = text.replace(cx, function(a){ return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); }; // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))){ // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. var j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? this.__walk({ '' : j }, '', reviver) : j; }; // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }, /** * The walk method is used to recursively walk the resulting structure so * that modifications can be made. * * @param holder {Object} the root object * @param key {String} walk holder[key] * @param reviver {Function} callback, which is called on every node. * @return {var} The reviver's return value */ __walk : function(holder, key, reviver){ var value = holder[key]; if(value && typeof value === 'object'){ for(var k in value){ if(Object.hasOwnProperty.call(value, k)){ var v = this.__walk(value, k, reviver); if(v !== undefined){ value[k] = v; } else { delete value[k]; }; }; }; }; return reviver.call(holder, key, value); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * Mootools http://mootools.net Version 1.1.1 Copyright: 2007 Valerio Proietti License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #require(qx.lang.Array) #ignore(qx.core.Object) #ignore(qx.event.GlobalError) ************************************************************************ */ /** * Collection of helper methods operating on functions. */ qx.Bootstrap.define("qx.lang.Function", { statics : { /** * Extract the caller of a function from the arguments variable. * This will not work in Opera < 9.6. * * @param args {arguments} The local arguments variable * @return {Function} A reference to the calling function or "undefined" if caller is not supported. */ getCaller : function(args){ return args.caller ? args.caller.callee : args.callee.caller; }, /** * Try to get a sensible textual description of a function object. * This may be the class/mixin and method name of a function * or at least the signature of the function. * * @param fcn {Function} function the get the name for. * @return {String} Name of the function. */ getName : function(fcn){ if(fcn.displayName){ return fcn.displayName; }; if(fcn.$$original || fcn.wrapper || fcn.classname){ return fcn.classname + ".constructor()"; }; if(fcn.$$mixin){ //members for(var key in fcn.$$mixin.$$members){ if(fcn.$$mixin.$$members[key] == fcn){ return fcn.$$mixin.name + ".prototype." + key + "()"; }; }; // statics for(var key in fcn.$$mixin){ if(fcn.$$mixin[key] == fcn){ return fcn.$$mixin.name + "." + key + "()"; }; }; }; if(fcn.self){ var clazz = fcn.self.constructor; if(clazz){ // members for(var key in clazz.prototype){ if(clazz.prototype[key] == fcn){ return clazz.classname + ".prototype." + key + "()"; }; }; // statics for(var key in clazz){ if(clazz[key] == fcn){ return clazz.classname + "." + key + "()"; }; }; }; }; var fcnReResult = fcn.toString().match(/function\s*(\w*)\s*\(.*/); if(fcnReResult && fcnReResult.length >= 1 && fcnReResult[1]){ return fcnReResult[1] + "()"; }; return 'anonymous()'; }, /** * Evaluates JavaScript code globally * * @lint ignoreDeprecated(eval) * * @param data {String} JavaScript commands * @return {var} Result of the execution */ globalEval : function(data){ if(window.execScript){ return window.execScript(data); } else { return eval.call(window, data); }; }, /** * empty function * @deprecated {2.1} Please use a new empty function. */ empty : function(){ }, /** * Simply return true. * @deprecated {2.1} Please use a custom function. * @return {Boolean} Always returns true. */ returnTrue : function(){ return true; }, /** * Simply return false. * @deprecated {2.1} Please use a custom function. * @return {Boolean} Always returns false. */ returnFalse : function(){ return false; }, /** * Simply return null. * @deprecated {2.1} Please use a custom function. * @return {var} Always returns null. */ returnNull : function(){ return null; }, /** * Return "this". * @deprecated {2.1} Please use a custom function. * @return {Object} Always returns "this". */ returnThis : function(){ return this; }, /** * Simply return 0. * @deprecated {2.1} Please use a custom function. * @return {Number} Always returns 0. */ returnZero : function(){ return 0; }, /** * Base function for creating functional closures which is used by most other methods here. * * *Syntax* * * <pre class='javascript'>var createdFunction = qx.lang.Function.create(myFunction, [options]);</pre> * * @param func {Function} Original function to wrap * @param options {Map?} Map of options * <ul> * <li><strong>self</strong>: The object that the "this" of the function will refer to. Default is the same as the wrapper function is called.</li> * <li><strong>args</strong>: An array of arguments that will be passed as arguments to the function when called. * Default is no custom arguments; the function will receive the standard arguments when called.</li> * <li><strong>delay</strong>: If set, the returned function will delay the actual execution by this amount of milliseconds and return a timer handle when called. * Default is no delay.</li> * <li><strong>periodical</strong>: If set the returned function will periodically perform the actual execution with this specified interval * and return a timer handle when called. Default is no periodical execution.</li> * <li><strong>attempt</strong>: If set to true, the returned function will try to execute and return either the results or false on error. Default is false.</li> * </ul> * * @return {Function} Wrapped function */ create : function(func, options){ { }; // Nothing to be done when there are no options. if(!options){ return func; }; // Check for at least one attribute. if(!(options.self || options.args || options.delay != null || options.periodical != null || options.attempt)){ return func; }; return function(event){ { }; // Convert (and copy) incoming arguments var args = qx.lang.Array.fromArguments(arguments); // Prepend static arguments if(options.args){ args = options.args.concat(args); }; if(options.delay || options.periodical){ var returns = function(){ return func.apply(options.self || this, args); }; if(qx.core.Environment.get("qx.globalErrorHandling")){ returns = qx.event.GlobalError.observeMethod(returns); }; if(options.delay){ return window.setTimeout(returns, options.delay); }; if(options.periodical){ return window.setInterval(returns, options.periodical); }; } else if(options.attempt){ var ret = false; try{ ret = func.apply(options.self || this, args); } catch(ex) { }; return ret; } else { return func.apply(options.self || this, args); }; }; }, /** * Returns a function whose "this" is altered. * * * *Native way* * * This is also a feature of JavaScript 1.8.5 and will be supplied * by modern browsers. Including {@link qx.lang.normalize.Function} * will supply a cross browser normalization of the native * implementation. We like to encourage you to use the native function! * * * *Syntax* * * <pre class='javascript'>qx.lang.Function.bind(myFunction, [self, [varargs...]]);</pre> * * *Example* * * <pre class='javascript'> * function myFunction() * { * this.setStyle('color', 'red'); * // note that 'this' here refers to myFunction, not an element * // we'll need to bind this function to the element we want to alter * }; * * var myBoundFunction = qx.lang.Function.bind(myFunction, myElement); * myBoundFunction(); // this will make the element myElement red. * </pre> * * If you find yourself using this static method a lot, you may be * interested in the bindTo() method in the mixin qx.core.MBindTo. * * @see qx.core.MBindTo * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Function} The bound function. */ bind : function(func, self, varargs){ return this.create(func, { self : self, args : arguments.length > 2 ? qx.lang.Array.fromArguments(arguments, 2) : null }); }, /** * Returns a function whose arguments are pre-configured. * * *Syntax* * * <pre class='javascript'>qx.lang.Function.curry(myFunction, [varargs...]);</pre> * * *Example* * * <pre class='javascript'> * function myFunction(elem) { * elem.setStyle('color', 'red'); * }; * * var myBoundFunction = qx.lang.Function.curry(myFunction, myElement); * myBoundFunction(); // this will make the element myElement red. * </pre> * * @param func {Function} Original function to wrap * @param varargs {arguments} The arguments to pass to the function. * @return {var} The pre-configured function. */ curry : function(func, varargs){ return this.create(func, { args : arguments.length > 1 ? qx.lang.Array.fromArguments(arguments, 1) : null }); }, /** * Returns a function which could be used as a listener for a native event callback. * * *Syntax* * * <pre class='javascript'>qx.lang.Function.listener(myFunction, [self, [varargs...]]);</pre> * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {var} The bound function. */ listener : function(func, self, varargs){ if(arguments.length < 3){ return function(event){ // Directly execute, but force first parameter to be the event object. return func.call(self || this, event || window.event); }; } else { var optargs = qx.lang.Array.fromArguments(arguments, 2); return function(event){ var args = [event || window.event]; // Append static arguments args.push.apply(args, optargs); // Finally execute original method func.apply(self || this, args); }; }; }, /** * Tries to execute the function. * * *Syntax* * * <pre class='javascript'>var result = qx.lang.Function.attempt(myFunction, [self, [varargs...]]);</pre> * * *Example* * * <pre class='javascript'> * var myObject = { * 'cow': 'moo!' * }; * * var myFunction = function() * { * for(var i = 0; i < arguments.length; i++) { * if(!this[arguments[i]]) throw('doh!'); * } * }; * * var result = qx.lang.Function.attempt(myFunction, myObject, 'pig', 'cow'); // false * </pre> * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Boolean|var} <code>false</code> if an exception is thrown, else the function's return. */ attempt : function(func, self, varargs){ return this.create(func, { self : self, attempt : true, args : arguments.length > 2 ? qx.lang.Array.fromArguments(arguments, 2) : null })(); }, /** * Delays the execution of a function by a specified duration. * * *Syntax* * * <pre class='javascript'>var timeoutID = qx.lang.Function.delay(myFunction, [delay, [self, [varargs...]]]);</pre> * * *Example* * * <pre class='javascript'> * var myFunction = function(){ alert('moo! Element id is: ' + this.id); }; * //wait 50 milliseconds, then call myFunction and bind myElement to it * qx.lang.Function.delay(myFunction, 50, myElement); // alerts: 'moo! Element id is: ... ' * * // An anonymous function, example * qx.lang.Function.delay(function(){ alert('one second later...'); }, 1000); //wait a second and alert * </pre> * * @param func {Function} Original function to wrap * @param delay {Integer} The duration to wait (in milliseconds). * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Integer} The JavaScript Timeout ID (useful for clearing delays). */ delay : function(func, delay, self, varargs){ return this.create(func, { delay : delay, self : self, args : arguments.length > 3 ? qx.lang.Array.fromArguments(arguments, 3) : null })(); }, /** * Executes a function in the specified intervals of time * * *Syntax* * * <pre class='javascript'>var intervalID = qx.lang.Function.periodical(myFunction, [period, [self, [varargs...]]]);</pre> * * *Example* * * <pre class='javascript'> * var Site = { counter: 0 }; * var addCount = function(){ this.counter++; }; * qx.lang.Function.periodical(addCount, 1000, Site); // will add the number of seconds at the Site * </pre> * * @param func {Function} Original function to wrap * @param interval {Integer} The duration of the intervals between executions. * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Integer} The Interval ID (useful for clearing a periodical). */ periodical : function(func, interval, self, varargs){ return this.create(func, { periodical : interval, self : self, args : arguments.length > 3 ? qx.lang.Array.fromArguments(arguments, 3) : null })(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ________________________________________________________________________ This class contains code based on the following work: http://www.JSON.org/json2.js 2009-06-29 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html ************************************************************************ */ /** * JSON (JavaScript Object Notation) parser, serializer for qooxdoo * * This class implements EcmaScript 3.1 JSON support. * * http://wiki.ecmascript.org/doku.php?id=es3.1:json_support * * If the browser supports native JSON the browser implementation is used. */ qx.Bootstrap.define("qx.lang.Json", { statics : { /** * {JSON} The JSON object to use. If the browser has native JSON support * this member points to <code>window.JSON</code>. Otherwise it points to * the qooxdoo implementation {@link JsonImpl}. */ JSON : true ? window.JSON : new qx.lang.JsonImpl(), /** * This method produces a JSON text from a JavaScript value. * * When an object value is found, if the object contains a toJSON * method, its toJSON method will be called and the result will be * stringified. A toJSON method does not serialize: it returns the * value represented by the name/value pair that should be serialized, * or undefined if nothing should be serialized. The toJSON method * will be passed the key associated with the value, and this will be * bound to the object holding the key. * * For example, this would serialize Dates as ISO strings. * * <pre class="javascript"> * Date.prototype.toJSON = function (key) { * function f(n) { * // Format integers to have at least two digits. * return n < 10 ? '0' + n : n; * } * * return this.getUTCFullYear() + '-' + * f(this.getUTCMonth() + 1) + '-' + * f(this.getUTCDate()) + 'T' + * f(this.getUTCHours()) + ':' + * f(this.getUTCMinutes()) + ':' + * f(this.getUTCSeconds()) + 'Z'; * }; * </pre> * * You can provide an optional replacer method. It will be passed the * key and value of each member, with this bound to the containing * object. The value that is returned from your method will be * serialized. If your method returns undefined, then the member will * be excluded from the serialization. * * If the replacer parameter is an array of strings, then it will be * used to select the members to be serialized. It filters the results * such that only members with keys listed in the replacer array are * stringified. * * Values that do not have JSON representations, such as undefined or * functions, will not be serialized. Such values in objects will be * dropped; in arrays they will be replaced with null. You can use * a replacer function to replace those with JSON values. * JSON.stringify(undefined) returns undefined. * * The optional space parameter produces a stringification of the * value that is filled with line breaks and indentation to make it * easier to read. * * If the space parameter is a non-empty string, then that string will * be used for indentation. If the space parameter is a number, then * the indentation will be that many spaces. * * Example: * * <pre class="javascript"> * text = JSON.stringify(['e', {pluribus: 'unum'}]); * // text is '["e",{"pluribus":"unum"}]' * * * text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); * // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' * * text = JSON.stringify([new Date()], function (key, value) { * return this[key] instanceof Date ? * 'Date(' + this[key] + ')' : value; * }); * // text is '["Date(---current time---)"]' * </pre> * * @signature function(value, replacer, space) * * @param value {var} any JavaScript value, usually an object or array. * * @param replacer {Function?} an optional parameter that determines how * object values are stringified for objects. It can be a function or an * array of strings. * * @param space {String?} an optional parameter that specifies the * indentation of nested structures. If it is omitted, the text will * be packed without extra whitespace. If it is a number, it will specify * the number of spaces to indent at each level. If it is a string * (such as '\t' or '&nbsp;'), it contains the characters used to indent * at each level. * * @return {String} The JSON string of the value */ stringify : null, // will be set in the defer block /** * This method parses a JSON text to produce an object or array. * It can throw a SyntaxError exception. * * The optional reviver parameter is a function that can filter and * transform the results. It receives each of the keys and values, * and its return value is used instead of the original value. * If it returns what it received, then the structure is not modified. * If it returns undefined then the member is deleted. * * Example: * * <pre class="javascript"> * // Parse the text. Values that look like ISO date strings will * // be converted to Date objects. * * myData = JSON.parse(text, function (key, value) * { * if (typeof value === 'string') * { * var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); * if (a) { * return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); * } * } * return value; * }); * * myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { * var d; * if (typeof value === 'string' && * value.slice(0, 5) === 'Date(' && * value.slice(-1) === ')') { * d = new Date(value.slice(5, -1)); * if (d) { * return d; * } * } * return value; * }); * </pre> * * @signature function(text, reviver) * * @param text {String} JSON string to parse * * @param reviver {Function?} Optional reviver function to filter and * transform the results * * @return {Object} The parsed JSON object */ parse : null }, defer : function(statics){ statics.stringify = statics.JSON.stringify; statics.parse = statics.JSON.parse; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.storage.UserData#getLength) #require(qx.bom.storage.UserData#setItem) #require(qx.bom.storage.UserData#getItem) #require(qx.bom.storage.UserData#removeItem) #require(qx.bom.storage.UserData#clear) #require(qx.bom.storage.UserData#getKey) #require(qx.bom.storage.UserData#forEach) ************************************************************************ */ /** * Fallback storage implementation usable in IE browsers. It is recommended to use * these implementation only in IE < 8 because IE >= 8 supports * {@link qx.bom.storage.Web}. */ qx.Bootstrap.define("qx.bom.storage.UserData", { statics : { __local : null, __session : null, // global id used as key for the storage __id : 0, /** * Returns an instance of {@link qx.bom.storage.UserData} used to store * data persistent. * @return {qx.bom.storage.UserData} A storage instance. */ getLocal : function(){ if(this.__local){ return this.__local; }; return this.__local = new qx.bom.storage.UserData("local"); }, /** * Returns an instance of {@link qx.bom.storage.UserData} used to store * data persistent. * @return {qx.bom.storage.UserData} A storage instance. */ getSession : function(){ if(this.__session){ return this.__session; }; return this.__session = new qx.bom.storage.UserData("session"); } }, /** * Create a new instance. Usually, you should take the static * accessors to get your instance. * * @param storeName {String} type of storage. */ construct : function(storeName){ // create a dummy DOM element used for storage this.__el = document.createElement("div"); this.__el.style["display"] = "none"; document.getElementsByTagName("head")[0].appendChild(this.__el); this.__el.addBehavior("#default#userdata"); this.__storeName = storeName; // load the inital data which might be stored this.__el.load(this.__storeName); // set up the internal reference maps this.__storage = { }; this.__reference = { }; // initialize var value = this.__el.getAttribute("qx" + qx.bom.storage.UserData.__id); while(value != undefined){ value = qx.lang.Json.parse(value); // save the data in the internal storage this.__storage[value.key] = value.value; // save the reference this.__reference[value.key] = "qx" + qx.bom.storage.UserData.__id; qx.bom.storage.UserData.__id++; value = this.__el.getAttribute("qx" + qx.bom.storage.UserData.__id); }; }, members : { __el : null, __storeName : "qxtest", // storage which holds the key and the value __storage : null, // reference store which holds the key and the key used to store __reference : null, /** * Returns the map used to keep a in memory copy of the stored data. * @return {Map} The stored data. * @internal */ getStorage : function(){ return this.__storage; }, /** * Returns the amount of key-value pairs stored. * @return {Integer} The length of the storage. */ getLength : function(){ return Object.keys(this.__storage).length; }, /** * Store an item in the storage. * * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setItem : function(key, value){ // override case if(this.__reference[key]){ var storageKey = this.__reference[key]; } else { var storageKey = "qx" + qx.bom.storage.UserData.__id; qx.bom.storage.UserData.__id++; }; // build and save the data used to store both, key and value var storageValue = qx.lang.Json.stringify({ key : key, value : value }); this.__el.setAttribute(storageKey, storageValue); this.__el.save(this.__storeName); // also update the internal mappings this.__storage[key] = value; this.__reference[key] = storageKey; }, /** * Returns the stored item. * * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getItem : function(key){ return this.__storage[key] || null; }, /** * Removes an item form the storage. * @param key {String} The identifier. */ removeItem : function(key){ // check if the item is availabel var storageName = this.__reference[key]; if(storageName == undefined){ return; }; // remove the item this.__el.removeAttribute(storageName); // decrease the id because we removed one item qx.bom.storage.UserData.__id--; // update the internal maps delete this.__storage[key]; delete this.__reference[key]; // check if we have deleted the last item var lastStoreName = "qx" + qx.bom.storage.UserData.__id; if(this.__el.getAttribute(lastStoreName)){ // if not, move the last item to the deleted spot var lastItem = this.__el.getAttribute("qx" + qx.bom.storage.UserData.__id); this.__el.removeAttribute(lastStoreName); this.__el.setAttribute(storageName, lastItem); // update the reference map var lastKey = qx.lang.Json.parse(lastItem).key; this.__reference[lastKey] = storageName; }; this.__el.save(this.__storeName); }, /** * Deletes every stored item in the storage. */ clear : function(){ // delete all entries from the storage for(var key in this.__reference){ this.__el.removeAttribute(this.__reference[key]); }; this.__el.save(this.__storeName); // reset the internal maps this.__storage = { }; this.__reference = { }; }, /** * Returns the named key at the given index. * @param index {Integer} The index in the storage. * @return {String} The key stored at the given index. */ getKey : function(index){ return Object.keys(this.__storage)[index]; }, /** * Helper to access every stored item. * * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEach : function(callback, scope){ var length = this.getLength(); for(var i = 0;i < length;i++){ var key = this.getKey(i); callback.call(scope, key, this.getItem(key)); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.storage.Memory#getLength) #require(qx.bom.storage.Memory#setItem) #require(qx.bom.storage.Memory#getItem) #require(qx.bom.storage.Memory#removeItem) #require(qx.bom.storage.Memory#clear) #require(qx.bom.storage.Memory#getKey) #require(qx.bom.storage.Memory#forEach) ************************************************************************ */ /** * Fallback storage implementation which offers the same API as every other storage * but is not persistent. Basically, its just a storage API on a JavaScript map. */ qx.Bootstrap.define("qx.bom.storage.Memory", { statics : { __local : null, __session : null, /** * Returns an instance of {@link qx.bom.storage.Memory} which is of course * not persisted on reload. * @return {qx.bom.storage.Memory} A memory storage. */ getLocal : function(){ if(this.__local){ return this.__local; }; return this.__local = new qx.bom.storage.Memory(); }, /** * Returns an instance of {@link qx.bom.storage.Memory} which is of course * not persisted on reload. * @return {qx.bom.storage.Memory} A memory storage. */ getSession : function(){ if(this.__session){ return this.__session; }; return this.__session = new qx.bom.storage.Memory(); } }, construct : function(){ this.__storage = { }; }, members : { __storage : null, /** * Returns the internal used map. * @return {Map} The storage. * @internal */ getStorage : function(){ return this.__storage; }, /** * Returns the amount of key-value pairs stored. * @return {Integer} The length of the storage. */ getLength : function(){ return Object.keys(this.__storage).length; }, /** * Store an item in the storage. * * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setItem : function(key, value){ value = qx.lang.Json.stringify(value); this.__storage[key] = value; }, /** * Returns the stored item. * * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getItem : function(key){ var item = this.__storage[key]; if(qx.lang.Type.isString(item)){ item = qx.lang.Json.parse(item); }; return item; }, /** * Removes an item form the storage. * @param key {String} The identifier. */ removeItem : function(key){ delete this.__storage[key]; }, /** * Deletes every stored item in the storage. */ clear : function(){ this.__storage = { }; }, /** * Returns the named key at the given index. * @param index {Integer} The index in the storage. * @return {String} The key stored at the given index. */ getKey : function(index){ var keys = Object.keys(this.__storage); return keys[index]; }, /** * Helper to access every stored item. * * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEach : function(callback, scope){ var length = this.getLength(); for(var i = 0;i < length;i++){ var key = this.getKey(i); callback.call(scope, key, this.getItem(key)); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /** * CSS/Style property manipulation module */ qx.Bootstrap.define("qx.module.Css", { statics : { /** * Modifies the given style property on all elements in the collection. * * @attach {qxWeb} * @param name {String} Name of the style property to modify * @param value {var} The value to apply * @return {qxWeb} The collection for chaining */ setStyle : function(name, value){ if(/\w-\w/.test(name)){ name = qx.lang.String.camelCase(name); }; for(var i = 0;i < this.length;i++){ qx.bom.element.Style.set(this[i], name, value); }; return this; }, /** * Returns the value of the given style property for the first item in the * collection. * * @attach {qxWeb} * @param name {String} Style property name * @return {var} Style property value */ getStyle : function(name){ if(this[0]){ if(/\w-\w/.test(name)){ name = qx.lang.String.camelCase(name); }; return qx.bom.element.Style.get(this[0], name); }; return null; }, /** * Sets multiple style properties for each item in the collection. * * @attach {qxWeb} * @param styles {Map} A map of style property name/value pairs * @return {qxWeb} The collection for chaining */ setStyles : function(styles){ for(var name in styles){ this.setStyle(name, styles[name]); }; return this; }, /** * Returns the values of multiple style properties for each item in the * collection * * @attach {qxWeb} * @param names {String[]} List of style property names * @return {Map} Map of style property name/value pairs */ getStyles : function(names){ var styles = { }; for(var i = 0;i < names.length;i++){ styles[names[i]] = this.getStyle(names[i]); }; return styles; }, /** * Adds a class name to each element in the collection * * @attach {qxWeb} * @param name {String} Class name * @return {qxWeb} The collection for chaining */ addClass : function(name){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.add(this[i], name); }; return this; }, /** * Adds multiple class names to each element in the collection * * @attach {qxWeb} * @param names {String[]} List of class names to add * @return {qxWeb} The collection for chaining */ addClasses : function(names){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.addClasses(this[i], names); }; return this; }, /** * Removes a class name from each element in the collection * * @attach {qxWeb} * @param name {String} The class name to remove * @return {qxWeb} The collection for chaining */ removeClass : function(name){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.remove(this[i], name); }; return this; }, /** * Removes multiple class names from each element in the collection * * @attach {qxWeb} * @param names {String[]} List of class names to remove * @return {qxWeb} The collection for chaining */ removeClasses : function(names){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.removeClasses(this[i], names); }; return this; }, /** * Checks if the first element in the collection has the given class name * * @attach {qxWeb} * @param name {String} Class name to check for * @return {Boolean} <code>true</code> if the first item has the given class name */ hasClass : function(name){ if(!this[0]){ return false; }; return qx.bom.element.Class.has(this[0], name); }, /** * Returns the class name of the first element in the collection * * @attach {qxWeb} * @return {String} Class name */ getClass : function(){ if(!this[0]){ return ""; }; return qx.bom.element.Class.get(this[0]); }, /** * Toggles the given class name on each item in the collection * * @attach {qxWeb} * @param name {String} Class name * @return {qxWeb} The collection for chaining */ toggleClass : function(name){ var bCls = qx.bom.element.Class; for(var i = 0,l = this.length;i < l;i++){ bCls.has(this[i], name) ? bCls.remove(this[i], name) : bCls.add(this[i], name); }; return this; }, /** * Toggles the given list of class names on each item in the collection * * @attach {qxWeb} * @param names {String[]} Class names * @return {qxWeb} The collection for chaining */ toggleClasses : function(names){ for(var i = 0,l = names.length;i < l;i++){ this.toggleClass(names[i]); }; return this; }, /** * Replaces a class name on each element in the collection * * @attach {qxWeb} * @param oldName {String} Class name to remove * @param newName {String} Class name to add * @return {qxWeb} The collection for chaining */ replaceClass : function(oldName, newName){ for(var i = 0,l = this.length;i < l;i++){ qx.bom.element.Class.replace(this[i], oldName, newName); }; return this; }, /** * Returns the rendered height of the first element in the collection. * @attach {qxWeb} * @return {Number} The first item's rendered height */ getHeight : function(){ var elem = this[0]; if(elem){ if(qx.dom.Node.isElement(elem)){ return qx.bom.element.Dimension.getHeight(elem); } else if(qx.dom.Node.isDocument(elem)){ return qx.bom.Document.getHeight(qx.dom.Node.getWindow(elem)); } else if(qx.dom.Node.isWindow(elem)){ return qx.bom.Viewport.getHeight(elem); };; }; return null; }, /** * Returns the rendered width of the first element in the collection * @attach {qxWeb} * @return {Number} The first item's rendered width */ getWidth : function(){ var elem = this[0]; if(elem){ if(qx.dom.Node.isElement(elem)){ return qx.bom.element.Dimension.getWidth(elem); } else if(qx.dom.Node.isDocument(elem)){ return qx.bom.Document.getWidth(qx.dom.Node.getWindow(elem)); } else if(qx.dom.Node.isWindow(elem)){ return qx.bom.Viewport.getWidth(elem); };; }; return null; }, /** * Returns the computed location of the given element in the context of the * document dimensions. * * @attach {qxWeb} * @return {Map} A map with the keys <code>left<code/>, <code>top<code/>, * <code>right<code/> and <code>bottom<code/> which contains the distance * of the element relative to the document. */ getOffset : function(){ var elem = this[0]; if(elem){ return qx.bom.element.Location.get(elem); }; return null; }, /** * Returns the content height of the first element in the collection. * This is the maximum height the element can use, excluding borders, * margins, padding or scroll bars. * @attach {qxWeb} * @return {Number} Computed content height */ getContentHeight : function(){ var obj = this[0]; if(qx.dom.Node.isElement(obj)){ return qx.bom.element.Dimension.getContentHeight(obj); }; return null; }, /** * Returns the content width of the first element in the collection. * This is the maximum width the element can use, excluding borders, * margins, padding or scroll bars. * @attach {qxWeb} * @return {Number} Computed content width */ getContentWidth : function(){ var obj = this[0]; if(qx.dom.Node.isElement(obj)){ return qx.bom.element.Dimension.getContentWidth(obj); }; return null; }, /** * Returns the distance between the first element in the collection and its * offset parent * * @attach {qxWeb} * @return {Map} a map with the keys <code>left</code> and <code>top</code> * containing the distance between the elements */ getPosition : function(){ var obj = this[0]; if(qx.dom.Node.isElement(obj)){ return qx.bom.element.Location.getPosition(obj); }; return null; }, /** * Includes a Stylesheet file * * @attachStatic {qxWeb} * @param uri {String} The stylesheet's URI * @param doc {Document?} Document to modify */ includeStylesheet : function(uri, doc){ qx.bom.Stylesheet.includeFile(uri, doc); }, /** * Hides all elements in the collection by setting their "display" * style to "none". The previous value is stored so it can be re-applied * when {@link #show} is called. * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ hide : function(){ for(var i = 0,l = this.length;i < l;i++){ var item = this.slice(i, i + 1); var prevStyle = item.getStyle("display"); if(prevStyle !== "none"){ item[0].$$qPrevDisp = prevStyle; item.setStyle("display", "none"); }; }; return this; }, /** * Shows any elements with "display: none" in the collection. If an element * was hidden by using the {@link #hide} method, its previous * "display" style value will be re-applied. Otherwise, the * default "display" value for the element type will be applied. * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ show : function(){ for(var i = 0,l = this.length;i < l;i++){ var item = this.slice(i, i + 1); var currentVal = item.getStyle("display"); var prevVal = item[0].$$qPrevDisp; var newVal; if(currentVal == "none"){ if(prevVal && prevVal != "none"){ newVal = prevVal; } else { var doc = qxWeb.getDocument(item[0]); newVal = qx.module.Css.__getDisplayDefault(item[0].tagName, doc); }; item.setStyle("display", newVal); item[0].$$qPrevDisp = "none"; }; }; return this; }, /** * Maps HTML elements to their default "display" style values. */ __displayDefaults : { }, /** * Attempts tp determine the default "display" style value for * elements with the given tag name. * * @param tagName {String} Tag name * @param doc {Document?} Document element. Default: The current document * @return {String} The default "display" value, e.g. <code>inline</code> * or <code>block</code> */ __getDisplayDefault : function(tagName, doc){ var defaults = qx.module.Css.__displayDefaults; if(!defaults[tagName]){ var docu = doc || document; var tempEl = qxWeb(docu.createElement(tagName)).appendTo(doc.body); defaults[tagName] = tempEl.getStyle("display"); tempEl.remove(); }; return defaults[tagName] || ""; } }, defer : function(statics){ qxWeb.$attach({ "setStyle" : statics.setStyle, "getStyle" : statics.getStyle, "setStyles" : statics.setStyles, "getStyles" : statics.getStyles, "addClass" : statics.addClass, "addClasses" : statics.addClasses, "removeClass" : statics.removeClass, "removeClasses" : statics.removeClasses, "hasClass" : statics.hasClass, "getClass" : statics.getClass, "toggleClass" : statics.toggleClass, "toggleClasses" : statics.toggleClasses, "replaceClass" : statics.replaceClass, "getHeight" : statics.getHeight, "getWidth" : statics.getWidth, "getOffset" : statics.getOffset, "getContentHeight" : statics.getContentHeight, "getContentWidth" : statics.getContentWidth, "getPosition" : statics.getPosition, "hide" : statics.hide, "show" : statics.show }); qxWeb.$attachStatic({ "includeStylesheet" : statics.includeStylesheet }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'String' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *trim*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/Trim">MDN documentation</a> | * <a href="http://es5.github.com/#x15.5.4.20">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.String", { defer : function(){ // trim if(!qx.core.Environment.get("ecmascript.string.trim")){ String.prototype.trim = function(context){ return this.replace(/^\s+|\s+$/g, ''); }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * Mootools http://mootools.net/ Version 1.1.1 Copyright: (c) 2007 Valerio Proietti License: MIT: http://www.opensource.org/licenses/mit-license.php and * XRegExp http://xregexp.com/ Version 1.5 Copyright: (c) 2006-2007, Steven Levithan <http://stevenlevithan.com> License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Steven Levithan ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.String) ************************************************************************ */ /** * String helper functions * * The native JavaScript String is not modified by this class. However, * there are modifications to the native String in {@link qx.lang.normalize.String} for * browsers that do not support certain features. */ qx.Bootstrap.define("qx.lang.String", { statics : { /** * Unicode letters. they are taken from Steve Levithan's excellent XRegExp library [http://xregexp.com/addons/unicode/unicode-base.js] */ __unicodeLetters : "0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC", /** * A RegExp that matches the first letter in a word - unicode aware */ __unicodeFirstLetterInWordRegexp : null, /** * {Map} Cache for often used string operations [camelCasing and hyphenation] * e.g. marginTop => margin-top */ __stringsMap : { }, /** * Converts a hyphenated string (separated by '-') to camel case. * * Example: * <pre class='javascript'>qx.lang.String.camelCase("I-like-cookies"); //returns "ILikeCookies"</pre> * * @param str {String} hyphenated string * @return {String} camelcase string */ camelCase : function(str){ var result = this.__stringsMap[str]; if(!result){ result = str.replace(/\-([a-z])/g, function(match, chr){ return chr.toUpperCase(); }); if(str.indexOf("-") >= 0){ this.__stringsMap[str] = result; }; }; return result; }, /** * Converts a camelcased string to a hyphenated (separated by '-') string. * * Example: * <pre class='javascript'>qx.lang.String.hyphenate("weLikeCookies"); //returns "we-like-cookies"</pre> * * @param str {String} camelcased string * @return {String} hyphenated string */ hyphenate : function(str){ var result = this.__stringsMap[str]; if(!result){ result = str.replace(/[A-Z]/g, function(match){ return ('-' + match.charAt(0).toLowerCase()); }); if(str.indexOf("-") == -1){ this.__stringsMap[str] = result; }; }; return result; }, /** * Converts a string to camel case. * * Example: * <pre class='javascript'>qx.lang.String.camelCase("i like cookies"); //returns "I Like Cookies"</pre> * * @param str {String} any string * @return {String} capitalized string */ capitalize : function(str){ if(this.__unicodeFirstLetterInWordRegexp === null){ var unicodeEscapePrefix = '\\u'; this.__unicodeFirstLetterInWordRegexp = new RegExp("(^|[^" + this.__unicodeLetters.replace(/[0-9A-F]{4}/g, function(match){ return unicodeEscapePrefix + match; }) + "])[" + this.__unicodeLetters.replace(/[0-9A-F]{4}/g, function(match){ return unicodeEscapePrefix + match; }) + "]", "g"); }; return str.replace(this.__unicodeFirstLetterInWordRegexp, function(match){ return match.toUpperCase(); }); }, /** * Removes all extraneous whitespace from a string and trims it * * Example: * * <code> * qx.lang.String.clean(" i like cookies \n\n"); * </code> * * Returns "i like cookies" * * @param str {String} the string to clean up * @return {String} Cleaned up string */ clean : function(str){ return str.replace(/\s+/g, ' ').trim(); }, /** * removes white space from the left side of a string * * @param str {String} the string to trim * @return {String} the trimmed string */ trimLeft : function(str){ return str.replace(/^\s+/, ""); }, /** * removes white space from the right side of a string * * @param str {String} the string to trim * @return {String} the trimmed string */ trimRight : function(str){ return str.replace(/\s+$/, ""); }, /** * removes white space from the left and the right side of a string * * @deprecated {2.1} please use the native trim method. * @param str {String} the string to trim * @return {String} the trimmed string */ trim : function(str){ { }; return str.replace(/^\s+|\s+$/g, ""); }, /** * Check whether the string starts with the given substring * * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string starts with the given substring */ startsWith : function(fullstr, substr){ return fullstr.indexOf(substr) === 0; }, /** * Check whether the string ends with the given substring * * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string ends with the given substring */ endsWith : function(fullstr, substr){ return fullstr.substring(fullstr.length - substr.length, fullstr.length) === substr; }, /** * Returns a string, which repeats a string 'length' times * * @param str {String} string used to repeat * @param times {Integer} the number of repetitions * @return {String} repeated string */ repeat : function(str, times){ return str.length > 0 ? new Array(times + 1).join(str) : ""; }, /** * Pad a string up to a given length. Padding characters are added to the left of the string. * * @param str {String} the string to pad * @param length {Integer} the final length of the string * @param ch {String} character used to fill up the string * @return {String} padded string */ pad : function(str, length, ch){ var padLength = length - str.length; if(padLength > 0){ if(typeof ch === "undefined"){ ch = "0"; }; return this.repeat(ch, padLength) + str; } else { return str; }; }, /** * Convert the first character of the string to upper case. * * @signature function(str) * @param str {String} the string * @return {String} the string with an upper case first character */ firstUp : qx.Bootstrap.firstUp, /** * Convert the first character of the string to lower case. * * @signature function(str) * @param str {String} the string * @return {String} the string with a lower case first character */ firstLow : qx.Bootstrap.firstLow, /** * Check whether the string contains a given substring * * @param str {String} the string * @param substring {String} substring to search for * @return {Boolean} whether the string contains the substring */ contains : function(str, substring){ return str.indexOf(substring) != -1; }, /** * Print a list of arguments using a format string * In the format string occurrences of %n are replaced by the n'th element of the args list. * Example: * <pre class='javascript'>qx.lang.String.format("Hello %1, my name is %2", ["Egon", "Franz"]) == "Hello Egon, my name is Franz"</pre> * * @param pattern {String} format string * @param args {Array} array of arguments to insert into the format string * @return {String} the formatted string */ format : function(pattern, args){ var str = pattern; var i = args.length; while(i--){ // be sure to always use a string for replacement. str = str.replace(new RegExp("%" + (i + 1), "g"), args[i] + ""); }; return str; }, /** * Escapes all chars that have a special meaning in regular expressions * * @param str {String} the string where to escape the chars. * @return {String} the string with the escaped chars. */ escapeRegexpChars : function(str){ return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }, /** * Converts a string to an array of characters. * <pre>"hello" => [ "h", "e", "l", "l", "o" ];</pre> * * @param str {String} the string which should be split * @return {Array} the result array of characters */ toArray : function(str){ return str.split(/\B|\b/g); }, /** * Remove HTML/XML tags from a string * Example: * <pre class='javascript'>qx.lang.String.stripTags("&lt;h1>Hello&lt;/h1>") == "Hello"</pre> * * @param str {String} string containing tags * @return {String} the string with stripped tags */ stripTags : function(str){ return str.replace(/<\/?[^>]+>/gi, ""); }, /** * Strips <script> tags including its content from the given string. * * @param str {String} string containing tags * @param exec {Boolean?false} Whether the filtered code should be executed * @return {String} The filtered string */ stripScripts : function(str, exec){ var scripts = ""; var text = str.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){ scripts += arguments[1] + '\n'; return ""; }); if(exec === true){ qx.lang.Function.globalEval(scripts); }; return text; }, /** * Quotes the given string. * @param str {String} String to quote. * @return {String} The quoted string. */ quote : function(str){ return '"' + str.replace(/\\/g, "\\\\").replace(/\"/g, "\\\"") + '"'; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /* ************************************************************************ #ignore(WebKitCSSMatrix) ************************************************************************ */ /** * The purpose of this class is to contain all checks about css. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Css", { statics : { __WEBKIT_LEGACY_GRADIENT : null, /** * Checks what box model is used in the current environemnt. * @return {String} It either returns "content" or "border". * @internal */ getBoxModel : function(){ var content = qx.bom.client.Engine.getName() !== "mshtml" || !qx.bom.client.Browser.getQuirksMode(); return content ? "content" : "border"; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>textOverflow</code> style property. * * @return {String|null} textOverflow property name or <code>null</code> if * textOverflow is not supported. * @internal */ getTextOverflow : function(){ return qx.bom.Style.getPropertyName("textOverflow"); }, /** * Checks if a placeholder could be used. * @return {Boolean} <code>true</code>, if it could be used. * @internal */ getPlaceholder : function(){ var i = document.createElement("input"); return "placeholder" in i; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>appearance</code> style property. * * @return {String|null} appearance property name or <code>null</code> if * appearance is not supported. * @internal */ getAppearance : function(){ return qx.bom.Style.getPropertyName("appearance"); }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>borderRadius</code> style property. * * @return {String|null} borderRadius property name or <code>null</code> if * borderRadius is not supported. * @internal */ getBorderRadius : function(){ return qx.bom.Style.getPropertyName("borderRadius"); }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>boxShadow</code> style property. * * @return {String|null} boxShadow property name or <code>null</code> if * boxShadow is not supported. * @internal */ getBoxShadow : function(){ return qx.bom.Style.getPropertyName("boxShadow"); }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>borderImage</code> style property. * * @return {String|null} borderImage property name or <code>null</code> if * borderImage is not supported. * @internal */ getBorderImage : function(){ return qx.bom.Style.getPropertyName("borderImage"); }, /** * Returns the type of syntax this client supports for its CSS border-image * implementation. Some browsers do not support the "fill" keyword defined * in the W3C draft (http://www.w3.org/TR/css3-background/) and will not * show the border image if it's set. Others follow the standard closely and * will omit the center image if "fill" is not set. * * @return {Boolean|null} <code>true</code> if the standard syntax is supported. * <code>null</code> if the supported syntax could not be detected. * @internal */ getBorderImageSyntax : function(){ var styleName = qx.bom.client.Css.getBorderImage(); if(!styleName){ return null; }; var el = document.createElement("div"); if(styleName === "borderImage"){ // unprefixed implementation: check individual properties el.style[styleName] = 'url("foo.png") 4 4 4 4 fill stretch'; if(el.style.borderImageSource.indexOf("foo.png") >= 0 && el.style.borderImageSlice.indexOf("4 fill") >= 0 && el.style.borderImageRepeat.indexOf("stretch") >= 0){ return true; }; } else { // prefixed implementation, assume no support for "fill" el.style[styleName] = 'url("foo.png") 4 4 4 4 stretch'; // serialized value is unreliable, so just a simple check if(el.style[styleName].indexOf("foo.png") >= 0){ return false; }; }; // unable to determine syntax return null; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>userSelect</code> style property. * * @return {String|null} userSelect property name or <code>null</code> if * userSelect is not supported. * @internal */ getUserSelect : function(){ return qx.bom.Style.getPropertyName("userSelect"); }, /** * Returns the (possibly vendor-prefixed) value for the * <code>userSelect</code> style property that disables selection. For Gecko, * "-moz-none" is returned since "none" only makes the target element appear * as if its text could not be selected * * @internal * @return {String|null} the userSelect property value that disables * selection or <code>null</code> if userSelect is not supported */ getUserSelectNone : function(){ var styleProperty = qx.bom.client.Css.getUserSelect(); if(styleProperty){ var el = document.createElement("span"); el.style[styleProperty] = "-moz-none"; return el.style[styleProperty] === "-moz-none" ? "-moz-none" : "none"; }; return null; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>userModify</code> style property. * * @return {String|null} userModify property name or <code>null</code> if * userModify is not supported. * @internal */ getUserModify : function(){ return qx.bom.Style.getPropertyName("userModify"); }, /** * Returns the vendor-specific name of the <code>float</code> style property * * @return {String|null} <code>cssFloat</code> for standards-compliant * browsers, <code>styleFloat</code> for legacy IEs, <code>null</code> if * the client supports neither property. * @internal */ getFloat : function(){ var style = document.documentElement.style; return style.cssFloat !== undefined ? "cssFloat" : style.styleFloat !== undefined ? "styleFloat" : null; }, /** * Checks if translate3d can be used. * @return {Boolean} <code>true</code>, if it could be used. * @internal * @lint ignoreUndefined(WebKitCSSMatrix) */ getTranslate3d : function(){ return 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix(); }, /** * Returns the (possibly vendor-prefixed) name this client uses for * <code>linear-gradient</code>. * http://dev.w3.org/csswg/css3-images/#linear-gradients * * @return {String|null} Prefixed linear-gradient name or <code>null</code> * if linear gradients are not supported * @internal */ getLinearGradient : function(){ qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT = false; var value = "linear-gradient(0deg, #fff, #000)"; var el = document.createElement("div"); var style = qx.bom.Style.getAppliedStyle(el, "backgroundImage", value); if(!style){ //try old WebKit syntax (versions 528 - 534.16) value = "-webkit-gradient(linear,0% 0%,100% 100%,from(white), to(red))"; var style = qx.bom.Style.getAppliedStyle(el, "backgroundImage", value, false); if(style){ qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT = true; }; }; // not supported if(!style){ return null; }; var match = /(.*?)\(/.exec(style); return match ? match[1] : null; }, /** * Returns <code>true</code> if the browser supports setting gradients * using the filter style. This usually only applies for IE browsers * starting from IE5.5. * http://msdn.microsoft.com/en-us/library/ms532997(v=vs.85).aspx * * @return {Boolean} <code>true</code> if supported. * @internal */ getFilterGradient : function(){ return qx.bom.client.Css.__isFilterSupported("DXImageTransform.Microsoft.Gradient", "startColorStr=#550000FF, endColorStr=#55FFFF00"); }, /** * Returns the (possibly vendor-prefixed) name this client uses for * <code>radial-gradient</code>. * * @return {String|null} Prefixed radial-gradient name or <code>null</code> * if radial gradients are not supported * @internal */ getRadialGradient : function(){ var value = "radial-gradient(0px 0px, cover, red 50%, blue 100%)"; var el = document.createElement("div"); var style = qx.bom.Style.getAppliedStyle(el, "backgroundImage", value); if(!style){ return null; }; var match = /(.*?)\(/.exec(style); return match ? match[1] : null; }, /** * Checks if **only** the old WebKit (version < 534.16) syntax for * linear gradients is supported, e.g. * <code>linear-gradient(0deg, #fff, #000)</code> * * @return {Boolean} <code>true</code> if the legacy syntax must be used * @internal */ getLegacyWebkitGradient : function(){ if(qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT === null){ qx.bom.client.Css.getLinearGradient(); }; return qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT; }, /** * Checks if rgba colors can be used: * http://www.w3.org/TR/2010/PR-css3-color-20101028/#rgba-color * * @return {Boolean} <code>true</code>, if rgba colors are supported. * @internal */ getRgba : function(){ var el; try{ el = document.createElement("div"); } catch(ex) { el = document.createElement(); }; // try catch for IE try{ el.style["color"] = "rgba(1, 2, 3, 0.5)"; if(el.style["color"].indexOf("rgba") != -1){ return true; }; } catch(ex) { }; return false; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>boxSizing</code> style property. * * @return {String|null} boxSizing property name or <code>null</code> if * boxSizing is not supported. * @internal */ getBoxSizing : function(){ return qx.bom.Style.getPropertyName("boxSizing"); }, /** * Returns the browser-specific name used for the <code>display</code> style * property's <code>inline-block</code> value. * * @internal * @return {String|null} */ getInlineBlock : function(){ var el = document.createElement("span"); el.style.display = "inline-block"; if(el.style.display == "inline-block"){ return "inline-block"; }; el.style.display = "-moz-inline-box"; if(el.style.display !== "-moz-inline-box"){ return "-moz-inline-box"; }; return null; }, /** * Checks if CSS opacity is supported * * @internal * @return {Boolean} <code>true</code> if opacity is supported */ getOpacity : function(){ return (typeof document.documentElement.style.opacity == "string"); }, /** * Checks if the overflowX and overflowY style properties are supported * * @internal * @return {Boolean} <code>true</code> if overflow-x and overflow-y can be * used * @deprecated {2.1} */ getOverflowXY : function(){ return (typeof document.documentElement.style.overflowX == "string") && (typeof document.documentElement.style.overflowY == "string"); }, /** * Checks if CSS texShadow is supported * * @internal * @return {Boolean} <code>true</code> if textShadow is supported */ getTextShadow : function(){ return !!qx.bom.Style.getPropertyName("textShadow"); }, /** * Returns <code>true</code> if the browser supports setting text shadow * using the filter style. This usually only applies for IE browsers * starting from IE5.5. * * @internal * @return {Boolean} <code>true</code> if textShadow is supported */ getFilterTextShadow : function(){ return qx.bom.client.Css.__isFilterSupported("DXImageTransform.Microsoft.Shadow", "color=#666666,direction=45"); }, /** * Checks if the given filter is supported. * * @param filterClass {String} The name of the filter class * @param initParams {String} Init values for the filter * @return {Boolean} <code>true</code> if the given filter is supported */ __isFilterSupported : function(filterClass, initParams){ var supported = false; var value = "progid:" + filterClass + "(" + initParams + ");"; var el = document.createElement("div"); document.body.appendChild(el); el.style.filter = value; if(el.filters && el.filters.length > 0 && el.filters.item(filterClass).enabled == true){ supported = true; }; document.body.removeChild(el); return supported; } }, defer : function(statics){ qx.core.Environment.add("css.textoverflow", statics.getTextOverflow); qx.core.Environment.add("css.placeholder", statics.getPlaceholder); qx.core.Environment.add("css.borderradius", statics.getBorderRadius); qx.core.Environment.add("css.boxshadow", statics.getBoxShadow); qx.core.Environment.add("css.gradient.linear", statics.getLinearGradient); qx.core.Environment.add("css.gradient.filter", statics.getFilterGradient); qx.core.Environment.add("css.gradient.radial", statics.getRadialGradient); qx.core.Environment.add("css.gradient.legacywebkit", statics.getLegacyWebkitGradient); qx.core.Environment.add("css.boxmodel", statics.getBoxModel); qx.core.Environment.add("css.rgba", statics.getRgba); qx.core.Environment.add("css.borderimage", statics.getBorderImage); qx.core.Environment.add("css.borderimage.standardsyntax", statics.getBorderImageSyntax); qx.core.Environment.add("css.usermodify", statics.getUserModify); qx.core.Environment.add("css.userselect", statics.getUserSelect); qx.core.Environment.add("css.userselect.none", statics.getUserSelectNone); qx.core.Environment.add("css.appearance", statics.getAppearance); qx.core.Environment.add("css.float", statics.getFloat); qx.core.Environment.add("css.boxsizing", statics.getBoxSizing); qx.core.Environment.add("css.inlineblock", statics.getInlineBlock); qx.core.Environment.add("css.opacity", statics.getOpacity); qx.core.Environment.add("css.overflowxy", statics.getOverflowXY); qx.core.Environment.add("css.textShadow", statics.getTextShadow); qx.core.Environment.add("css.textShadow.filter", statics.getFilterTextShadow); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) * Sebastian Fastner (fastner) ************************************************************************ */ /** * This class is responsible for checking the operating systems name. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.OperatingSystem", { statics : { /** * Checks for the name of the operating system. * @return {String} The name of the operating system. * @internal */ getName : function(){ if(!navigator){ return ""; }; var input = navigator.platform || ""; var agent = navigator.userAgent || ""; if(input.indexOf("Windows") != -1 || input.indexOf("Win32") != -1 || input.indexOf("Win64") != -1){ return "win"; } else if(input.indexOf("Macintosh") != -1 || input.indexOf("MacPPC") != -1 || input.indexOf("MacIntel") != -1 || input.indexOf("Mac OS X") != -1){ return "osx"; } else if(agent.indexOf("RIM Tablet OS") != -1){ return "rim_tabletos"; } else if(agent.indexOf("webOS") != -1){ return "webos"; } else if(input.indexOf("iPod") != -1 || input.indexOf("iPhone") != -1 || input.indexOf("iPad") != -1){ return "ios"; } else if(agent.indexOf("Android") != -1){ return "android"; } else if(input.indexOf("Linux") != -1){ return "linux"; } else if(input.indexOf("X11") != -1 || input.indexOf("BSD") != -1 || input.indexOf("Darwin") != -1){ return "unix"; } else if(input.indexOf("SymbianOS") != -1){ return "symbian"; } else if(input.indexOf("BlackBerry") != -1){ return "blackberry"; };;;;;;;;; // don't know return ""; }, /** Maps user agent names to system IDs */ __ids : { // Windows "Windows NT 6.3" : "8.1", "Windows NT 6.2" : "8", "Windows NT 6.1" : "7", "Windows NT 6.0" : "vista", "Windows NT 5.2" : "2003", "Windows NT 5.1" : "xp", "Windows NT 5.0" : "2000", "Windows 2000" : "2000", "Windows NT 4.0" : "nt4", "Win 9x 4.90" : "me", "Windows CE" : "ce", "Windows 98" : "98", "Win98" : "98", "Windows 95" : "95", "Win95" : "95", // OS X "Mac OS X 10_9" : "10.9", "Mac OS X 10.9" : "10.9", "Mac OS X 10_8" : "10.8", "Mac OS X 10.8" : "10.8", "Mac OS X 10_7" : "10.7", "Mac OS X 10.7" : "10.7", "Mac OS X 10_6" : "10.6", "Mac OS X 10.6" : "10.6", "Mac OS X 10_5" : "10.5", "Mac OS X 10.5" : "10.5", "Mac OS X 10_4" : "10.4", "Mac OS X 10.4" : "10.4", "Mac OS X 10_3" : "10.3", "Mac OS X 10.3" : "10.3", "Mac OS X 10_2" : "10.2", "Mac OS X 10.2" : "10.2", "Mac OS X 10_1" : "10.1", "Mac OS X 10.1" : "10.1", "Mac OS X 10_0" : "10.0", "Mac OS X 10.0" : "10.0" }, /** * Checks for the version of the operating system using the internal map. * * @internal * @return {String} The version as strin or an empty string if the version * could not be detected. */ getVersion : function(){ var version = qx.bom.client.OperatingSystem.__getVersionForDesktopOs(navigator.userAgent); if(version == null){ version = qx.bom.client.OperatingSystem.__getVersionForMobileOs(navigator.userAgent); }; if(version != null){ return version; } else { return ""; }; }, /** * Detect OS version for desktop devices * @param userAgent {String} userAgent parameter, needed for detection. * @return {String} version number as string or null. */ __getVersionForDesktopOs : function(userAgent){ var str = []; for(var key in qx.bom.client.OperatingSystem.__ids){ str.push(key); }; var reg = new RegExp("(" + str.join("|").replace(/\./g, "\.") + ")", "g"); var match = reg.exec(userAgent); if(match && match[1]){ return qx.bom.client.OperatingSystem.__ids[match[1]]; }; return null; }, /** * Detect OS version for mobile devices * @param userAgent {String} userAgent parameter, needed for detection. * @return {String} version number as string or null. */ __getVersionForMobileOs : function(userAgent){ var android = userAgent.indexOf("Android") != -1; var iOs = userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false; if(android){ var androidVersionRegExp = new RegExp(/ Android (\d+(?:\.\d+)+)/i); var androidMatch = androidVersionRegExp.exec(userAgent); if(androidMatch && androidMatch[1]){ return androidMatch[1]; }; } else if(iOs){ var iOsVersionRegExp = new RegExp(/(CPU|iPhone|iPod) OS (\d+)_(\d+)\s+/); var iOsMatch = iOsVersionRegExp.exec(userAgent); if(iOsMatch && iOsMatch[2] && iOsMatch[3]){ return iOsMatch[2] + "." + iOsMatch[3]; }; }; return null; } }, defer : function(statics){ qx.core.Environment.add("os.name", statics.getName); qx.core.Environment.add("os.version", statics.getVersion); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) * Martin Wittemann (martinwittemann) ====================================================================== This class contains code from: Copyright: 2009 Deutsche Telekom AG, Germany, http://telekom.com License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code from: Copyright: 2011 Pocket Widget S.L., Spain, http://www.pocketwidget.com License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php Authors: * Javier Martinez Villacampa ************************************************************************ */ /** #require(qx.bom.client.OperatingSystem#getVersion) */ /** * Basic browser detection for qooxdoo. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Browser", { statics : { /** * Checks for the name of the browser and returns it. * @return {String} The name of the current browser. * @internal */ getName : function(){ var agent = navigator.userAgent; var reg = new RegExp("(" + qx.bom.client.Browser.__agents + ")(/| )([0-9]+\.[0-9])"); var match = agent.match(reg); if(!match){ return ""; }; var name = match[1].toLowerCase(); var engine = qx.bom.client.Engine.getName(); if(engine === "webkit"){ if(name === "android"){ // Fix Chrome name (for instance wrongly defined in user agent on Android 1.6) name = "mobile chrome"; } else if(agent.indexOf("Mobile Safari") !== -1 || agent.indexOf("Mobile/") !== -1){ // Fix Safari name name = "mobile safari"; }; } else if(engine === "mshtml"){ // IE 11's ua string no longer contains "MSIE" or even "IE" if(name === "msie" || name === "trident"){ name = "ie"; // Fix IE mobile before Microsoft added IEMobile string if(qx.bom.client.OperatingSystem.getVersion() === "ce"){ name = "iemobile"; }; }; } else if(engine === "opera"){ if(name === "opera mobi"){ name = "operamobile"; } else if(name === "opera mini"){ name = "operamini"; }; } else if(engine === "gecko"){ if(agent.indexOf("Maple") !== -1){ name = "maple"; }; };;; return name; }, /** * Determines the version of the current browser. * @return {String} The name of the current browser. * @internal */ getVersion : function(){ var agent = navigator.userAgent; var reg = new RegExp("(" + qx.bom.client.Browser.__agents + ")(/| )([0-9]+\.[0-9])"); var match = agent.match(reg); if(!match){ return ""; }; var name = match[1].toLowerCase(); var version = match[3]; // Support new style version string used by Opera and Safari if(agent.match(/Version(\/| )([0-9]+\.[0-9])/)){ version = RegExp.$2; }; if(qx.bom.client.Engine.getName() == "mshtml"){ // Use the Engine version, because IE8 and higher change the user agent // string to an older version in compatibility mode version = qx.bom.client.Engine.getVersion(); if(name === "msie" && qx.bom.client.OperatingSystem.getVersion() == "ce"){ // Fix IE mobile before Microsoft added IEMobile string version = "5.0"; }; }; if(qx.bom.client.Browser.getName() == "maple"){ // Fix version detection for Samsung Smart TVs Maple browser from 2010 and 2011 models reg = new RegExp("(Maple )([0-9]+\.[0-9]+\.[0-9]*)"); match = agent.match(reg); if(!match){ return ""; }; version = match[2]; }; return version; }, /** * Returns in which document mode the current document is (only for IE). * * @internal * @return {Number} The mode in which the browser is. */ getDocumentMode : function(){ if(document.documentMode){ return document.documentMode; }; return 0; }, /** * Check if in quirks mode. * * @internal * @return {Boolean} <code>true</code>, if the environment is in quirks mode */ getQuirksMode : function(){ if(qx.bom.client.Engine.getName() == "mshtml" && parseFloat(qx.bom.client.Engine.getVersion()) >= 8){ return qx.bom.client.Engine.DOCUMENT_MODE === 5; } else { return document.compatMode !== "CSS1Compat"; }; }, /** * Internal helper map for picking the right browser names to check. */ __agents : { // Safari should be the last one to check, because some other Webkit-based browsers // use this identifier together with their own one. // "Version" is used in Safari 4 to define the Safari version. After "Safari" they place the // Webkit version instead. Silly. // Palm Pre uses both Safari (contains Webkit version) and "Version" contains the "Pre" version. But // as "Version" is not Safari here, we better detect this as the Pre-Browser version. So place // "Pre" in front of both "Version" and "Safari". "webkit" : "AdobeAIR|Titanium|Fluid|Chrome|Android|Epiphany|Konqueror|iCab|OmniWeb|Maxthon|Pre|Mobile Safari|Safari", // Better security by keeping Firefox the last one to match "gecko" : "prism|Fennec|Camino|Kmeleon|Galeon|Netscape|SeaMonkey|Namoroka|Firefox", // No idea what other browsers based on IE's engine "mshtml" : "IEMobile|Maxthon|MSIE|Trident", // Keep "Opera" the last one to correctly prefer/match the mobile clients "opera" : "Opera Mini|Opera Mobi|Opera" }[qx.bom.client.Engine.getName()] }, defer : function(statics){ qx.core.Environment.add("browser.name", statics.getName),qx.core.Environment.add("browser.version", statics.getVersion),qx.core.Environment.add("browser.documentmode", statics.getDocumentMode),qx.core.Environment.add("browser.quirksmode", statics.getQuirksMode); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /** * Responsible class for everything concerning styles without the need of * an element. * * If you want to query or modify styles of HTML elements, * take a look at {@link qx.bom.element.Style}. */ qx.Bootstrap.define("qx.bom.Style", { statics : { /** Vendor-specific style property prefixes */ VENDOR_PREFIXES : ["Webkit", "Moz", "O", "ms", "Khtml"], /** * Internal lookup table to map property names to CSS names * @internal */ __cssName : { }, /** * Takes the name of a style property and returns the name the browser uses * for its implementation, which might include a vendor prefix. * * @param propertyName {String} Style property name to check * @return {String|null} The supported property name or <code>null</code> if * not supported */ getPropertyName : function(propertyName){ var style = document.documentElement.style; if(style[propertyName] !== undefined){ return propertyName; }; for(var i = 0,l = this.VENDOR_PREFIXES.length;i < l;i++){ var prefixedProp = this.VENDOR_PREFIXES[i] + qx.lang.String.firstUp(propertyName); if(style[prefixedProp] !== undefined){ return prefixedProp; }; }; return null; }, /** * Takes the name of a JavaScript style property and returns the * corresponding CSS name. * * The name of the style property is taken as is, i.e. it gets not * extended by vendor prefixes. The conversion into the CSS name is * done by string manipulation, not involving the DOM. * * Example: * <pre class='javascript'>qx.bom.Style.getCssName("MozTransform"); //returns "-moz-transform"</pre> * * @param propertyName {String} JavaScript style property * @return {String} CSS property */ getCssName : function(propertyName){ var cssName = this.__cssName[propertyName]; if(!cssName){ // all vendor prefixes (except for "ms") start with an uppercase letter cssName = propertyName.replace(/[A-Z]/g, function(match){ return ('-' + match.charAt(0).toLowerCase()); }); // lowercase "ms" vendor prefix needs special handling if((/^ms/.test(cssName))){ cssName = "-" + cssName; }; this.__cssName[propertyName] = cssName; }; return cssName; }, /** * Detects CSS support by applying a style to a DOM element of the given type * and verifying the result. Also checks for vendor-prefixed variants of the * value, e.g. "linear-gradient" -> "-webkit-linear-gradient". Returns the * (possibly vendor-prefixed) value if successful or <code>null</code> if * the property and/or value are not supported. * * @param element {Element} element to be used for the detection * @param propertyName {String} the style property to be tested * @param value {String} style property value to be tested * @param prefixed {Boolean?} try to determine the appropriate vendor prefix * for the value. Default: <code>true</code> * @return {String|null} prefixed style value or <code>null</code> if not supported * @internal */ getAppliedStyle : function(element, propertyName, value, prefixed){ var vendorPrefixes = (prefixed !== false) ? [null].concat(this.VENDOR_PREFIXES) : [null]; for(var i = 0,l = vendorPrefixes.length;i < l;i++){ var prefixedVal = vendorPrefixes[i] ? "-" + vendorPrefixes[i].toLowerCase() + "-" + value : value; // IE might throw an exception try{ element.style[propertyName] = prefixedVal; if(typeof element.style[propertyName] == "string" && element.style[propertyName] !== ""){ return prefixedVal; }; } catch(ex) { }; }; return null; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Christian Hagendorn (chris_schmidt) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson 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 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. ************************************************************************ */ /** * Cross-browser opacity support. * * Optimized for animations (contains workarounds for typical flickering * in some browsers). Reduced class dependencies for optimal size and * performance. */ qx.Bootstrap.define("qx.bom.element.Opacity", { statics : { /** * {Boolean} <code>true</code> when the style attribute "opacity" is supported, * <code>false</code> otherwise. * @deprecated {2.1} Please use qx.core.Environment.get("css.opacity") instead. */ SUPPORT_CSS3_OPACITY : false, /** * Compiles the given opacity value into a cross-browser CSS string. * Accepts numbers between zero and one * where "0" means transparent, "1" means opaque. * * @signature function(opacity) * @param opacity {Float} A float number between 0 and 1 * @return {String} CSS compatible string */ compile : qx.core.Environment.select("engine.name", { "mshtml" : function(opacity){ if(opacity >= 1){ opacity = 1; }; if(opacity < 0.00001){ opacity = 0; }; if(qx.core.Environment.get("css.opacity")){ return "opacity:" + opacity + ";"; } else { return "zoom:1;filter:alpha(opacity=" + (opacity * 100) + ");"; }; }, "default" : function(opacity){ if(opacity >= 1){ return ""; }; return "opacity:" + opacity + ";"; } }), /** * Sets opacity of given element. Accepts numbers between zero and one * where "0" means transparent, "1" means opaque. * * @param element {Element} DOM element to modify * @param opacity {Float} A float number between 0 and 1 * @signature function(element, opacity) */ set : qx.core.Environment.select("engine.name", { "mshtml" : function(element, opacity){ if(qx.core.Environment.get("css.opacity")){ if(opacity >= 1){ opacity = ""; }; element.style.opacity = opacity; } else { // Read in computed filter var filter = qx.bom.element.Style.get(element, "filter", qx.bom.element.Style.COMPUTED_MODE, false); if(opacity >= 1){ opacity = 1; }; if(opacity < 0.00001){ opacity = 0; }; // IE has trouble with opacity if it does not have layout (hasLayout) // Force it by setting the zoom level if(!element.currentStyle || !element.currentStyle.hasLayout){ element.style.zoom = 1; }; // Remove old alpha filter and add new one element.style.filter = filter.replace(/alpha\([^\)]*\)/gi, "") + "alpha(opacity=" + opacity * 100 + ")"; }; }, "default" : function(element, opacity){ if(opacity >= 1){ opacity = ""; }; element.style.opacity = opacity; } }), /** * Resets opacity of given element. * * @param element {Element} DOM element to modify * @signature function(element) */ reset : qx.core.Environment.select("engine.name", { "mshtml" : function(element){ if(qx.core.Environment.get("css.opacity")){ element.style.opacity = ""; } else { // Read in computed filter var filter = qx.bom.element.Style.get(element, "filter", qx.bom.element.Style.COMPUTED_MODE, false); // Remove old alpha filter element.style.filter = filter.replace(/alpha\([^\)]*\)/gi, ""); }; }, "default" : function(element){ element.style.opacity = ""; } }), /** * Gets computed opacity of given element. Accepts numbers between zero and one * where "0" means transparent, "1" means opaque. * * @param element {Element} DOM element to modify * @param mode {Number} Choose one of the modes {@link qx.bom.element.Style#COMPUTED_MODE}, * {@link qx.bom.element.Style#CASCADED_MODE}, {@link qx.bom.element.Style#LOCAL_MODE}. * The computed mode is the default one. * @return {Float} A float number between 0 and 1 * @signature function(element, mode) */ get : qx.core.Environment.select("engine.name", { "mshtml" : function(element, mode){ if(qx.core.Environment.get("css.opacity")){ var opacity = qx.bom.element.Style.get(element, "opacity", mode, false); if(opacity != null){ return parseFloat(opacity); }; return 1.0; } else { var filter = qx.bom.element.Style.get(element, "filter", mode, false); if(filter){ var opacity = filter.match(/alpha\(opacity=(.*)\)/); if(opacity && opacity[1]){ return parseFloat(opacity[1]) / 100; }; }; return 1.0; }; }, "default" : function(element, mode){ var opacity = qx.bom.element.Style.get(element, "opacity", mode, false); if(opacity != null){ return parseFloat(opacity); }; return 1.0; } }) }, // @deprecated {2.1} defer : function(statics){ statics.SUPPORT_CSS3_OPACITY = qx.core.Environment.get("css.opacity"); } }); { }; /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.String) ************************************************************************ */ /** * Contains methods to control and query the element's clip property */ qx.Bootstrap.define("qx.bom.element.Clip", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Compiles the given clipping into a CSS compatible string. This * is a simple square which describes the visible area of an DOM element. * Changing the clipping does not change the dimensions of * an element. * * @param map {Map} Map which contains <code>left</code>, <code>top</code> * <code>width</code> and <code>height</code> of the clipped area. * @return {String} CSS compatible string */ compile : function(map){ if(!map){ return "clip:auto;"; }; var left = map.left; var top = map.top; var width = map.width; var height = map.height; var right,bottom; if(left == null){ right = (width == null ? "auto" : width + "px"); left = "auto"; } else { right = (width == null ? "auto" : left + width + "px"); left = left + "px"; }; if(top == null){ bottom = (height == null ? "auto" : height + "px"); top = "auto"; } else { bottom = (height == null ? "auto" : top + height + "px"); top = top + "px"; }; return "clip:rect(" + top + "," + right + "," + bottom + "," + left + ");"; }, /** * Gets the clipping of the given element. * * @param element {Element} DOM element to query * @param mode {Number} Choose one of the modes {@link qx.bom.element.Style#COMPUTED_MODE}, * {@link qx.bom.element.Style#CASCADED_MODE}, {@link qx.bom.element.Style#LOCAL_MODE}. * The computed mode is the default one. * @return {Map} Map which contains <code>left</code>, <code>top</code> * <code>width</code> and <code>height</code> of the clipped area. * Each one could be null or any integer value. */ get : function(element, mode){ var clip = qx.bom.element.Style.get(element, "clip", mode, false); var left,top,width,height; var right,bottom; if(typeof clip === "string" && clip !== "auto" && clip !== ""){ clip = clip.trim(); // Do not use "global" here. This will break Firefox because of // an issue that the lastIndex will not be resetted on separate calls. if(/\((.*)\)/.test(clip)){ var result = RegExp.$1; // Process result // Some browsers store values space-separated, others comma-separated. // Handle both cases by means of feature-detection. if(/,/.test(result)){ var split = result.split(","); } else { var split = result.split(" "); }; top = split[0].trim(); right = split[1].trim(); bottom = split[2].trim(); left = split[3].trim(); // Normalize "auto" to null if(left === "auto"){ left = null; }; if(top === "auto"){ top = null; }; if(right === "auto"){ right = null; }; if(bottom === "auto"){ bottom = null; }; // Convert to integer values if(top != null){ top = parseInt(top, 10); }; if(right != null){ right = parseInt(right, 10); }; if(bottom != null){ bottom = parseInt(bottom, 10); }; if(left != null){ left = parseInt(left, 10); }; // Compute width and height if(right != null && left != null){ width = right - left; } else if(right != null){ width = right; }; if(bottom != null && top != null){ height = bottom - top; } else if(bottom != null){ height = bottom; }; } else { throw new Error("Could not parse clip string: " + clip); }; }; // Return map when any value is available. return { left : left || null, top : top || null, width : width || null, height : height || null }; }, /** * Sets the clipping of the given element. This is a simple * square which describes the visible area of an DOM element. * Changing the clipping does not change the dimensions of * an element. * * @param element {Element} DOM element to modify * @param map {Map} A map with one or more of these available keys: * <code>left</code>, <code>top</code>, <code>width</code>, <code>height</code>. */ set : function(element, map){ if(!map){ element.style.clip = "rect(auto,auto,auto,auto)"; return; }; var left = map.left; var top = map.top; var width = map.width; var height = map.height; var right,bottom; if(left == null){ right = (width == null ? "auto" : width + "px"); left = "auto"; } else { right = (width == null ? "auto" : left + width + "px"); left = left + "px"; }; if(top == null){ bottom = (height == null ? "auto" : height + "px"); top = "auto"; } else { bottom = (height == null ? "auto" : top + height + "px"); top = top + "px"; }; element.style.clip = "rect(" + top + "," + right + "," + bottom + "," + left + ")"; }, /** * Resets the clipping of the given DOM element. * * @param element {Element} DOM element to modify */ reset : function(element){ element.style.clip = "rect(auto, auto, auto, auto)"; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Contains methods to control and query the element's cursor property */ qx.Bootstrap.define("qx.bom.element.Cursor", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** Internal helper structure to map cursor values to supported ones */ __map : { }, /** * Compiles the given cursor into a CSS compatible string. * * @param cursor {String} Valid CSS cursor name * @return {String} CSS string */ compile : function(cursor){ return "cursor:" + (this.__map[cursor] || cursor) + ";"; }, /** * Returns the computed cursor style for the given element. * * @param element {Element} The element to query * @param mode {Number} Choose one of the modes {@link qx.bom.element.Style#COMPUTED_MODE}, * {@link qx.bom.element.Style#CASCADED_MODE}, {@link qx.bom.element.Style#LOCAL_MODE}. * The computed mode is the default one. * @return {String} Computed cursor value of the given element. */ get : function(element, mode){ return qx.bom.element.Style.get(element, "cursor", mode, false); }, /** * Applies a new cursor style to the given element * * @param element {Element} The element to modify * @param value {String} New cursor value to set */ set : function(element, value){ element.style.cursor = this.__map[value] || value; }, /** * Removes the local cursor style applied to the element * * @param element {Element} The element to modify */ reset : function(element){ element.style.cursor = ""; } }, defer : function(statics){ // < IE 9 if(qx.core.Environment.get("engine.name") == "mshtml" && ((parseFloat(qx.core.Environment.get("engine.version")) < 9 || qx.core.Environment.get("browser.documentmode") < 9) && !qx.core.Environment.get("browser.quirksmode"))){ statics.__map["nesw-resize"] = "ne-resize"; statics.__map["nwse-resize"] = "nw-resize"; // < IE 8 if(((parseFloat(qx.core.Environment.get("engine.version")) < 8 || qx.core.Environment.get("browser.documentmode") < 8) && !qx.core.Environment.get("browser.quirksmode"))){ statics.__map["ew-resize"] = "e-resize"; statics.__map["ns-resize"] = "n-resize"; }; } else if(qx.core.Environment.get("engine.name") == "opera" && parseInt(qx.core.Environment.get("engine.version")) < 12){ statics.__map["nesw-resize"] = "ne-resize"; statics.__map["nwse-resize"] = "nw-resize"; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Object' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *keys*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys">MDN documentation</a> | * <a href="http://es5.github.com/#x15.2.3.14">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Object", { defer : function(){ // keys if(!qx.core.Environment.get("ecmascript.object.keys")){ Object.keys = qx.Bootstrap.keys; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.Object) ************************************************************************ */ /** * Helper functions to handle Object as a Hash map. */ qx.Bootstrap.define("qx.lang.Object", { statics : { /** * Clears the map from all values * * @param map {Object} the map to clear */ empty : function(map){ { }; for(var key in map){ if(map.hasOwnProperty(key)){ delete map[key]; }; }; }, /** * Check if the hash has any keys * * @signature function(map) * @param map {Object} the map to check * @return {Boolean} whether the map has any keys * @lint ignoreUnused(key) */ isEmpty : function(map){ { }; for(var key in map){ return false; }; return true; }, /** * Check whether the number of objects in the maps is at least "length" * * @signature function(map, minLength) * @param map {Object} the map to check * @param minLength {Integer} minimum number of objects in the map * @deprecated {2.1} Please use a check and 'qx.lang.Object.getLength'. * @return {Boolean} whether the map contains at least "length" objects. * @lint ignoreUnused(key) */ hasMinLength : function(map, minLength){ { }; if(minLength <= 0){ return true; }; var length = 0; for(var key in map){ if((++length) >= minLength){ return true; }; }; return false; }, /** * Get the number of objects in the map * * @signature function(map) * @param map {Object} the map * @return {Integer} number of objects in the map */ getLength : qx.Bootstrap.objectGetLength, /** * Get the keys of a map as array as returned by a "for ... in" statement. * * @deprecated {2.1.} Please use Object.keys instead. * @signature function(map) * @param map {Object} the map * @return {Array} array of the keys of the map */ getKeys : qx.Bootstrap.getKeys, /** * Get the keys of a map as string * * @signature function(map) * @param map {Object} the map * @deprecated {2.1} Object.keys(map).join(). * @return {String} String of the keys of the map * The keys are separated by ", " */ getKeysAsString : qx.Bootstrap.getKeysAsString, /** * Get the values of a map as array * * @param map {Object} the map * @return {Array} array of the values of the map */ getValues : function(map){ { }; var arr = []; var keys = Object.keys(map); for(var i = 0,l = keys.length;i < l;i++){ arr.push(map[keys[i]]); }; return arr; }, /** * Inserts all keys of the source object into the * target objects. Attention: The target map gets modified. * * @signature function(target, source, overwrite) * @param target {Object} target object * @param source {Object} object to be merged * @param overwrite {Boolean ? true} If enabled existing keys will be overwritten * @return {Object} Target with merged values from the source object */ mergeWith : qx.Bootstrap.objectMergeWith, /** * Inserts all key/value pairs of the source object into the * target object but doesn't override existing keys * * @param target {Object} target object * @param source {Object} object to be merged * @return {Object} target with merged values from source * @deprecated {2.1} please use mergeWith instead with override set to false */ carefullyMergeWith : function(target, source){ { }; return qx.lang.Object.mergeWith(target, source, false); }, /** * Merge a number of objects. * * @param target {Object} target object * @param varargs {Object} variable number of objects to merged with target * @return {Object} target with merged values from the other objects * @deprecated {2.1} Please use mergeWith instead. */ merge : function(target, varargs){ { }; var len = arguments.length; for(var i = 1;i < len;i++){ qx.lang.Object.mergeWith(target, arguments[i]); }; return target; }, /** * Return a copy of an Object * * @param source {Object} Object to copy * @param deep {Boolean} If the clone should be a deep clone. * @return {Object} A copy of the object */ clone : function(source, deep){ if(qx.lang.Type.isObject(source)){ var clone = { }; for(var key in source){ if(deep){ clone[key] = qx.lang.Object.clone(source[key], deep); } else { clone[key] = source[key]; }; }; return clone; } else if(qx.lang.Type.isArray(source)){ var clone = []; for(var i = 0;i < source.length;i++){ if(deep){ clone[i] = qx.lang.Object.clone(source[i]); } else { clone[i] = source[i]; }; }; return clone; }; return source; }, /** * Inverts a map by exchanging the keys with the values. * * If the map has the same values for different keys, information will get lost. * The values will be converted to strings using the toString methods. * * @param map {Object} Map to invert * @return {Object} inverted Map */ invert : function(map){ { }; var result = { }; for(var key in map){ result[map[key].toString()] = key; }; return result; }, /** * Get the key of the given value from a map. * If the map has more than one key matching the value, the first match is returned. * If the map does not contain the value, <code>null</code> is returned. * * @param map {Object} Map to search for the key * @param value {var} Value to look for * @return {String|null} Name of the key (null if not found). */ getKeyFromValue : function(map, value){ { }; for(var key in map){ if(map.hasOwnProperty(key) && map[key] === value){ return key; }; }; return null; }, /** * Whether the map contains the given value. * * @param map {Object} Map to search for the value * @param value {var} Value to look for * @return {Boolean} Whether the value was found in the map. */ contains : function(map, value){ { }; return this.getKeyFromValue(map, value) !== null; }, /** * Selects the value with the given key from the map. * * @param key {String} name of the key to get the value from * @param map {Object} map to get the value from * @return {var} value for the given key from the map * @deprecated {2.1} */ select : function(key, map){ { }; { }; return map[key]; }, /** * Convert an array into a map. * * All elements of the array become keys of the returned map by * calling <code>toString</code> on the array elements. The values of the * map are set to <code>true</code> * * @param array {Array} array to convert * @return {Map} the array converted to a map. */ fromArray : function(array){ { }; var obj = { }; for(var i = 0,l = array.length;i < l;i++){ { }; obj[array[i].toString()] = true; }; return obj; }, /** * Serializes an object to URI parameters (also known as query string). * * Escapes characters that have a special meaning in URIs as well as * umlauts. Uses the global function encodeURIComponent, see * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent * * Note: For URI parameters that are to be sent as * application/x-www-form-urlencoded (POST), spaces should be encoded * with "+". * * @param obj {Object} Object to serialize. * @param post {Boolean} Whether spaces should be encoded with "+". * @return {String} Serialized object. Safe to append to URIs or send as * URL encoded string. * @deprecated {2.1} Please use qx.util.Uri.toParameter instead. */ toUriParameter : function(obj, post){ { }; return qx.util.Uri.toParameter(obj, post); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /** * Static helpers for parsing and modifying URIs. */ qx.Bootstrap.define("qx.util.Uri", { statics : { /** * Split URL * * Code taken from: * parseUri 1.2.2 * (c) Steven Levithan <stevenlevithan.com> * MIT License * * * @param str {String} String to parse as URI * @param strict {Boolean} Whether to parse strictly by the rules * @return {Object} Map with parts of URI as properties */ parseUri : function(str, strict){ var options = { key : ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], q : { name : "queryKey", parser : /(?:^|&)([^&=]*)=?([^&]*)/g }, parser : { strict : /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose : /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ } }; var o = options,m = options.parser[strict ? "strict" : "loose"].exec(str),uri = { },i = 14; while(i--){ uri[o.key[i]] = m[i] || ""; }; uri[o.q.name] = { }; uri[o.key[12]].replace(o.q.parser, function($0, $1, $2){ if($1){ uri[o.q.name][$1] = $2; }; }); return uri; }, /** * Append string to query part of URL. Respects existing query. * * @param url {String} URL to append string to. * @param params {String} Parameters to append to URL. * @return {String} URL with string appended in query part. */ appendParamsToUrl : function(url, params){ if(params === undefined){ return url; }; { }; if(qx.lang.Type.isObject(params)){ params = qx.util.Uri.toParameter(params); }; if(!params){ return url; }; return url += (/\?/).test(url) ? "&" + params : "?" + params; }, /** * Serializes an object to URI parameters (also known as query string). * * Escapes characters that have a special meaning in URIs as well as * umlauts. Uses the global function encodeURIComponent, see * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent * * Note: For URI parameters that are to be sent as * application/x-www-form-urlencoded (POST), spaces should be encoded * with "+". * * @param obj {Object} Object to serialize. * @param post {Boolean} Whether spaces should be encoded with "+". * @return {String} Serialized object. Safe to append to URIs or send as * URL encoded string. */ toParameter : function(obj, post){ var key,parts = []; for(key in obj){ if(obj.hasOwnProperty(key)){ var value = obj[key]; if(value instanceof Array){ for(var i = 0;i < value.length;i++){ this.__toParameterPair(key, value[i], parts, post); }; } else { this.__toParameterPair(key, value, parts, post); }; }; }; return parts.join("&"); }, /** * Encodes key/value to URI safe string and pushes to given array. * * @param key {String} Key. * @param value {String} Value. * @param parts {Array} Array to push to. * @param post {Boolean} Whether spaces should be encoded with "+". */ __toParameterPair : function(key, value, parts, post){ var encode = window.encodeURIComponent; if(post){ parts.push(encode(key).replace(/%20/g, "+") + "=" + encode(value).replace(/%20/g, "+")); } else { parts.push(encode(key) + "=" + encode(value)); }; }, /** * Takes a relative URI and returns an absolute one. * * @param uri {String} relative URI * @return {String} absolute URI */ getAbsolute : function(uri){ var div = document.createElement("div"); div.innerHTML = '<a href="' + uri + '">0</a>'; return div.firstChild.href; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Contains methods to control and query the element's box-sizing property. * * Supported values: * * * "content-box" = W3C model (dimensions are content specific) * * "border-box" = Microsoft model (dimensions are box specific incl. border and padding) */ qx.Bootstrap.define("qx.bom.element.BoxSizing", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** {Map} Internal data structure for __usesNativeBorderBox() */ __nativeBorderBox : { tags : { button : true, select : true }, types : { search : true, button : true, submit : true, reset : true, checkbox : true, radio : true } }, /** * Whether the given elements defaults to the "border-box" Microsoft model in all cases. * * @param element {Element} DOM element to query * @return {Boolean} true when the element uses "border-box" independently from the doctype */ __usesNativeBorderBox : function(element){ var map = this.__nativeBorderBox; return map.tags[element.tagName.toLowerCase()] || map.types[element.type]; }, /** * Compiles the given box sizing into a CSS compatible string. * * @param value {String} Valid CSS box-sizing value * @return {String} CSS string */ compile : function(value){ if(qx.core.Environment.get("css.boxsizing")){ var prop = qx.bom.Style.getCssName(qx.core.Environment.get("css.boxsizing")); return prop + ":" + value + ";"; } else { { }; }; }, /** * Returns the box sizing for the given element. * * @param element {Element} The element to query * @return {String} Box sizing value of the given element. */ get : function(element){ if(qx.core.Environment.get("css.boxsizing")){ return qx.bom.element.Style.get(element, "boxSizing", null, false) || ""; }; if(qx.bom.Document.isStandardMode(qx.dom.Node.getWindow(element))){ if(!this.__usesNativeBorderBox(element)){ return "content-box"; }; }; return "border-box"; }, /** * Applies a new box sizing to the given element * * @param element {Element} The element to modify * @param value {String} New box sizing value to set */ set : function(element, value){ if(qx.core.Environment.get("css.boxsizing")){ // IE8 bombs when trying to apply an unsupported value try{ element.style[qx.core.Environment.get("css.boxsizing")] = value; } catch(ex) { { }; }; } else { { }; }; }, /** * Removes the local box sizing applied to the element * * @param element {Element} The element to modify */ reset : function(element){ this.set(element, ""); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson 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 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. ************************************************************************ */ /* ************************************************************************ #require(qx.lang.String) #require(qx.bom.client.Css) #require(qx.bom.element.Clip#set) #require(qx.bom.element.Cursor#set) #require(qx.bom.element.Opacity#set) #require(qx.bom.element.BoxSizing#set) #require(qx.bom.element.Clip#get) #require(qx.bom.element.Cursor#get) #require(qx.bom.element.Opacity#get) #require(qx.bom.element.BoxSizing#get) #require(qx.bom.element.Clip#reset) #require(qx.bom.element.Cursor#reset) #require(qx.bom.element.Opacity#reset) #require(qx.bom.element.BoxSizing#reset) #require(qx.bom.element.Clip#compile) #require(qx.bom.element.Cursor#compile) #require(qx.bom.element.Opacity#compile) #require(qx.bom.element.BoxSizing#compile) ************************************************************************ */ /** * Style querying and modification of HTML elements. * * Automatically normalizes cross-browser differences for setting and reading * CSS attributes. Optimized for performance. */ qx.Bootstrap.define("qx.bom.element.Style", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { __styleNames : null, __cssNames : null, /** * Detect vendor specific properties. */ __detectVendorProperties : function(){ var styleNames = { "appearance" : qx.core.Environment.get("css.appearance"), "userSelect" : qx.core.Environment.get("css.userselect"), "textOverflow" : qx.core.Environment.get("css.textoverflow"), "borderImage" : qx.core.Environment.get("css.borderimage"), "float" : qx.core.Environment.get("css.float"), "userModify" : qx.core.Environment.get("css.usermodify"), "boxSizing" : qx.core.Environment.get("css.boxsizing") }; this.__cssNames = { }; for(var key in qx.lang.Object.clone(styleNames)){ if(!styleNames[key]){ delete styleNames[key]; } else { this.__cssNames[key] = key == "float" ? "float" : qx.bom.Style.getCssName(styleNames[key]); }; }; this.__styleNames = styleNames; }, /** * Gets the (possibly vendor-prefixed) name of a style property and stores * it to avoid multiple checks. * * @param name {String} Style property name to check * @return {String|null} The client-specific name of the property, or * <code>null</code> if it's not supported. */ __getStyleName : function(name){ var styleName = qx.bom.Style.getPropertyName(name); if(styleName){ this.__styleNames[name] = styleName; }; return styleName; }, /** * Mshtml has proprietary pixel* properties for locations and dimensions * which return the pixel value. Used by getComputed() in mshtml variant. * * @internal */ __mshtmlPixel : { width : "pixelWidth", height : "pixelHeight", left : "pixelLeft", right : "pixelRight", top : "pixelTop", bottom : "pixelBottom" }, /** * Whether a special class is available for the processing of this style. * * @internal */ __special : { clip : qx.bom.element.Clip, cursor : qx.bom.element.Cursor, opacity : qx.bom.element.Opacity, boxSizing : qx.bom.element.BoxSizing }, /* --------------------------------------------------------------------------- COMPILE SUPPORT --------------------------------------------------------------------------- */ /** * Compiles the given styles into a string which can be used to * concat a HTML string for innerHTML usage. * * @param map {Map} Map of style properties to compile * @return {String} Compiled string of given style properties. */ compile : function(map){ var html = []; var special = this.__special; var cssNames = this.__cssNames; var name,value; for(name in map){ // read value value = map[name]; if(value == null){ continue; }; // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // process special properties if(special[name]){ html.push(special[name].compile(value)); } else { if(!cssNames[name]){ cssNames[name] = qx.bom.Style.getCssName(name); }; html.push(cssNames[name], ":", value, ";"); }; }; return html.join(""); }, /* --------------------------------------------------------------------------- CSS TEXT SUPPORT --------------------------------------------------------------------------- */ /** * Set the full CSS content of the style attribute * * @param element {Element} The DOM element to modify * @param value {String} The full CSS string */ setCss : function(element, value){ if(qx.core.Environment.get("engine.name") === "mshtml" && parseInt(qx.core.Environment.get("browser.documentmode"), 10) < 8){ element.style.cssText = value; } else { element.setAttribute("style", value); }; }, /** * Returns the full content of the style attribute. * * @param element {Element} The DOM element to query * @return {String} the full CSS string * @signature function(element) */ getCss : function(element){ if(qx.core.Environment.get("engine.name") === "mshtml" && parseInt(qx.core.Environment.get("browser.documentmode"), 10) < 8){ return element.style.cssText.toLowerCase(); } else { return element.getAttribute("style"); }; }, /* --------------------------------------------------------------------------- STYLE ATTRIBUTE SUPPORT --------------------------------------------------------------------------- */ /** * Checks whether the browser supports the given CSS property. * * @param propertyName {String} The name of the property * @return {Boolean} Whether the property id supported */ isPropertySupported : function(propertyName){ return (this.__special[propertyName] || this.__styleNames[propertyName] || propertyName in document.documentElement.style); }, /** {Integer} Computed value of a style property. Compared to the cascaded style, * this one also interprets the values e.g. translates <code>em</code> units to * <code>px</code>. */ COMPUTED_MODE : 1, /** {Integer} Cascaded value of a style property. */ CASCADED_MODE : 2, /** * {Integer} Local value of a style property. Ignores inheritance cascade. * Does not interpret values. */ LOCAL_MODE : 3, /** * Sets the value of a style property * * @param element {Element} The DOM element to modify * @param name {String} Name of the style attribute (js variant e.g. marginTop, wordSpacing) * @param value {var} The value for the given style * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties */ set : function(element, name, value, smart){ { }; // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling for specific properties // through this good working switch this part costs nothing when // processing non-smart properties if(smart !== false && this.__special[name]){ this.__special[name].set(element, value); } else { element.style[name] = value !== null ? value : ""; }; }, /** * Convenience method to modify a set of styles at once. * * @param element {Element} The DOM element to modify * @param styles {Map} a map where the key is the name of the property * and the value is the value to use. * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties */ setStyles : function(element, styles, smart){ { }; // inline calls to "set" and "reset" because this method is very // performance critical! var styleNames = this.__styleNames; var special = this.__special; var style = element.style; for(var key in styles){ var value = styles[key]; var name = styleNames[key] || this.__getStyleName(key) || key; if(value === undefined){ if(smart !== false && special[name]){ special[name].reset(element); } else { style[name] = ""; }; } else { if(smart !== false && special[name]){ special[name].set(element, value); } else { style[name] = value !== null ? value : ""; }; }; }; }, /** * Resets the value of a style property * * @param element {Element} The DOM element to modify * @param name {String} Name of the style attribute (js variant e.g. marginTop, wordSpacing) * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties */ reset : function(element, name, smart){ // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling for specific properties if(smart !== false && this.__special[name]){ this.__special[name].reset(element); } else { element.style[name] = ""; }; }, /** * Gets the value of a style property. * * *Computed* * * Returns the computed value of a style property. Compared to the cascaded style, * this one also interprets the values e.g. translates <code>em</code> units to * <code>px</code>. * * *Cascaded* * * Returns the cascaded value of a style property. * * *Local* * * Ignores inheritance cascade. Does not interpret values. * * @signature function(element, name, mode, smart) * @param element {Element} The DOM element to modify * @param name {String} Name of the style attribute (js variant e.g. marginTop, wordSpacing) * @param mode {Number} Choose one of the modes {@link #COMPUTED_MODE}, {@link #CASCADED_MODE}, * {@link #LOCAL_MODE}. The computed mode is the default one. * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties * @return {var} The value of the property */ get : qx.core.Environment.select("engine.name", { "mshtml" : function(element, name, mode, smart){ // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling if(smart !== false && this.__special[name]){ return this.__special[name].get(element, mode); }; // if the element is not inserted into the document "currentStyle" // may be undefined. In this case always return the local style. if(!element.currentStyle){ return element.style[name] || ""; }; // switch to right mode switch(mode){case this.LOCAL_MODE: return element.style[name] || "";case this.CASCADED_MODE: return element.currentStyle[name] || "";default: // Read cascaded style. Shorthand properties like "border" are not available // on the currentStyle object. var currentStyle = element.currentStyle[name] || element.style[name] || ""; // Pixel values are always OK if(/^-?[\.\d]+(px)?$/i.test(currentStyle)){ return currentStyle; }; // Try to convert non-pixel values var pixel = this.__mshtmlPixel[name]; if(pixel){ // Backup local and runtime style var localStyle = element.style[name]; // Overwrite local value with cascaded value // This is needed to have the pixel value setupped element.style[name] = currentStyle || 0; // Read pixel value and add "px" var value = element.style[pixel] + "px"; // Recover old local value element.style[name] = localStyle; // Return value return value; }; // Just the current style return currentStyle;}; }, "default" : function(element, name, mode, smart){ // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling if(smart !== false && this.__special[name]){ return this.__special[name].get(element, mode); }; // switch to right mode switch(mode){case this.LOCAL_MODE: return element.style[name] || "";case this.CASCADED_MODE: // Currently only supported by Opera and Internet Explorer if(element.currentStyle){ return element.currentStyle[name] || ""; }; throw new Error("Cascaded styles are not supported in this browser!");// Support for the DOM2 getComputedStyle method // // Safari >= 3 & Gecko > 1.4 expose all properties to the returned // CSSStyleDeclaration object. In older browsers the function // "getPropertyValue" is needed to access the values. // // On a computed style object all properties are read-only which is // identical to the behavior of MSHTML's "currentStyle". default: // Opera, Mozilla and Safari 3+ also have a global getComputedStyle which is identical // to the one found under document.defaultView. // The problem with this is however that this does not work correctly // when working with frames and access an element of another frame. // Then we must use the <code>getComputedStyle</code> of the document // where the element is defined. var doc = qx.dom.Node.getDocument(element); var computed = doc.defaultView.getComputedStyle(element, null); // All relevant browsers expose the configured style properties to // the CSSStyleDeclaration objects if(computed && computed[name]){ return computed[name]; }; return element.style[name] || "";}; } }) }, defer : function(statics){ statics.__detectVendorProperties(); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Basic node creation and type detection */ qx.Bootstrap.define("qx.dom.Node", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /* --------------------------------------------------------------------------- NODE TYPES --------------------------------------------------------------------------- */ /** * {Map} Node type: * * * ELEMENT * * ATTRIBUTE * * TEXT * * CDATA_SECTION * * ENTITY_REFERENCE * * ENTITY * * PROCESSING_INSTRUCTION * * COMMENT * * DOCUMENT * * DOCUMENT_TYPE * * DOCUMENT_FRAGMENT * * NOTATION */ ELEMENT : 1, ATTRIBUTE : 2, TEXT : 3, CDATA_SECTION : 4, ENTITY_REFERENCE : 5, ENTITY : 6, PROCESSING_INSTRUCTION : 7, COMMENT : 8, DOCUMENT : 9, DOCUMENT_TYPE : 10, DOCUMENT_FRAGMENT : 11, NOTATION : 12, /* --------------------------------------------------------------------------- DOCUMENT ACCESS --------------------------------------------------------------------------- */ /** * Returns the owner document of the given node * * @param node {Node|Document|Window} the node which should be tested * @return {Document|null} The document of the given DOM node */ getDocument : function(node){ return node.nodeType === this.DOCUMENT ? node : // is document already node.ownerDocument || // is DOM node node.document; }, /** * Returns the DOM2 <code>defaultView</code> (window). * * @param node {Node|Document|Window} node to inspect * @return {Window} the <code>defaultView</code> of the given node */ getWindow : function(node){ // is a window already if(node.nodeType == null){ return node; }; // jump to document if(node.nodeType !== this.DOCUMENT){ node = node.ownerDocument; }; // jump to window return node.defaultView || node.parentWindow; }, /** * Returns the document element. (Logical root node) * * This is a convenience attribute that allows direct access to the child * node that is the root element of the document. For HTML documents, * this is the element with the tagName "HTML". * * @param node {Node|Document|Window} node to inspect * @return {Element} document element of the given node */ getDocumentElement : function(node){ return this.getDocument(node).documentElement; }, /** * Returns the body element. (Visual root node) * * This normally only makes sense for HTML documents. It returns * the content area of the HTML document. * * @param node {Node|Document|Window} node to inspect * @return {Element} document body of the given node */ getBodyElement : function(node){ return this.getDocument(node).body; }, /* --------------------------------------------------------------------------- TYPE TESTS --------------------------------------------------------------------------- */ /** * Whether the given object is a DOM node * * @param node {Node} the node which should be tested * @return {Boolean} true if the node is a DOM node */ isNode : function(node){ return !!(node && node.nodeType != null); }, /** * Whether the given object is a DOM element node * * @param node {Node} the node which should be tested * @return {Boolean} true if the node is a DOM element */ isElement : function(node){ return !!(node && node.nodeType === this.ELEMENT); }, /** * Whether the given object is a DOM document node * * @param node {Node} the node which should be tested * @return {Boolean} true when the node is a DOM document */ isDocument : function(node){ return !!(node && node.nodeType === this.DOCUMENT); }, /** * Whether the given object is a DOM text node * * @param node {Node} the node which should be tested * @return {Boolean} true if the node is a DOM text node */ isText : function(node){ return !!(node && node.nodeType === this.TEXT); }, /** * Check whether the given object is a browser window object. * * @param obj {Object} the object which should be tested * @return {Boolean} true if the object is a window object */ isWindow : function(obj){ return !!(obj && obj.history && obj.location && obj.document); }, /** * Whether the node has the given node name * * @param node {Node} the node * @param nodeName {String} the node name to check for * @return {Boolean} Whether the node has the given node name */ isNodeName : function(node, nodeName){ if(!nodeName || !node || !node.nodeName){ return false; }; return nodeName.toLowerCase() == qx.dom.Node.getName(node); }, /* --------------------------------------------------------------------------- UTILITIES --------------------------------------------------------------------------- */ /** * Get the node name as lower case string * * @param node {Node} the node * @return {String} the node name */ getName : function(node){ if(!node || !node.nodeName){ return null; }; return node.nodeName.toLowerCase(); }, /** * Returns the text content of an node where the node may be of node type * NODE_ELEMENT, NODE_ATTRIBUTE, NODE_TEXT or NODE_CDATA * * @param node {Node} the node from where the search should start. * If the node has subnodes the text contents are recursively retreived and joined. * @return {String} the joined text content of the given node or null if not appropriate. * @signature function(node) */ getText : function(node){ if(!node || !node.nodeType){ return null; }; switch(node.nodeType){case 1: // NODE_ELEMENT var i,a = [],nodes = node.childNodes,length = nodes.length; for(i = 0;i < length;i++){ a[i] = this.getText(nodes[i]); }; return a.join("");case 2:// NODE_ATTRIBUTE case 3:// NODE_TEXT case 4: // CDATA return node.nodeValue;}; return null; }, /** * Checks if the given node is a block node * * @param node {Node} Node * @return {Boolean} whether it is a block node */ isBlockNode : function(node){ if(!qx.dom.Node.isElement(node)){ return false; }; node = qx.dom.Node.getName(node); return /^(body|form|textarea|fieldset|ul|ol|dl|dt|dd|li|div|hr|p|h[1-6]|quote|pre|table|thead|tbody|tfoot|tr|td|th|iframe|address|blockquote)$/.test(node); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Yahoo! UI Library http://developer.yahoo.com/yui Version 2.2.0 Copyright: (c) 2007, Yahoo! Inc. License: BSD: http://developer.yahoo.com/yui/license.txt ---------------------------------------------------------------------- http://developer.yahoo.com/yui/license.html Copyright (c) 2009, Yahoo! Inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Yahoo! Inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************************************ */ /** * Includes library functions to work with the current document. */ qx.Bootstrap.define("qx.bom.Document", { statics : { /** * Whether the document is in quirks mode (e.g. non XHTML, HTML4 Strict or missing doctype) * * @signature function(win) * @param win {Window?window} The window to query * @return {Boolean} true when containing document is in quirks mode */ isQuirksMode : qx.core.Environment.select("engine.name", { "mshtml" : function(win){ if(qx.core.Environment.get("engine.version") >= 8){ return (win || window).document.documentMode === 5; } else { return (win || window).document.compatMode !== "CSS1Compat"; }; }, "webkit" : function(win){ if(document.compatMode === undefined){ var el = (win || window).document.createElement("div"); el.style.cssText = "position:absolute;width:0;height:0;width:1"; return el.style.width === "1px" ? true : false; } else { return (win || window).document.compatMode !== "CSS1Compat"; }; }, "default" : function(win){ return (win || window).document.compatMode !== "CSS1Compat"; } }), /** * Whether the document is in standard mode (e.g. XHTML, HTML4 Strict or doctype defined) * * @param win {Window?window} The window to query * @return {Boolean} true when containing document is in standard mode */ isStandardMode : function(win){ return !this.isQuirksMode(win); }, /** * Returns the width of the document. * * Internet Explorer in standard mode stores the proprietary <code>scrollWidth</code> property * on the <code>documentElement</code>, but in quirks mode on the body element. All * other known browsers simply store the correct value on the <code>documentElement</code>. * * If the viewport is wider than the document the viewport width is returned. * * As the html element has no visual appearance it also can not scroll. This * means that we must use the body <code>scrollWidth</code> in all non mshtml clients. * * Verified to correctly work with: * * * Mozilla Firefox 2.0.0.4 * * Opera 9.2.1 * * Safari 3.0 beta (3.0.2) * * Internet Explorer 7.0 * * @param win {Window?window} The window to query * @return {Integer} The width of the actual document (which includes the body and its margin). * * NOTE: Opera 9.5x and 9.6x have wrong value for the scrollWidth property, * if an element use negative value for top and left to be outside the viewport! * See: http://bugzilla.qooxdoo.org/show_bug.cgi?id=2869 */ getWidth : function(win){ var doc = (win || window).document; var view = qx.bom.Viewport.getWidth(win); var scroll = this.isStandardMode(win) ? doc.documentElement.scrollWidth : doc.body.scrollWidth; return Math.max(scroll, view); }, /** * Returns the height of the document. * * Internet Explorer in standard mode stores the proprietary <code>scrollHeight</code> property * on the <code>documentElement</code>, but in quirks mode on the body element. All * other known browsers simply store the correct value on the <code>documentElement</code>. * * If the viewport is higher than the document the viewport height is returned. * * As the html element has no visual appearance it also can not scroll. This * means that we must use the body <code>scrollHeight</code> in all non mshtml clients. * * Verified to correctly work with: * * * Mozilla Firefox 2.0.0.4 * * Opera 9.2.1 * * Safari 3.0 beta (3.0.2) * * Internet Explorer 7.0 * * @param win {Window?window} The window to query * @return {Integer} The height of the actual document (which includes the body and its margin). * * NOTE: Opera 9.5x and 9.6x have wrong value for the scrollWidth property, * if an element use negative value for top and left to be outside the viewport! * See: http://bugzilla.qooxdoo.org/show_bug.cgi?id=2869 */ getHeight : function(win){ var doc = (win || window).document; var view = qx.bom.Viewport.getHeight(win); var scroll = this.isStandardMode(win) ? doc.documentElement.scrollHeight : doc.body.scrollHeight; return Math.max(scroll, view); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Sebastian Fastner (fastner) * Tino Butz (tbtz) ====================================================================== This class contains code based on the following work: * Unify Project Homepage: http://unify-project.org Copyright: 2009-2010 Deutsche Telekom AG, Germany, http://telekom.com License: MIT: http://www.opensource.org/licenses/mit-license.php * Yahoo! UI Library http://developer.yahoo.com/yui Version 2.2.0 Copyright: (c) 2007, Yahoo! Inc. License: BSD: http://developer.yahoo.com/yui/license.txt ---------------------------------------------------------------------- http://developer.yahoo.com/yui/license.html Copyright (c) 2009, Yahoo! Inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Yahoo! Inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************************************ */ /** * Includes library functions to work with the client's viewport (window). * Orientation related functions are point to window.top as default. */ qx.Bootstrap.define("qx.bom.Viewport", { statics : { /** * Returns the current width of the viewport (excluding the vertical scrollbar * if present). * * @param win {Window?window} The window to query * @return {Integer} The width of the viewable area of the page (excluding scrollbars). */ getWidth : function(win){ var win = win || window; var doc = win.document; return qx.bom.Document.isStandardMode(win) ? doc.documentElement.clientWidth : doc.body.clientWidth; }, /** * Returns the current height of the viewport (excluding the horizontal scrollbar * if present). * * @param win {Window?window} The window to query * @return {Integer} The Height of the viewable area of the page (excluding scrollbars). */ getHeight : function(win){ var win = win || window; var doc = win.document; return qx.bom.Document.isStandardMode(win) ? doc.documentElement.clientHeight : doc.body.clientHeight; }, /** * Returns the scroll position of the viewport * * All clients except IE < 9 support the non-standard property <code>pageXOffset</code>. * As this is easier to evaluate we prefer this property over <code>scrollLeft</code>. * Since the window could differ from the one the application is running in, we can't * use a one-time environment check to decide which property to use. * * @param win {Window?window} The window to query * @return {Integer} Scroll position in pixels from left edge, always a positive integer or zero */ getScrollLeft : function(win){ var win = win ? win : window; if(typeof win.pageXOffset !== "undefined"){ return win.pageXOffset; }; // Firefox is using 'documentElement.scrollLeft' and Chrome is using // 'document.body.scrollLeft'. For the other value each browser is returning // 0, so we can use this check to get the positive value without using specific // browser checks. var doc = win.document; return doc.documentElement.scrollLeft || doc.body.scrollLeft; }, /** * Returns the scroll position of the viewport * * All clients except MSHTML support the non-standard property <code>pageYOffset</code>. * As this is easier to evaluate we prefer this property over <code>scrollTop</code>. * Since the window could differ from the one the application is running in, we can't * use a one-time environment check to decide which property to use. * * @param win {Window?window} The window to query * @return {Integer} Scroll position in pixels from top edge, always a positive integer or zero */ getScrollTop : function(win){ var win = win ? win : window; if(typeof win.pageYOffeset !== "undefined"){ return win.pageYOffset; }; // Firefox is using 'documentElement.scrollTop' and Chrome is using // 'document.body.scrollTop'. For the other value each browser is returning // 0, so we can use this check to get the positive value without using specific // browser checks. var doc = win.document; return doc.documentElement.scrollTop || doc.body.scrollTop; }, /** * Returns an orientation normalizer value that should be added to device orientation * to normalize behaviour on different devices. * * @param win {Window} The window to query * @return {Map} Orientation normalizing value */ __getOrientationNormalizer : function(win){ // Calculate own understanding of orientation (0 = portrait, 90 = landscape) var currentOrientation = this.getWidth(win) > this.getHeight(win) ? 90 : 0; var deviceOrientation = win.orientation; if(deviceOrientation == null || Math.abs(deviceOrientation % 180) == currentOrientation){ // No device orientation available or device orientation equals own understanding of orientation return { "-270" : 90, "-180" : 180, "-90" : -90, "0" : 0, "90" : 90, "180" : 180, "270" : -90 }; } else { // Device orientation is not equal to own understanding of orientation return { "-270" : 180, "-180" : -90, "-90" : 0, "0" : 90, "90" : 180, "180" : -90, "270" : 0 }; }; }, // Cache orientation normalizer map on start __orientationNormalizer : null, /** * Returns the current orientation of the viewport in degree. * * All possible values and their meaning: * * * <code>-90</code>: "Landscape" * * <code>0</code>: "Portrait" * * <code>90</code>: "Landscape" * * <code>180</code>: "Portrait" * * @param win {Window?window.top} The window to query. (Default = top window) * @return {Integer} The current orientation in degree */ getOrientation : function(win){ // Set window.top as default, because orientationChange event is only fired top window var win = win || window.top; // The orientation property of window does not have the same behaviour over all devices // iPad has 0degrees = Portrait, Playbook has 90degrees = Portrait, same for Android Honeycomb // // To fix this an orientationNormalizer map is calculated on application start // // The calculation of getWidth and getHeight returns wrong values if you are in an input field // on iPad and rotate your device! var orientation = win.orientation; if(orientation == null){ // Calculate orientation from window width and window height orientation = this.getWidth(win) > this.getHeight(win) ? 90 : 0; } else { if(this.__orientationNormalizer == null){ this.__orientationNormalizer = this.__getOrientationNormalizer(win); }; // Normalize orientation value orientation = this.__orientationNormalizer[orientation]; }; return orientation; }, /** * Whether the viewport orientation is currently in landscape mode. * * @param win {Window?window} The window to query * @return {Boolean} <code>true</code> when the viewport orientation * is currently in landscape mode. */ isLandscape : function(win){ return this.getWidth(win) >= this.getHeight(win); }, /** * Whether the viewport orientation is currently in portrait mode. * * @param win {Window?window} The window to query * @return {Boolean} <code>true</code> when the viewport orientation * is currently in portrait mode. */ isPortrait : function(win){ return this.getWidth(win) < this.getHeight(win); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Base2 http://code.google.com/p/base2/ Version 0.9 Copyright: (c) 2006-2007, Dean Edwards License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Dean Edwards ************************************************************************ */ /** * CSS class name support for HTML elements. Supports multiple class names * for each element. Can query and apply class names to HTML elements. */ qx.Bootstrap.define("qx.bom.element.Class", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** {RegExp} Regular expressions to split class names */ __splitter : /\s+/g, /** {RegExp} String trim regular expression. */ __trim : /^\s+|\s+$/g, /** * Adds a className to the given element * If successfully added the given className will be returned * * @signature function(element, name) * @param element {Element} The element to modify * @param name {String} The class name to add * @return {String} The added classname (if so) */ add : { "native" : function(element, name){ element.classList.add(name); return name; }, "default" : function(element, name){ if(!this.has(element, name)){ element.className += (element.className ? " " : "") + name; }; return name; } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Adds multiple classes to the given element * * @signature function(element, classes) * @param element {Element} DOM element to modify * @param classes {String[]} List of classes to add. * @return {String} The resulting class name which was applied */ addClasses : { "native" : function(element, classes){ for(var i = 0;i < classes.length;i++){ element.classList.add(classes[i]); }; return element.className; }, "default" : function(element, classes){ var keys = { }; var result; var old = element.className; if(old){ result = old.split(this.__splitter); for(var i = 0,l = result.length;i < l;i++){ keys[result[i]] = true; }; for(var i = 0,l = classes.length;i < l;i++){ if(!keys[classes[i]]){ result.push(classes[i]); }; }; } else { result = classes; }; return element.className = result.join(" "); } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Gets the classname of the given element * * @param element {Element} The element to query * @return {String} The retrieved classname */ get : function(element){ var className = element.className; if(typeof className.split !== 'function'){ if(typeof className === 'object'){ if(qx.Bootstrap.getClass(className) == 'SVGAnimatedString'){ className = className.baseVal; } else { { }; className = ''; }; }; if(typeof className === 'undefined'){ { }; className = ''; }; }; return className; }, /** * Whether the given element has the given className. * * @signature function(element, name) * @param element {Element} The DOM element to check * @param name {String} The class name to check for * @return {Boolean} true when the element has the given classname */ has : { "native" : function(element, name){ return element.classList.contains(name); }, "default" : function(element, name){ var regexp = new RegExp("(^|\\s)" + name + "(\\s|$)"); return regexp.test(element.className); } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Removes a className from the given element * * @signature function(element, name) * @param element {Element} The DOM element to modify * @param name {String} The class name to remove * @return {String} The removed class name */ remove : { "native" : function(element, name){ element.classList.remove(name); return name; }, "default" : function(element, name){ var regexp = new RegExp("(^|\\s)" + name + "(\\s|$)"); element.className = element.className.replace(regexp, "$2"); return name; } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Removes multiple classes from the given element * * @signature function(element, classes) * @param element {Element} DOM element to modify * @param classes {String[]} List of classes to remove. * @return {String} The resulting class name which was applied */ removeClasses : { "native" : function(element, classes){ for(var i = 0;i < classes.length;i++){ element.classList.remove(classes[i]); }; return element.className; }, "default" : function(element, classes){ var reg = new RegExp("\\b" + classes.join("\\b|\\b") + "\\b", "g"); return element.className = element.className.replace(reg, "").replace(this.__trim, "").replace(this.__splitter, " "); } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Replaces the first given class name with the second one * * @param element {Element} The DOM element to modify * @param oldName {String} The class name to remove * @param newName {String} The class name to add * @return {String} The added class name */ replace : function(element, oldName, newName){ if(!this.has(element, oldName)){ return ""; }; this.remove(element, oldName); return this.add(element, newName); }, /** * Toggles a className of the given element * * @signature function(element, name, toggle) * @param element {Element} The DOM element to modify * @param name {String} The class name to toggle * @param toggle {Boolean?null} Whether to switch class on/off. Without * the parameter an automatic toggling would happen. * @return {String} The class name */ toggle : { "native" : function(element, name, toggle){ if(toggle === undefined){ element.classList.toggle(name); } else { toggle ? this.add(element, name) : this.remove(element, name); }; return name; }, "default" : function(element, name, toggle){ if(toggle == null){ toggle = !this.has(element, name); }; toggle ? this.add(element, name) : this.remove(element, name); return name; } }[qx.core.Environment.get("html.classlist") ? "native" : "default"] } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Contains support for calculating dimensions of HTML elements. * * We differ between the box (or border) size which is available via * {@link #getWidth} and {@link #getHeight} and the content or scroll * sizes which are available via {@link #getContentWidth} and * {@link #getContentHeight}. */ qx.Bootstrap.define("qx.bom.element.Dimension", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Returns the rendered width of the given element. * * This is the visible width of the object, which need not to be identical * to the width configured via CSS. This highly depends on the current * box-sizing for the document and maybe even for the element. * * @signature function(element) * @param element {Element} element to query * @return {Integer} width of the element */ getWidth : qx.core.Environment.select("engine.name", { "gecko" : function(element){ // offsetWidth in Firefox does not always return the rendered pixel size // of an element. // Starting with Firefox 3 the rendered size can be determined by using // getBoundingClientRect // https://bugzilla.mozilla.org/show_bug.cgi?id=450422 if(element.getBoundingClientRect){ var rect = element.getBoundingClientRect(); return Math.round(rect.right) - Math.round(rect.left); } else { return element.offsetWidth; }; }, "default" : function(element){ return element.offsetWidth; } }), /** * Returns the rendered height of the given element. * * This is the visible height of the object, which need not to be identical * to the height configured via CSS. This highly depends on the current * box-sizing for the document and maybe even for the element. * * @signature function(element) * @param element {Element} element to query * @return {Integer} height of the element */ getHeight : qx.core.Environment.select("engine.name", { "gecko" : function(element){ if(element.getBoundingClientRect){ var rect = element.getBoundingClientRect(); return Math.round(rect.bottom) - Math.round(rect.top); } else { return element.offsetHeight; }; }, "default" : function(element){ return element.offsetHeight; } }), /** * Returns the rendered size of the given element. * * @param element {Element} element to query * @return {Map} map containing the width and height of the element */ getSize : function(element){ return { width : this.getWidth(element), height : this.getHeight(element) }; }, /** {Map} Contains all overflow values where scrollbars are invisible */ __hiddenScrollbars : { visible : true, hidden : true }, /** * Returns the content width. * * The content width is basically the maximum * width used or the maximum width which can be used by the content. This * excludes all kind of styles of the element like borders, paddings, margins, * and even scrollbars. * * Please note that with visible scrollbars the content width returned * may be larger than the box width returned via {@link #getWidth}. * * @param element {Element} element to query * @return {Integer} Computed content width */ getContentWidth : function(element){ var Style = qx.bom.element.Style; var overflowX = qx.bom.element.Style.get(element, "overflowX"); var paddingLeft = parseInt(Style.get(element, "paddingLeft") || "0px", 10); var paddingRight = parseInt(Style.get(element, "paddingRight") || "0px", 10); if(this.__hiddenScrollbars[overflowX]){ var contentWidth = element.clientWidth; if((qx.core.Environment.get("engine.name") == "opera") || qx.dom.Node.isBlockNode(element)){ contentWidth = contentWidth - paddingLeft - paddingRight; }; return contentWidth; } else { if(element.clientWidth >= element.scrollWidth){ // Scrollbars visible, but not needed? We need to substract both paddings return Math.max(element.clientWidth, element.scrollWidth) - paddingLeft - paddingRight; } else { // Scrollbars visible and needed. We just remove the left padding, // as the right padding is not respected in rendering. var width = element.scrollWidth - paddingLeft; // IE renders the paddingRight as well with scrollbars on if(qx.core.Environment.get("engine.name") == "mshtml" && qx.core.Environment.get("engine.version") >= 6){ width -= paddingRight; }; return width; }; }; }, /** * Returns the content height. * * The content height is basically the maximum * height used or the maximum height which can be used by the content. This * excludes all kind of styles of the element like borders, paddings, margins, * and even scrollbars. * * Please note that with visible scrollbars the content height returned * may be larger than the box height returned via {@link #getHeight}. * * @param element {Element} element to query * @return {Integer} Computed content height */ getContentHeight : function(element){ var Style = qx.bom.element.Style; var overflowY = qx.bom.element.Style.get(element, "overflowY"); var paddingTop = parseInt(Style.get(element, "paddingTop") || "0px", 10); var paddingBottom = parseInt(Style.get(element, "paddingBottom") || "0px", 10); if(this.__hiddenScrollbars[overflowY]){ return element.clientHeight - paddingTop - paddingBottom; } else { if(element.clientHeight >= element.scrollHeight){ // Scrollbars visible, but not needed? We need to substract both paddings return Math.max(element.clientHeight, element.scrollHeight) - paddingTop - paddingBottom; } else { // Scrollbars visible and needed. We just remove the top padding, // as the bottom padding is not respected in rendering. var height = element.scrollHeight - paddingTop; // IE renders the paddingBottom as well with scrollbars on if(qx.core.Environment.get("engine.name") == "mshtml" && qx.core.Environment.get("engine.version") == 6){ height -= paddingBottom; }; return height; }; }; }, /** * Returns the rendered content size of the given element. * * @param element {Element} element to query * @return {Map} map containing the content width and height of the element */ getContentSize : function(element){ return { width : this.getContentWidth(element), height : this.getContentHeight(element) }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * jQuery Dimension Plugin http://jquery.com/ Version 1.1.3 Copyright: (c) 2007, Paul Bakaus & Brandon Aaron License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: Paul Bakaus Brandon Aaron ************************************************************************ */ /** * Query the location of an arbitrary DOM element in relation to its top * level body element. Works in all major browsers: * * * Mozilla 1.5 + 2.0 * * Internet Explorer 6.0 + 7.0 (both standard & quirks mode) * * Opera 9.2 * * Safari 3.0 beta */ qx.Bootstrap.define("qx.bom.element.Location", { statics : { /** * Queries a style property for the given element * * @param elem {Element} DOM element to query * @param style {String} Style property * @return {String} Value of given style property */ __style : function(elem, style){ return qx.bom.element.Style.get(elem, style, qx.bom.element.Style.COMPUTED_MODE, false); }, /** * Queries a style property for the given element and parses it to an integer value * * @param elem {Element} DOM element to query * @param style {String} Style property * @return {Integer} Value of given style property */ __num : function(elem, style){ return parseInt(qx.bom.element.Style.get(elem, style, qx.bom.element.Style.COMPUTED_MODE, false), 10) || 0; }, /** * Computes the scroll offset of the given element relative to the document * <code>body</code>. * * @param elem {Element} DOM element to query * @return {Map} Map which contains the <code>left</code> and <code>top</code> scroll offsets */ __computeScroll : function(elem){ var left = 0,top = 0; // Find window var win = qx.dom.Node.getWindow(elem); left -= qx.bom.Viewport.getScrollLeft(win); top -= qx.bom.Viewport.getScrollTop(win); return { left : left, top : top }; }, /** * Computes the offset of the given element relative to the document * <code>body</code>. * * @param elem {Element} DOM element to query * @return {Map} Map which contains the <code>left</code> and <code>top</code> offsets */ __computeBody : qx.core.Environment.select("engine.name", { "mshtml" : function(elem){ // Find body element var doc = qx.dom.Node.getDocument(elem); var body = doc.body; var left = 0; var top = 0; left -= body.clientLeft + doc.documentElement.clientLeft; top -= body.clientTop + doc.documentElement.clientTop; if(!qx.core.Environment.get("browser.quirksmode")){ left += this.__num(body, "borderLeftWidth"); top += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, "webkit" : function(elem){ // Find body element var doc = qx.dom.Node.getDocument(elem); var body = doc.body; // Start with the offset var left = body.offsetLeft; var top = body.offsetTop; // only for safari < version 4.0 if(parseFloat(qx.core.Environment.get("engine.version")) < 530.17){ left += this.__num(body, "borderLeftWidth"); top += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, "gecko" : function(elem){ // Find body element var body = qx.dom.Node.getDocument(elem).body; // Start with the offset var left = body.offsetLeft; var top = body.offsetTop; // add the body margin for firefox 3.0 and below if(parseFloat(qx.core.Environment.get("engine.version")) < 1.9){ left += this.__num(body, "marginLeft"); top += this.__num(body, "marginTop"); }; // Correct substracted border (only in content-box mode) if(qx.bom.element.BoxSizing.get(body) !== "border-box"){ left += this.__num(body, "borderLeftWidth"); top += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, // At the moment only correctly supported by Opera "default" : function(elem){ // Find body element var body = qx.dom.Node.getDocument(elem).body; // Start with the offset var left = body.offsetLeft; var top = body.offsetTop; return { left : left, top : top }; } }), /** * Computes the sum of all offsets of the given element node. * * Traditionally this is a loop which goes up the whole parent tree * and sums up all found offsets. * * But both <code>mshtml</code> and <code>gecko >= 1.9</code> support * <code>getBoundingClientRect</code> which allows a * much faster access to the offset position. * * Please note: When gecko 1.9 does not use the <code>getBoundingClientRect</code> * implementation, and therefore use the traditional offset calculation * the gecko 1.9 fix in <code>__computeBody</code> must not be applied. * * @signature function(elem) * @param elem {Element} DOM element to query * @return {Map} Map which contains the <code>left</code> and <code>top</code> offsets */ __computeOffset : qx.core.Environment.select("engine.name", { "gecko" : function(elem){ // Use faster getBoundingClientRect() if available (gecko >= 1.9) if(elem.getBoundingClientRect){ var rect = elem.getBoundingClientRect(); // Firefox 3.0 alpha 6 (gecko 1.9) returns floating point numbers // use Math.round() to round them to style compatible numbers // MSHTML returns integer numbers var left = Math.round(rect.left); var top = Math.round(rect.top); } else { var left = 0; var top = 0; // Stop at the body var body = qx.dom.Node.getDocument(elem).body; var box = qx.bom.element.BoxSizing; if(box.get(elem) !== "border-box"){ left -= this.__num(elem, "borderLeftWidth"); top -= this.__num(elem, "borderTopWidth"); }; while(elem && elem !== body){ // Add node offsets left += elem.offsetLeft; top += elem.offsetTop; // Mozilla does not add the borders to the offset // when using box-sizing=content-box if(box.get(elem) !== "border-box"){ left += this.__num(elem, "borderLeftWidth"); top += this.__num(elem, "borderTopWidth"); }; // Mozilla does not add the border for a parent that has // overflow set to anything but visible if(elem.parentNode && this.__style(elem.parentNode, "overflow") != "visible"){ left += this.__num(elem.parentNode, "borderLeftWidth"); top += this.__num(elem.parentNode, "borderTopWidth"); }; // One level up (offset hierarchy) elem = elem.offsetParent; }; }; return { left : left, top : top }; }, "default" : function(elem){ var doc = qx.dom.Node.getDocument(elem); // Use faster getBoundingClientRect() if available if(elem.getBoundingClientRect){ var rect = elem.getBoundingClientRect(); var left = Math.round(rect.left); var top = Math.round(rect.top); } else { // Offset of the incoming element var left = elem.offsetLeft; var top = elem.offsetTop; // Start with the first offset parent elem = elem.offsetParent; // Stop at the body var body = doc.body; // Border correction is only needed for each parent // not for the incoming element itself while(elem && elem != body){ // Add node offsets left += elem.offsetLeft; top += elem.offsetTop; // Fix missing border left += this.__num(elem, "borderLeftWidth"); top += this.__num(elem, "borderTopWidth"); // One level up (offset hierarchy) elem = elem.offsetParent; }; }; return { left : left, top : top }; } }), /** * Computes the location of the given element in context of * the document dimensions. * * Supported modes: * * * <code>margin</code>: Calculate from the margin box of the element (bigger than the visual appearance: including margins of given element) * * <code>box</code>: Calculates the offset box of the element (default, uses the same size as visible) * * <code>border</code>: Calculate the border box (useful to align to border edges of two elements). * * <code>scroll</code>: Calculate the scroll box (relevant for absolute positioned content). * * <code>padding</code>: Calculate the padding box (relevant for static/relative positioned content). * * @param elem {Element} DOM element to query * @param mode {String?box} A supported option. See comment above. * @return {Map} Returns a map with <code>left</code>, <code>top</code>, * <code>right</code> and <code>bottom</code> which contains the distance * of the element relative to the document. */ get : function(elem, mode){ if(elem.tagName == "BODY"){ var location = this.__getBodyLocation(elem); var left = location.left; var top = location.top; } else { var body = this.__computeBody(elem); var offset = this.__computeOffset(elem); // Reduce by viewport scrolling. // Hint: getBoundingClientRect returns the location of the // element in relation to the viewport which includes // the scrolling var scroll = this.__computeScroll(elem); var left = offset.left + body.left - scroll.left; var top = offset.top + body.top - scroll.top; }; var right = left + elem.offsetWidth; var bottom = top + elem.offsetHeight; if(mode){ // In this modes we want the size as seen from a child what means that we want the full width/height // which may be higher than the outer width/height when the element has scrollbars. if(mode == "padding" || mode == "scroll"){ var overX = qx.bom.element.Style.get(elem, "overflowX"); if(overX == "scroll" || overX == "auto"){ right += elem.scrollWidth - elem.offsetWidth + this.__num(elem, "borderLeftWidth") + this.__num(elem, "borderRightWidth"); }; var overY = qx.bom.element.Style.get(elem, "overflowY"); if(overY == "scroll" || overY == "auto"){ bottom += elem.scrollHeight - elem.offsetHeight + this.__num(elem, "borderTopWidth") + this.__num(elem, "borderBottomWidth"); }; }; switch(mode){case "padding": left += this.__num(elem, "paddingLeft"); top += this.__num(elem, "paddingTop"); right -= this.__num(elem, "paddingRight"); bottom -= this.__num(elem, "paddingBottom");// no break here case "scroll": left -= elem.scrollLeft; top -= elem.scrollTop; right -= elem.scrollLeft; bottom -= elem.scrollTop;// no break here case "border": left += this.__num(elem, "borderLeftWidth"); top += this.__num(elem, "borderTopWidth"); right -= this.__num(elem, "borderRightWidth"); bottom -= this.__num(elem, "borderBottomWidth"); break;case "margin": left -= this.__num(elem, "marginLeft"); top -= this.__num(elem, "marginTop"); right += this.__num(elem, "marginRight"); bottom += this.__num(elem, "marginBottom"); break;}; }; return { left : left, top : top, right : right, bottom : bottom }; }, /** * Get the location of the body element relative to the document. * @param body {Element} The body element. * @return {Map} map with the keys <code>left</code> and <code>top</code> */ __getBodyLocation : function(body){ var top = body.offsetTop; var left = body.offsetLeft; if(qx.core.Environment.get("engine.name") !== "mshtml" || !((parseFloat(qx.core.Environment.get("engine.version")) < 8 || qx.core.Environment.get("browser.documentmode") < 8) && !qx.core.Environment.get("browser.quirksmode"))){ top += this.__num(body, "marginTop"); left += this.__num(body, "marginLeft"); }; if(qx.core.Environment.get("engine.name") === "gecko"){ top += this.__num(body, "borderLeftWidth"); left += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The left distance * of the element relative to the document. */ getLeft : function(elem, mode){ return this.get(elem, mode).left; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The top distance * of the element relative to the document. */ getTop : function(elem, mode){ return this.get(elem, mode).top; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The right distance * of the element relative to the document. */ getRight : function(elem, mode){ return this.get(elem, mode).right; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The bottom distance * of the element relative to the document. */ getBottom : function(elem, mode){ return this.get(elem, mode).bottom; }, /** * Returns the distance between two DOM elements. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem1 {Element} First element * @param elem2 {Element} Second element * @param mode1 {String?null} Mode for first element * @param mode2 {String?null} Mode for second element * @return {Map} Returns a map with <code>left</code> and <code>top</code> * which contains the distance of the elements from each other. */ getRelative : function(elem1, elem2, mode1, mode2){ var loc1 = this.get(elem1, mode1); var loc2 = this.get(elem2, mode2); return { left : loc1.left - loc2.left, top : loc1.top - loc2.top, right : loc1.right - loc2.right, bottom : loc1.bottom - loc2.bottom }; }, /** * Returns the distance between the given element to its offset parent. * * @param elem {Element} DOM element to query * @return {Map} Returns a map with <code>left</code> and <code>top</code> * which contains the distance of the elements from each other. */ getPosition : function(elem){ return this.getRelative(elem, this.getOffsetParent(elem)); }, /** * Detects the offset parent of the given element * * @param element {Element} Element to query for offset parent * @return {Element} Detected offset parent */ getOffsetParent : function(element){ var offsetParent = element.offsetParent || document.body; var Style = qx.bom.element.Style; while(offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && Style.get(offsetParent, "position") === "static")){ offsetParent = offsetParent.offsetParent; }; return offsetParent; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de 2006 STZ-IDA, Germany, http://www.stz-ida.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Andreas Junghans (lucidcake) ************************************************************************ */ /** * Cross-browser wrapper to work with CSS stylesheets. */ qx.Bootstrap.define("qx.bom.Stylesheet", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Include a CSS file * * <em>Note:</em> Using a resource ID as the <code>href</code> parameter * will no longer be supported. Call * <code>qx.util.ResourceManager.getInstance().toUri(href)</code> to get * valid URI to be used with this method. * * @param href {String} Href value * @param doc {Document?} Document to modify */ includeFile : function(href, doc){ if(!doc){ doc = document; }; var el = doc.createElement("link"); el.type = "text/css"; el.rel = "stylesheet"; el.href = href; var head = doc.getElementsByTagName("head")[0]; head.appendChild(el); }, /** * Create a new Stylesheet node and append it to the document * * @param text {String?} optional string of css rules * @return {Stylesheet} the generates stylesheet element */ createElement : function(text){ if(qx.core.Environment.get("html.stylesheet.createstylesheet")){ var sheet = document.createStyleSheet(); if(text){ sheet.cssText = text; }; return sheet; } else { var elem = document.createElement("style"); elem.type = "text/css"; if(text){ elem.appendChild(document.createTextNode(text)); }; document.getElementsByTagName("head")[0].appendChild(elem); return elem.sheet; }; }, /** * Insert a new CSS rule into a given Stylesheet * * @param sheet {Object} the target Stylesheet object * @param selector {String} the selector * @param entry {String} style rule */ addRule : function(sheet, selector, entry){ if(qx.core.Environment.get("html.stylesheet.insertrule")){ sheet.insertRule(selector + "{" + entry + "}", sheet.cssRules.length); } else { sheet.addRule(selector, entry); }; }, /** * Remove a CSS rule from a stylesheet * * @param sheet {Object} the Stylesheet * @param selector {String} the Selector of the rule to remove */ removeRule : function(sheet, selector){ if(qx.core.Environment.get("html.stylesheet.deleterule")){ var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;--i){ if(rules[i].selectorText == selector){ sheet.deleteRule(i); }; }; } else { var rules = sheet.rules; var len = rules.length; for(var i = len - 1;i >= 0;--i){ if(rules[i].selectorText == selector){ sheet.removeRule(i); }; }; }; }, /** * Remove the given sheet from its owner. * @param sheet {Object} the stylesheet object */ removeSheet : function(sheet){ var owner = sheet.ownerNode ? sheet.ownerNode : sheet.owningElement; qx.dom.Element.removeChild(owner, owner.parentNode); }, /** * Remove all CSS rules from a stylesheet * * @param sheet {Object} the stylesheet object */ removeAllRules : function(sheet){ if(qx.core.Environment.get("html.stylesheet.deleterule")){ var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ sheet.deleteRule(i); }; } else { var rules = sheet.rules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ sheet.removeRule(i); }; }; }, /** * Add an import of an external CSS file to a stylesheet * * @param sheet {Object} the stylesheet object * @param url {String} URL of the external stylesheet file */ addImport : function(sheet, url){ if(qx.core.Environment.get("html.stylesheet.addimport")){ sheet.addImport(url); } else { sheet.insertRule('@import "' + url + '";', sheet.cssRules.length); }; }, /** * Removes an import from a stylesheet * * @param sheet {Object} the stylesheet object * @param url {String} URL of the imported CSS file */ removeImport : function(sheet, url){ if(qx.core.Environment.get("html.stylesheet.removeimport")){ var imports = sheet.imports; var len = imports.length; for(var i = len - 1;i >= 0;i--){ if(imports[i].href == url || imports[i].href == qx.util.Uri.getAbsolute(url)){ sheet.removeImport(i); }; }; } else { var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ if(rules[i].href == url){ sheet.deleteRule(i); }; }; }; }, /** * Remove all imports from a stylesheet * * @param sheet {Object} the stylesheet object */ removeAllImports : function(sheet){ if(qx.core.Environment.get("html.stylesheet.removeimport")){ var imports = sheet.imports; var len = imports.length; for(var i = len - 1;i >= 0;i--){ sheet.removeImport(i); }; } else { var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ if(rules[i].type == rules[i].IMPORT_RULE){ sheet.deleteRule(i); }; }; }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (d_wagner) ************************************************************************ */ /** * Internal class which contains the checks used by {@link qx.core.Environment}. * All checks in here are marked as internal which means you should never use * them directly. * * This class contains checks related to Stylesheet objects. * * @internal */ qx.Bootstrap.define("qx.bom.client.Stylesheet", { statics : { /** * Returns a stylesheet to be used for feature checks * * @return {Stylesheet} Stylesheet element */ __getStylesheet : function(){ if(!qx.bom.client.Stylesheet.__stylesheet){ qx.bom.client.Stylesheet.__stylesheet = qx.bom.Stylesheet.createElement(); }; return qx.bom.client.Stylesheet.__stylesheet; }, /** * Check for IE's non-standard document.createStyleSheet function. * In IE9 (standards mode), the typeof check returns "function" so false is * returned. This is intended since IE9 supports the DOM-standard * createElement("style") which should be used instead. * * @internal * @return {Boolean} <code>true</code> if the browser supports * document.createStyleSheet */ getCreateStyleSheet : function(){ return typeof document.createStyleSheet === "object"; }, /** * Check for stylesheet.insertRule. Legacy IEs do not support this. * * @internal * @return {Boolean} <code>true</code> if insertRule is supported */ getInsertRule : function(){ return typeof qx.bom.client.Stylesheet.__getStylesheet().insertRule === "function"; }, /** * Check for stylesheet.deleteRule. Legacy IEs do not support this. * * @internal * @return {Boolean} <code>true</code> if deleteRule is supported */ getDeleteRule : function(){ return typeof qx.bom.client.Stylesheet.__getStylesheet().deleteRule === "function"; }, /** * Decides whether to use the legacy IE-only stylesheet.addImport or the * DOM-standard stylesheet.insertRule('@import [...]') * * @internal * @return {Boolean} <code>true</code> if stylesheet.addImport is supported */ getAddImport : function(){ return (typeof qx.bom.client.Stylesheet.__getStylesheet().addImport === "object"); }, /** * Decides whether to use the legacy IE-only stylesheet.removeImport or the * DOM-standard stylesheet.deleteRule('@import [...]') * * @internal * @return {Boolean} <code>true</code> if stylesheet.removeImport is supported */ getRemoveImport : function(){ return (typeof qx.bom.client.Stylesheet.__getStylesheet().removeImport === "object"); } }, defer : function(statics){ qx.core.Environment.add("html.stylesheet.createstylesheet", statics.getCreateStyleSheet); qx.core.Environment.add("html.stylesheet.insertrule", statics.getInsertRule); qx.core.Environment.add("html.stylesheet.deleterule", statics.getDeleteRule); qx.core.Environment.add("html.stylesheet.addimport", statics.getAddImport); qx.core.Environment.add("html.stylesheet.removeimport", statics.getRemoveImport); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Manages children structures of an element. Easy and convenient APIs * to insert, remove and replace children. */ qx.Bootstrap.define("qx.dom.Element", { statics : { /** * {Map} A list of all attributes which needs to be part of the initial element to work correctly * * @internal */ __initialAttributes : { "onload" : true, "onpropertychange" : true, "oninput" : true, "onchange" : true, "name" : true, "type" : true, "checked" : true, "disabled" : true }, /** * Whether the given <code>child</code> is a child of <code>parent</code> * * @param parent {Element} parent element * @param child {Node} child node * @return {Boolean} true when the given <code>child</code> is a child of <code>parent</code> */ hasChild : function(parent, child){ return child.parentNode === parent; }, /** * Whether the given <code>element</code> has children. * * @param element {Element} element to test * @return {Boolean} true when the given <code>element</code> has at least one child node */ hasChildren : function(element){ return !!element.firstChild; }, /** * Whether the given <code>element</code> has any child elements. * * @param element {Element} element to test * @return {Boolean} true when the given <code>element</code> has at least one child element */ hasChildElements : function(element){ element = element.firstChild; while(element){ if(element.nodeType === 1){ return true; }; element = element.nextSibling; }; return false; }, /** * Returns the parent element of the given element. * * @param element {Element} Element to find the parent for * @return {Element} The parent element */ getParentElement : function(element){ return element.parentNode; }, /** * Checks if the <code>element</code> is in the DOM, but note that * the method is very expensive! * * @param element {Element} The DOM element to check. * @param win {Window} The window to check for. * @return {Boolean} <code>true</code> if the <code>element</code> is in * the DOM, <code>false</code> otherwise. */ isInDom : function(element, win){ if(!win){ win = window; }; var domElements = win.document.getElementsByTagName(element.nodeName); for(var i = 0,l = domElements.length;i < l;i++){ if(domElements[i] === element){ return true; }; }; return false; }, /* --------------------------------------------------------------------------- INSERTION --------------------------------------------------------------------------- */ /** * Inserts <code>node</code> at the given <code>index</code> * inside <code>parent</code>. * * @param node {Node} node to insert * @param parent {Element} parent element node * @param index {Integer} where to insert * @return {Boolean} returns true (successful) */ insertAt : function(node, parent, index){ var ref = parent.childNodes[index]; if(ref){ parent.insertBefore(node, ref); } else { parent.appendChild(node); }; return true; }, /** * Insert <code>node</code> into <code>parent</code> as first child. * Indexes of other children will be incremented by one. * * @param node {Node} Node to insert * @param parent {Element} parent element node * @return {Boolean} returns true (successful) */ insertBegin : function(node, parent){ if(parent.firstChild){ this.insertBefore(node, parent.firstChild); } else { parent.appendChild(node); }; return true; }, /** * Insert <code>node</code> into <code>parent</code> as last child. * * @param node {Node} Node to insert * @param parent {Element} parent element node * @return {Boolean} returns true (successful) */ insertEnd : function(node, parent){ parent.appendChild(node); return true; }, /** * Inserts <code>node</code> before <code>ref</code> in the same parent. * * @param node {Node} Node to insert * @param ref {Node} Node which will be used as reference for insertion * @return {Boolean} returns true (successful) */ insertBefore : function(node, ref){ ref.parentNode.insertBefore(node, ref); return true; }, /** * Inserts <code>node</code> after <code>ref</code> in the same parent. * * @param node {Node} Node to insert * @param ref {Node} Node which will be used as reference for insertion * @return {Boolean} returns true (successful) */ insertAfter : function(node, ref){ var parent = ref.parentNode; if(ref == parent.lastChild){ parent.appendChild(node); } else { return this.insertBefore(node, ref.nextSibling); }; return true; }, /* --------------------------------------------------------------------------- REMOVAL --------------------------------------------------------------------------- */ /** * Removes the given <code>node</code> from its parent element. * * @param node {Node} Node to remove * @return {Boolean} <code>true</code> when node was successfully removed, * otherwise <code>false</code> */ remove : function(node){ if(!node.parentNode){ return false; }; node.parentNode.removeChild(node); return true; }, /** * Removes the given <code>node</code> from the <code>parent</code>. * * @param node {Node} Node to remove * @param parent {Element} parent element which contains the <code>node</code> * @return {Boolean} <code>true</code> when node was successfully removed, * otherwise <code>false</code> */ removeChild : function(node, parent){ if(node.parentNode !== parent){ return false; }; parent.removeChild(node); return true; }, /** * Removes the node at the given <code>index</code> * from the <code>parent</code>. * * @param index {Integer} position of the node which should be removed * @param parent {Element} parent DOM element * @return {Boolean} <code>true</code> when node was successfully removed, * otherwise <code>false</code> */ removeChildAt : function(index, parent){ var child = parent.childNodes[index]; if(!child){ return false; }; parent.removeChild(child); return true; }, /* --------------------------------------------------------------------------- REPLACE --------------------------------------------------------------------------- */ /** * Replaces <code>oldNode</code> with <code>newNode</code> in the current * parent of <code>oldNode</code>. * * @param newNode {Node} DOM node to insert * @param oldNode {Node} DOM node to remove * @return {Boolean} <code>true</code> when node was successfully replaced */ replaceChild : function(newNode, oldNode){ if(!oldNode.parentNode){ return false; }; oldNode.parentNode.replaceChild(newNode, oldNode); return true; }, /** * Replaces the node at <code>index</code> with <code>newNode</code> in * the given parent. * * @param newNode {Node} DOM node to insert * @param index {Integer} position of old DOM node * @param parent {Element} parent DOM element * @return {Boolean} <code>true</code> when node was successfully replaced */ replaceAt : function(newNode, index, parent){ var oldNode = parent.childNodes[index]; if(!oldNode){ return false; }; parent.replaceChild(newNode, oldNode); return true; }, /** * Stores helper element for element creation in WebKit * * @internal */ __helperElement : { }, /** * Saves whether a helper element is needed for each window. * * @internal */ __allowMarkup : { }, /** * Detects if the DOM support a <code>document.createElement</code> call with a * <code>String</code> as markup like: * * <pre class="javascript"> * document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='Second Choice'>"); * </pre> * * Element creation with markup is not standard compatible with Document Object Model (Core) Level 1, but * Internet Explorer supports it. With an exception that IE9 in IE9 standard mode is standard compatible and * doesn't support element creation with markup. * * @param win {Window?} Window to check for * @return {Boolean} <code>true</code> if the DOM supports it, <code>false</code> otherwise. */ _allowCreationWithMarkup : function(win){ if(!win){ win = window; }; // key is needed to allow using different windows var key = win.location.href; if(qx.dom.Element.__allowMarkup[key] == undefined){ try{ win.document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='Second Choice'>"); qx.dom.Element.__allowMarkup[key] = true; } catch(e) { qx.dom.Element.__allowMarkup[key] = false; }; }; return qx.dom.Element.__allowMarkup[key]; }, /** * Creates and returns a DOM helper element. * * @param win {Window?} Window to create the element for * @return {Element} The created element node */ getHelperElement : function(win){ if(!win){ win = window; }; // key is needed to allow using different windows var key = win.location.href; if(!qx.dom.Element.__helperElement[key]){ var helper = qx.dom.Element.__helperElement[key] = win.document.createElement("div"); // innerHTML will only parsed correctly if element is appended to document if(qx.core.Environment.get("engine.name") == "webkit"){ helper.style.display = "none"; win.document.body.appendChild(helper); }; }; return qx.dom.Element.__helperElement[key]; }, /** * Creates a DOM element. * * Attributes may be given directly with this call. This is critical * for some attributes e.g. name, type, ... in many clients. * * Depending on the kind of attributes passed, <code>innerHTML</code> may be * used internally to assemble the element. Please make sure you understand * the security implications. See {@link qx.bom.Html#clean}. * * @param name {String} Tag name of the element * @param attributes {Map?} Map of attributes to apply * @param win {Window?} Window to create the element for * @return {Element} The created element node */ create : function(name, attributes, win){ if(!win){ win = window; }; if(!name){ throw new Error("The tag name is missing!"); }; var initial = this.__initialAttributes; var attributesHtml = ""; for(var key in attributes){ if(initial[key]){ attributesHtml += key + "='" + attributes[key] + "' "; }; }; var element; // If specific attributes are defined we need to process // the element creation in a more complex way. if(attributesHtml != ""){ if(qx.dom.Element._allowCreationWithMarkup(win)){ element = win.document.createElement("<" + name + " " + attributesHtml + ">"); } else { var helper = qx.dom.Element.getHelperElement(win); helper.innerHTML = "<" + name + " " + attributesHtml + "></" + name + ">"; element = helper.firstChild; }; } else { element = win.document.createElement(name); }; for(var key in attributes){ if(!initial[key]){ qx.bom.element.Attribute.set(element, key, attributes[key]); }; }; return element; }, /** * Removes all content from the given element * * @param element {Element} element to clean * @return {String} empty string (new HTML content) */ empty : function(element){ return element.innerHTML = ""; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Alexander Steitz (aback) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson 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 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. ************************************************************************ */ /** * Attribute/Property handling for DOM HTML elements. * * Also includes support for HTML properties like <code>checked</code> * or <code>value</code>. This feature set is supported cross-browser * through one common interface and is independent of the differences between * the multiple implementations. * * Supports applying text and HTML content using the attribute names * <code>text</code> and <code>html</code>. */ qx.Bootstrap.define("qx.bom.element.Attribute", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** Internal map of attribute conversions */ __hints : { // Name translation table (camelcase is important for some attributes) names : { "class" : "className", "for" : "htmlFor", html : "innerHTML", text : qx.core.Environment.get("html.element.textcontent") ? "textContent" : "innerText", colspan : "colSpan", rowspan : "rowSpan", valign : "vAlign", datetime : "dateTime", accesskey : "accessKey", tabindex : "tabIndex", maxlength : "maxLength", readonly : "readOnly", longdesc : "longDesc", cellpadding : "cellPadding", cellspacing : "cellSpacing", frameborder : "frameBorder", usemap : "useMap" }, // Attributes which are only applyable on a DOM element (not using compile()) runtime : { "html" : 1, "text" : 1 }, // Attributes which are (forced) boolean bools : { compact : 1, nowrap : 1, ismap : 1, declare : 1, noshade : 1, checked : 1, disabled : 1, readOnly : 1, multiple : 1, selected : 1, noresize : 1, defer : 1, allowTransparency : 1 }, // Interpreted as property (element.property) property : { // Used by qx.html.Element $$html : 1, // Used by qx.ui.core.Widget $$widget : 1, // Native properties disabled : 1, checked : 1, readOnly : 1, multiple : 1, selected : 1, value : 1, maxLength : 1, className : 1, innerHTML : 1, innerText : 1, textContent : 1, htmlFor : 1, tabIndex : 1 }, qxProperties : { $$widget : 1, $$html : 1 }, // Default values when "null" is given to a property propertyDefault : { disabled : false, checked : false, readOnly : false, multiple : false, selected : false, value : "", className : "", innerHTML : "", innerText : "", textContent : "", htmlFor : "", tabIndex : 0, maxLength : qx.core.Environment.select("engine.name", { "mshtml" : 2147483647, "webkit" : 524288, "default" : -1 }) }, // Properties which can be removed to reset them removeableProperties : { disabled : 1, multiple : 1, maxLength : 1 }, // Use getAttribute(name, 2) for these to query for the real value, not // the interpreted one. original : { href : 1, src : 1, type : 1 } }, /** * Compiles an incoming attribute map to a string which * could be used when building HTML blocks using innerHTML. * * This method silently ignores runtime attributes like * <code>html</code> or <code>text</code>. * * @param map {Map} Map of attributes. The key is the name of the attribute. * @return {String} Returns a compiled string ready for usage. */ compile : function(map){ var html = []; var runtime = this.__hints.runtime; for(var key in map){ if(!runtime[key]){ html.push(key, "='", map[key], "'"); }; }; return html.join(""); }, /** * Returns the value of the given HTML attribute * * @param element {Element} The DOM element to query * @param name {String} Name of the attribute * @return {var} The value of the attribute */ get : function(element, name){ var hints = this.__hints; var value; // normalize name name = hints.names[name] || name; // respect original values // http://msdn2.microsoft.com/en-us/library/ms536429.aspx if(qx.core.Environment.get("engine.name") == "mshtml" && parseInt(qx.core.Environment.get("browser.documentmode"), 10) < 8 && hints.original[name]){ value = element.getAttribute(name, 2); } else if(hints.property[name]){ value = element[name]; if(typeof hints.propertyDefault[name] !== "undefined" && value == hints.propertyDefault[name]){ // only return null for all non-boolean properties if(typeof hints.bools[name] === "undefined"){ return null; } else { return value; }; }; } else { // fallback to attribute value = element.getAttribute(name); }; if(hints.bools[name]){ return !!value; }; return value; }, /** * Sets an HTML attribute on the given DOM element * * @param element {Element} The DOM element to modify * @param name {String} Name of the attribute * @param value {var} New value of the attribute */ set : function(element, name, value){ if(typeof value === "undefined"){ return; }; var hints = this.__hints; // normalize name name = hints.names[name] || name; // respect booleans if(hints.bools[name]){ value = !!value; }; // apply attribute // only properties which can be applied by the browser or qxProperties // otherwise use the attribute methods if(hints.property[name] && (!(element[name] === undefined) || hints.qxProperties[name])){ // resetting the attribute/property if(value == null){ // for properties which need to be removed for a correct reset if(hints.removeableProperties[name]){ element.removeAttribute(name); return; } else if(typeof hints.propertyDefault[name] !== "undefined"){ value = hints.propertyDefault[name]; }; }; element[name] = value; } else { if(value === true){ element.setAttribute(name, name); } else if(value === false || value === null){ element.removeAttribute(name); } else { element.setAttribute(name, value); }; }; }, /** * Resets an HTML attribute on the given DOM element * * @param element {Element} The DOM element to modify * @param name {String} Name of the attribute */ reset : function(element, name){ this.set(element, name, null); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Utility for checking the type of a variable. * It adds a <code>type</code> key static to q and offers the given method. * * <pre class="javascript"> * q.type.get("abc"); // return "String" e.g. * </pre> */ qx.Bootstrap.define("qx.module.util.Type", { statics : { /** * Get the internal class of the value. The following classes are possible: * <code>"String"</code>, * <code>"Array"</code>, * <code>"Object"</code>, * <code>"RegExp"</code>, * <code>"Number"</code>, * <code>"Boolean"</code>, * <code>"Date"</code>, * <code>"Function"</code>, * <code>"Error"</code> * </pre> * @attachStatic {qxWeb, type.get} * @signature function(value) * @param value {var} Value to get the class for. * @return {String} The internal class of the value. */ get : qx.Bootstrap.getClass }, defer : function(statics){ qxWeb.$attachStatic({ type : { get : statics.get } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ====================================================================== This class contains code based on the following work: * es5-shim Code: https://github.com/kriskowal/es5-shim/ Copyright: (c) 2009, 2010 Kristopher Michael Kowal License: https://github.com/kriskowal/es5-shim/blob/master/LICENSE ---------------------------------------------------------------------- Copyright 2009, 2010 Kristopher Michael Kowal. All rights reserved. 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. ---------------------------------------------------------------------- Version: Snapshot taken on 2012-07-25,: commit 9f539abd9aa9950e1d907077a4be7f5133a00e52 ************************************************************************ */ /** * This class takes care of the normalization of the native 'Function' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *bind*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind">MDN documentation</a> | * <a href="http://es5.github.com/#x15.3.4.5">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Function", { defer : function(){ // bind if(!qx.core.Environment.get("ecmascript.function.bind")){ var slice = Array.prototype.slice; Function.prototype.bind = function(that){ // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if(typeof target != "function"){ throw new TypeError("Function.prototype.bind called on incompatible " + target); }; // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = slice.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var bound = function(){ if(this instanceof bound){ // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var F = function(){ }; 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 { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply(that, args.concat(slice.call(arguments))); }; }; // XXX bound.length is never writable, so don't even try // // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Error' object. * It contains a simple bugfix for toString which might not print out the proper * error message. * * *toString*: * <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Error/toString">MDN documentation</a> | * <a href="http://es5.github.com/#x15.11.4.4">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Error", { defer : function(){ // toString if(!qx.core.Environment.get("ecmascript.error.toString")){ Error.prototype.toString = function(){ var name = this.name || "Error"; var message = this.message || ""; if(name === "" && message === ""){ return "Error"; }; if(name === ""){ return message; }; if(message === ""){ return name; }; return name + ": " + message; }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.Function) #require(qx.lang.normalize.String) #require(qx.lang.normalize.Date) #require(qx.lang.normalize.Array) #require(qx.lang.normalize.Error) #require(qx.lang.normalize.Object) ************************************************************************ */ /** * Adds JavaScript features that may not be supported by all clients. */ qx.Bootstrap.define("qx.module.Polyfill", { }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Polyfill) ************************************************************************ */ /** * Support for native and custom events. */ qx.Bootstrap.define("qx.module.Event", { statics : { /** * Event normalization registry * * @internal */ __normalizations : { }, /** * Registry of event hooks * @internal */ __hooks : { on : { }, off : { } }, /** * Registers a listener for the given event type on each item in the * collection. This can be either native or custom events. * * @attach {qxWeb} * @param type {String} Type of the event to listen for * @param listener {Function} Listener callback * @param context {Object?} Context the callback function will be executed in. * Default: The element on which the listener was registered * @return {qxWeb} The collection for chaining */ on : function(type, listener, context){ for(var i = 0;i < this.length;i++){ var el = this[i]; var ctx = context || qxWeb(el); // call hooks var hooks = qx.module.Event.__hooks.on; // generic var typeHooks = hooks["*"] || []; // type specific if(hooks[type]){ typeHooks = typeHooks.concat(hooks[type]); }; for(var j = 0,m = typeHooks.length;j < m;j++){ typeHooks[j](el, type, listener, context); }; var bound = function(event){ // apply normalizations var registry = qx.module.Event.__normalizations; // generic var normalizations = registry["*"] || []; // type specific if(registry[type]){ normalizations = normalizations.concat(registry[type]); }; for(var x = 0,y = normalizations.length;x < y;x++){ event = normalizations[x](event, el, type); }; // call original listener with normalized event listener.apply(this, [event]); }.bind(ctx); bound.original = listener; // add native listener if(qx.bom.Event.supportsEvent(el, type)){ qx.bom.Event.addNativeListener(el, type, bound); }; // create an emitter if necessary if(!el.__emitter){ el.__emitter = new qx.event.Emitter(); }; var id = el.__emitter.on(type, bound, ctx); if(!el.__listener){ el.__listener = { }; }; if(!el.__listener[type]){ el.__listener[type] = { }; }; el.__listener[type][id] = bound; if(!context){ // store a reference to the dynamically created context so we know // what to check for when removing the listener if(!el.__ctx){ el.__ctx = { }; }; el.__ctx[id] = ctx; }; }; return this; }, /** * Unregisters event listeners for the given type from each element in the * collection. * * @attach {qxWeb} * @param type {String} Type of the event * @param listener {Function} Listener callback * @param context {Object?} Listener callback context * @return {qxWeb} The collection for chaining */ off : function(type, listener, context){ for(var j = 0;j < this.length;j++){ var el = this[j]; // continue if no listener are available if(!el.__listener){ continue; }; for(var id in el.__listener[type]){ var storedListener = el.__listener[type][id]; if(storedListener == listener || storedListener.original == listener){ // get the stored context var hasStoredContext = typeof el.__ctx !== "undefined" && el.__ctx[id]; if(!context && hasStoredContext){ var storedContext = el.__ctx[id]; }; // remove the listener from the emitter el.__emitter.off(type, storedListener, storedContext || context); // check if it's a bound listener which means it was a native event if(storedListener.original == listener){ // remove the native listener qx.bom.Event.removeNativeListener(el, type, storedListener); }; delete el.__listener[type][id]; if(hasStoredContext){ delete el.__ctx[id]; }; }; }; // call hooks var hooks = qx.module.Event.__hooks.off; // generic var typeHooks = hooks["*"] || []; // type specific if(hooks[type]){ typeHooks = typeHooks.concat(hooks[type]); }; for(var i = 0,m = typeHooks.length;i < m;i++){ typeHooks[i](el, type, listener, context); }; }; return this; }, /** * Fire an event of the given type. * * @attach {qxWeb} * @param type {String} Event type * @param data {var?} Optional data that will be passed to the listener * callback function. * @return {qxWeb} The collection for chaining */ emit : function(type, data){ for(var j = 0;j < this.length;j++){ var el = this[j]; if(el.__emitter){ el.__emitter.emit(type, data); }; }; return this; }, /** * Attaches a listener for the given event that will be executed only once. * * @attach {qxWeb} * @param type {String} Type of the event to listen for * @param listener {Function} Listener callback * @param context {Object?} Context the callback function will be executed in. * Default: The element on which the listener was registered * @return {qxWeb} The collection for chaining */ once : function(type, listener, context){ var self = this; var wrappedListener = function(data){ self.off(type, wrappedListener, context); listener.call(this, data); }; this.on(type, wrappedListener, context); return this; }, /** * Checks if one or more listeners for the given event type are attached to * the first element in the collection * * @attach {qxWeb} * @param type {String} Event type, e.g. <code>mousedown</code> * @return {Boolean} <code>true</code> if one or more listeners are attached */ hasListener : function(type){ if(!this[0] || !this[0].__emitter || !this[0].__emitter.getListeners()[type]){ return false; }; return this[0].__emitter.getListeners()[type].length > 0; }, /** * Copies any event listeners that are attached to the elements in the * collection to the provided target element * * @internal * @param target {Element} Element to attach the copied listeners to */ copyEventsTo : function(target){ // Copy both arrays to make sure the original collections are not manipulated. // If e.g. the 'target' array contains a DOM node with child nodes we run into // problems because the 'target' array is flattened within this method. var source = this.concat(); var targetCopy = target.concat(); // get all children of source and target for(var i = source.length - 1;i >= 0;i--){ var descendants = source[i].getElementsByTagName("*"); for(var j = 0;j < descendants.length;j++){ source.push(descendants[j]); }; }; for(var i = targetCopy.length - 1;i >= 0;i--){ var descendants = targetCopy[i].getElementsByTagName("*"); for(var j = 0;j < descendants.length;j++){ targetCopy.push(descendants[j]); }; }; // make sure no emitter object has been copied targetCopy.forEach(function(el){ el.__emitter = null; }); for(var i = 0;i < source.length;i++){ var el = source[i]; if(!el.__emitter){ continue; }; var storage = el.__emitter.getListeners(); for(var name in storage){ for(var j = storage[name].length - 1;j >= 0;j--){ var listener = storage[name][j].listener; if(listener.original){ listener = listener.original; }; qxWeb(targetCopy[i]).on(name, listener, storage[name][j].ctx); }; }; }; }, __isReady : false, /** * Executes the given function once the document is ready. * * @attachStatic {qxWeb} * @param callback {Function} callback function */ ready : function(callback){ // DOM is already ready if(document.readyState === "complete"){ window.setTimeout(callback, 1); return; }; // listen for the load event so the callback is executed no matter what var onWindowLoad = function(){ qx.module.Event.__isReady = true; callback(); }; qxWeb(window).on("load", onWindowLoad); var wrappedCallback = function(){ qxWeb(window).off("load", onWindowLoad); callback(); }; // Listen for DOMContentLoaded event if available (no way to reliably detect // support) if(qxWeb.env.get("engine.name") !== "mshtml" || qxWeb.env.get("browser.documentmode") > 8){ qx.bom.Event.addNativeListener(document, "DOMContentLoaded", wrappedCallback); } else { // Continually check to see if the document is ready var timer = function(){ // onWindowLoad already executed if(qx.module.Event.__isReady){ return; }; try{ // If DOMContentLoaded is unavailable, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); if(document.body){ wrappedCallback(); }; } catch(error) { window.setTimeout(timer, 100); }; }; timer(); }; }, /** * Registers a normalization function for the given event types. Listener * callbacks for these types will be called with the return value of the * normalization function instead of the regular event object. * * The normalizer will be called with two arguments: The original event * object and the element on which the event was triggered * * @attachStatic {qxWeb, $registerEventNormalization} * @param types {String[]} List of event types to be normalized. Use an * asterisk (<code>*</code>) to normalize all event types * @param normalizer {Function} Normalizer function */ $registerNormalization : function(types, normalizer){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var registry = qx.module.Event.__normalizations; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(qx.lang.Type.isFunction(normalizer)){ if(!registry[type]){ registry[type] = []; }; registry[type].push(normalizer); }; }; }, /** * Unregisters a normalization function from the given event types. * * @attachStatic {qxWeb, $unregisterEventNormalization} * @param types {String[]} List of event types * @param normalizer {Function} Normalizer function */ $unregisterNormalization : function(types, normalizer){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var registry = qx.module.Event.__normalizations; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(registry[type]){ qx.lang.Array.remove(registry[type], normalizer); }; }; }, /** * Returns all registered event normalizers * * @attachStatic {qxWeb, $getEventNormalizationRegistry} * @return {Map} Map of event types/normalizer functions */ $getRegistry : function(){ return qx.module.Event.__normalizations; }, /** * Registers an event hook for the given event types. * * @attachStatic {qxWeb, $registerEventHook} * @param types {String[]} List of event types * @param registerHook {Function} Hook function to be called on event registration * @param unregisterHook {Function?} Hook function to be called on event deregistration * @internal */ $registerEventHook : function(types, registerHook, unregisterHook){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var onHooks = qx.module.Event.__hooks.on; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(qx.lang.Type.isFunction(registerHook)){ if(!onHooks[type]){ onHooks[type] = []; }; onHooks[type].push(registerHook); }; }; if(!unregisterHook){ return; }; var offHooks = qx.module.Event.__hooks.off; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(qx.lang.Type.isFunction(unregisterHook)){ if(!offHooks[type]){ offHooks[type] = []; }; offHooks[type].push(unregisterHook); }; }; }, /** * Unregisters a hook from the given event types. * * @attachStatic {qxWeb, $unregisterEventHooks} * @param types {String[]} List of event types * @param registerHook {Function} Hook function to be called on event registration * @param unregisterHook {Function?} Hook function to be called on event deregistration * @internal */ $unregisterEventHook : function(types, registerHook, unregisterHook){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var onHooks = qx.module.Event.__hooks.on; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(onHooks[type]){ qx.lang.Array.remove(onHooks[type], registerHook); }; }; if(!unregisterHook){ return; }; var offHooks = qx.module.Event.__hooks.off; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(offHooks[type]){ qx.lang.Array.remove(offHooks[type], unregisterHook); }; }; }, /** * Returns all registered event hooks * * @attachStatic {qxWeb, $getEventHookRegistry} * @return {Map} Map of event types/registration hook functions * @internal */ $getHookRegistry : function(){ return qx.module.Event.__hooks; } }, defer : function(statics){ qxWeb.$attach({ "on" : statics.on, "off" : statics.off, "once" : statics.once, "emit" : statics.emit, "hasListener" : statics.hasListener, "copyEventsTo" : statics.copyEventsTo }); qxWeb.$attachStatic({ "ready" : statics.ready, "$registerEventNormalization" : statics.$registerNormalization, "$unregisterEventNormalization" : statics.$unregisterNormalization, "$getEventNormalizationRegistry" : statics.$getRegistry, "$registerEventHook" : statics.$registerEventHook, "$unregisterEventHook" : statics.$unregisterEventHook, "$getEventHookRegistry" : statics.$getHookRegistry }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2007-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Sebastian Werner (wpbasti) * Alexander Steitz (aback) * Christian Hagendorn (chris_schmidt) ====================================================================== This class contains code based on the following work: * Juriy Zaytsev http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ Copyright (c) 2009 Juriy Zaytsev Licence: BSD: http://github.com/kangax/iseventsupported/blob/master/LICENSE ---------------------------------------------------------------------- http://github.com/kangax/iseventsupported/blob/master/LICENSE Copyright (c) 2009 Juriy Zaytsev 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. ************************************************************************ */ /** * Wrapper around native event management capabilities of the browser. * This class should not be used directly normally. It's better * to use {@link qx.event.Registration} instead. */ qx.Bootstrap.define("qx.bom.Event", { statics : { /** * Use the low level browser functionality to attach event listeners * to DOM nodes. * * Use this with caution. This is only thought for event handlers and * qualified developers. These are not mem-leak protected! * * @param target {Object} Any valid native event target * @param type {String} Name of the event * @param listener {Function} The pointer to the function to assign * @param useCapture {Boolean ? false} A Boolean value that specifies the event phase to add * the event handler for the capturing phase or the bubbling phase. */ addNativeListener : function(target, type, listener, useCapture){ if(target.addEventListener){ target.addEventListener(type, listener, !!useCapture); } else if(target.attachEvent){ target.attachEvent("on" + type, listener); } else if(typeof target["on" + type] != "undefined"){ target["on" + type] = listener; } else { { }; };; }, /** * Use the low level browser functionality to remove event listeners * from DOM nodes. * * @param target {Object} Any valid native event target * @param type {String} Name of the event * @param listener {Function} The pointer to the function to assign * @param useCapture {Boolean ? false} A Boolean value that specifies the event phase to remove * the event handler for the capturing phase or the bubbling phase. */ removeNativeListener : function(target, type, listener, useCapture){ if(target.removeEventListener){ target.removeEventListener(type, listener, !!useCapture); } else if(target.detachEvent){ try{ target.detachEvent("on" + type, listener); } catch(e) { // IE7 sometimes dispatches "unload" events on protected windows // Ignore the "permission denied" errors. if(e.number !== -2146828218){ throw e; }; }; } else if(typeof target["on" + type] != "undefined"){ target["on" + type] = null; } else { { }; };; }, /** * Returns the target of the event. * * @param e {Event} Native event object * @return {Object} Any valid native event target */ getTarget : function(e){ return e.target || e.srcElement; }, /** * Computes the related target from the native DOM event * * @param e {Event} Native DOM event object * @return {Element} The related target */ getRelatedTarget : function(e){ if(e.relatedTarget !== undefined){ // In Firefox the related target of mouse events is sometimes an // anonymous div inside of a text area, which raises an exception if // the nodeType is read. This is why the try/catch block is needed. if((qx.core.Environment.get("engine.name") == "gecko")){ try{ e.relatedTarget && e.relatedTarget.nodeType; } catch(ex) { return null; }; }; return e.relatedTarget; } else if(e.fromElement !== undefined && e.type === "mouseover"){ return e.fromElement; } else if(e.toElement !== undefined){ return e.toElement; } else { return null; };; }, /** * Prevent the native default of the event to be processed. * * This is useful to stop native keybindings, native selection * and other native functionality behind events. * * @param e {Event} Native event object */ preventDefault : function(e){ if(e.preventDefault){ e.preventDefault(); } else { try{ // this allows us to prevent some key press events in IE. // See bug #1049 e.keyCode = 0; } catch(ex) { }; e.returnValue = false; }; }, /** * Stops the propagation of the given event to the parent element. * * Only useful for events which bubble e.g. mousedown. * * @param e {Event} Native event object */ stopPropagation : function(e){ if(e.stopPropagation){ e.stopPropagation(); } else { e.cancelBubble = true; }; }, /** * Fires a synthetic native event on the given element. * * @param target {Element} DOM element to fire event on * @param type {String} Name of the event to fire * @return {Boolean} A value that indicates whether any of the event handlers called {@link #preventDefault}. * <code>true</code> The default action is permitted, <code>false</code> the caller should prevent the default action. */ fire : function(target, type){ // dispatch for standard first if(document.createEvent){ var evt = document.createEvent("HTMLEvents"); evt.initEvent(type, true, true); return !target.dispatchEvent(evt); } else { var evt = document.createEventObject(); return target.fireEvent("on" + type, evt); }; }, /** * Whether the given target supports the given event type. * * Useful for testing for support of new features like * touch events, gesture events, orientation change, on/offline, etc. * * @signature function(target, type) * @param target {var} Any valid target e.g. window, dom node, etc. * @param type {String} Type of the event e.g. click, mousedown * @return {Boolean} Whether the given event is supported */ supportsEvent : function(target, type){ // Detecting the transitionend event's name is not possible in some // browsers, so we deduce it from the style property name instead. if(type.toLowerCase().indexOf("transitionend") != -1){ var transitionProp = qx.bom.Style.getPropertyName("transition"); if(!transitionProp){ return false; }; var endEvent = qx.lang.String.firstLow(transitionProp) + (transitionProp.indexOf("Trans") > 0 ? "E" : "e") + "nd"; return type == endEvent; }; var eventName = "on" + type; var supportsEvent = (eventName in target); if(!supportsEvent){ supportsEvent = typeof target[eventName] == "function"; if(!supportsEvent && target.setAttribute){ target.setAttribute(eventName, "return;"); supportsEvent = typeof target[eventName] == "function"; target.removeAttribute(eventName); }; }; return supportsEvent; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * EXPERIMENTAL - NOT READY FOR PRODUCTION * * Basic implementation for an event emitter. This supplies a basic and * minimalistic event mechanism. */ qx.Bootstrap.define("qx.event.Emitter", { extend : Object, statics : { /** Static storage for all event listener */ __storage : [] }, members : { __listener : null, __any : null, /** * Attach a listener to the event emitter. The given <code>name</code> * will define the type of event. Handing in a <code>'*'</code> will * listen to all events emitted by the event emitter. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ on : function(name, listener, ctx){ var id = qx.event.Emitter.__storage.length; this.__getStorage(name).push({ listener : listener, ctx : ctx, id : id }); qx.event.Emitter.__storage.push({ name : name, listener : listener, ctx : ctx }); return id; }, /** * Attach a listener to the event emitter which will be executed only once. * The given <code>name</code> will define the type of event. Handing in a * <code>'*'</code> will listen to all events emitted by the event emitter. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ once : function(name, listener, ctx){ var id = qx.event.Emitter.__storage.length; this.__getStorage(name).push({ listener : listener, ctx : ctx, once : true, id : id }); qx.event.Emitter.__storage.push({ name : name, listener : listener, ctx : ctx }); return id; }, /** * Remove a listener from the event emitter. The given <code>name</code> * will define the type of event. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer|null} The listener's id if it was removed or * <code>null</code> if it wasn't found */ off : function(name, listener, ctx){ var storage = this.__getStorage(name); for(var i = storage.length - 1;i >= 0;i--){ var entry = storage[i]; if(entry.listener == listener && entry.ctx == ctx){ storage.splice(i, 1); qx.event.Emitter.__storage[entry.id] = null; return entry.id; }; }; return null; }, /** * Removes the listener identified by the given <code>id</code>. The id * will be return on attaching the listener and can be stored for removing. * * @param id {Integer} The id of the listener. */ offById : function(id){ var entry = qx.event.Emitter.__storage[id]; this.off(entry.name, entry.listener, entry.ctx); }, /** * Alternative for {@link #on}. * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ addListener : function(name, listener, ctx){ return this.on(name, listener, ctx); }, /** * Alternative for {@link #once}. * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ addListenerOnce : function(name, listener, ctx){ return this.once(name, listener, ctx); }, /** * Alternative for {@link #off}. * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. */ removeListener : function(name, listener, ctx){ this.off(name, listener, ctx); }, /** * Alternative for {@link #offById}. * @param id {Integer} The id of the listener. */ removeListenerById : function(id){ this.offById(id); }, /** * Emits an event with the given name. The data will be passed * to the listener. * @param name {String} The name of the event to emit. * @param data {var?undefined} The data which should be passed to the listener. */ emit : function(name, data){ var storage = this.__getStorage(name); for(var i = 0;i < storage.length;i++){ var entry = storage[i]; entry.listener.call(entry.ctx, data); if(entry.once){ storage.splice(i, 1); i--; }; }; // call on any storage = this.__getStorage("*"); for(var i = storage.length - 1;i >= 0;i--){ var entry = storage[i]; entry.listener.call(entry.ctx, data); }; }, /** * Returns the internal attached listener. * @internal * @return {Map} A map which has the event name as key. The values are * arrays containing a map with 'listener' and 'ctx'. */ getListeners : function(){ return this.__listener; }, /** * Internal helper which will return the storage for the given name. * @param name {String} The name of the event. * @return {Array} An array which is the storage for the listener and * the given event name. */ __getStorage : function(name){ if(this.__listener == null){ this.__listener = { }; }; if(this.__listener[name] == null){ this.__listener[name] = []; }; return this.__listener[name]; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Normalization for touch events */ qx.Bootstrap.define("qx.module.event.Touch", { statics : { /** * List of event types to be normalized * @type {Array} */ TYPES : ["tap", "swipe"], /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @param type {String} Event type * @return {Event} Normalized event object * @internal */ normalize : function(event, element, type){ if(!event){ return event; }; event._type = type; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(statics.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The class is responsible for device detection. This is specially usefull * if you are on a mobile device. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Device", { statics : { /** Maps user agent names to device IDs */ __ids : { "iPod" : "ipod", "iPad" : "ipad", "iPhone" : "iPhone", "PSP" : "psp", "PLAYSTATION 3" : "ps3", "Nintendo Wii" : "wii", "Nintendo DS" : "ds", "XBOX" : "xbox", "Xbox" : "xbox" }, /** * Returns the name of the current device if detectable. It falls back to * <code>pc</code> if the detection for other devices fails. * * @internal * @return {String} The string of the device found. */ getName : function(){ var str = []; for(var key in this.__ids){ str.push(key); }; var reg = new RegExp("(" + str.join("|").replace(/\./g, "\.") + ")", "g"); var match = reg.exec(navigator.userAgent); if(match && match[1]){ return qx.bom.client.Device.__ids[match[1]]; }; return "pc"; }, /** * Determines on what type of device the application is running. * Valid values are: "mobile", "tablet" or "desktop". * @return {String} The device type name of determined device. */ getType : function(){ return qx.bom.client.Device.detectDeviceType(navigator.userAgent); }, /** * Detects the device type, based on given userAgentString. * * @param userAgentString {String} userAgent parameter, needed for decision. * @return {String} The device type name of determined device: "mobile","desktop","tablet" */ detectDeviceType : function(userAgentString){ if(qx.bom.client.Device.detectTabletDevice(userAgentString)){ return "tablet"; } else if(qx.bom.client.Device.detectMobileDevice(userAgentString)){ return "mobile"; }; return "desktop"; }, /** * Detects if a device is a mobile phone. (Tablets excluded.) * @param userAgentString {String} userAgent parameter, needed for decision. * @return {Boolean} Flag which indicates whether it is a mobile device. */ detectMobileDevice : function(userAgentString){ return /android.+mobile|ip(hone|od)|bada\/|blackberry|maemo|opera m(ob|in)i|fennec|NetFront|phone|psp|symbian|IEMobile|windows (ce|phone)|xda/i.test(userAgentString); }, /** * Detects if a device is a tablet device. * @param userAgentString {String} userAgent parameter, needed for decision. * @return {Boolean} Flag which indicates whether it is a tablet device. */ detectTabletDevice : function(userAgentString){ var isIE10Tablet = (/MSIE 10/i.test(userAgentString)) && (/ARM/i.test(userAgentString)) && !(/windows phone/i.test(userAgentString)); var isCommonTablet = (!(/Fennec|HTC.Magic|Nexus|android.+mobile|Tablet PC/i.test(userAgentString)) && (/Android|ipad|tablet|playbook|silk|kindle|psp/i.test(userAgentString))); return isIE10Tablet || isCommonTablet; } }, defer : function(statics){ qx.core.Environment.add("device.name", statics.getName); qx.core.Environment.add("device.type", statics.getType); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Module for querying information about the environment / runtime. * It adds a static key <code>env</code> to qxWeb and offers the given methods. * * <pre class="javascript"> * q.env.get("engine.name"); // return "webkit" e.g. * </pre> * * The following values are predefined: * * * <code>browser.name</code> : The name of the browser * * <code>browser.version</code> : The version of the browser * * <code>browser.quirksmode</code> : <code>true</code> if the browser is in quirksmode * * <code>browser.documentmode</code> : The document mode of the browser * * * <code>device.name</code> : The name of the device e.g. <code>iPad</code>. * * <code>device.type</code> : Either <code>desktop</code>, <code>tablet</code> or <code>mobile</code>. * * * <code>engine.name</code> : The name of the browser engine * * <code>engine.version</code> : The version of the browser engine */ qx.Bootstrap.define("qx.module.Environment", { statics : { /** * Get the value stored for the given key. * * @attachStatic {qxWeb, env.get} * @param key {String} The key to check for. * @return {var} The value stored for the given key. * @lint environmentNonLiteralKey(key) */ get : function(key){ return qx.core.Environment.get(key); }, /** * Adds a new environment setting which can be queried via {@link #get}. * @param key {String} The key to store the value for. * * @attachStatic {qxWeb, env.add} * @param value {var} The value to store. * @return {qxWeb} The collection for chaining. */ add : function(key, value){ qx.core.Environment.add(key, value); return this; } }, defer : function(statics){ // make sure the desired keys are available (browser.* and engine.*) qx.core.Environment.get("browser.name"); qx.core.Environment.get("browser.version"); qx.core.Environment.get("browser.quirksmode"); qx.core.Environment.get("browser.documentmode"); qx.core.Environment.get("engine.name"); qx.core.Environment.get("engine.version"); qx.core.Environment.get("device.type"); qxWeb.$attachStatic({ "env" : { get : statics.get, add : statics.add } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Environment) #require(qx.module.Event) ************************************************************************ */ /** * Normalization for native mouse events */ qx.Bootstrap.define("qx.module.event.Mouse", { statics : { /** * List of event types to be normalized */ TYPES : ["click", "dblclick", "mousedown", "mouseup", "mouseover", "mousemove", "mouseout"], /** * List qx.module.event.Mouse methods to be attached to native mouse event * objects * @internal */ BIND_METHODS : ["getButton", "getViewportLeft", "getViewportTop", "getDocumentLeft", "getDocumentTop", "getScreenLeft", "getScreenTop"], /** * Standard mouse button mapping */ BUTTONS_DOM2 : { '0' : "left", '2' : "right", '1' : "middle" }, /** * Legacy Internet Explorer mouse button mapping */ BUTTONS_MSHTML : { '1' : "left", '2' : "right", '4' : "middle" }, /** * Returns the identifier of the mouse button that change state when the * event was triggered * * @return {String} One of <code>left</code>, <code>right</code> or * <code>middle</code> */ getButton : function(){ switch(this.type){case "contextmenu": return "right";case "click": // IE does not support buttons on click --> assume left button if(qxWeb.env.get("browser.name") === "ie" && qxWeb.env.get("browser.documentmode") < 9){ return "left"; };default: if(this.target !== undefined){ return qx.module.event.Mouse.BUTTONS_DOM2[this.button] || "none"; } else { return qx.module.event.Mouse.BUTTONS_MSHTML[this.button] || "none"; };}; }, /** * Get the horizontal coordinate at which the event occurred relative * to the viewport. * * @return {Number} The horizontal mouse position */ getViewportLeft : function(){ return this.clientX; }, /** * Get the vertical coordinate at which the event occurred relative * to the viewport. * * @return {Number} The vertical mouse position * @signature function() */ getViewportTop : function(){ return this.clientY; }, /** * Get the horizontal position at which the event occurred relative to the * left of the document. This property takes into account any scrolling of * the page. * * @return {Number} The horizontal mouse position in the document. */ getDocumentLeft : function(){ if(this.pageX !== undefined){ return this.pageX; } else { var win = qx.dom.Node.getWindow(this.srcElement); return this.clientX + qx.bom.Viewport.getScrollLeft(win); }; }, /** * Get the vertical position at which the event occurred relative to the * top of the document. This property takes into account any scrolling of * the page. * * @return {Number} The vertical mouse position in the document. */ getDocumentTop : function(){ if(this.pageY !== undefined){ return this.pageY; } else { var win = qx.dom.Node.getWindow(this.srcElement); return this.clientY + qx.bom.Viewport.getScrollTop(win); }; }, /** * Get the horizontal coordinate at which the event occurred relative to * the origin of the screen coordinate system. * * Note: This value is usually not very useful unless you want to * position a native popup window at this coordinate. * * @return {Number} The horizontal mouse position on the screen. */ getScreenLeft : function(){ return this.screenX; }, /** * Get the vertical coordinate at which the event occurred relative to * the origin of the screen coordinate system. * * Note: This value is usually not very useful unless you want to * position a native popup window at this coordinate. * * @return {Number} The vertical mouse position on the screen. */ getScreenTop : function(){ return this.screenY; }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @return {Event} Normalized event object * @internal */ normalize : function(event, element){ if(!event){ return event; }; var bindMethods = qx.module.event.Mouse.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Mouse[bindMethods[i]].bind(event); }; }; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(qx.module.event.Mouse.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tino Butz (tbtz) * Martin Wittemann (wittemann) ************************************************************************ */ /** * Define messages to react on certain channels. * * The channel names will be used in the {@link #on} method to define handlers which will * be called on certain channels and routes. The {@link #emit} method can be used * to execute a given route on a channel. {@link #onAny} defines a handler on any channel. * * *Example* * * Here is a little example of how to use the messaging. * * <pre class='javascript'> * var m = new qx.event.Messaging(); * * m.on("get", "/address/{id}", function(data) { * var id = data.params.id; // 1234 * // do something with the id... * },this); * * m.emit("get", "/address/1234"); * </pre> */ qx.Bootstrap.define("qx.event.Messaging", { construct : function(){ this._listener = { },this.__listenerIdCount = 0; this.__channelToIdMapping = { }; }, members : { _listener : null, __listenerIdCount : null, __channelToIdMapping : null, /** * Adds a route handler for the given channel. The route is called * if the {@link #emit} method finds a match. * * @param channel {String} The channel of the message. * @param type {String|RegExp} The type, used for checking if the executed path matches. * @param handler {Function} The handler to call if the route matches the executed path. * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. */ on : function(channel, type, handler, scope){ return this._addListener(channel, type, handler, scope); }, /** * Adds a handler for the "any" channel. The "any" channel is called * before all other channels. * * @param type {String|RegExp} The route, used for checking if the executed path matches * @param handler {Function} The handler to call if the route matches the executed path * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. */ onAny : function(type, handler, scope){ return this._addListener("any", type, handler, scope); }, /** * Adds a listener for a certain channel. * * @param channel {String} The channel the route should be registered for * @param type {String|RegExp} The type, used for checking if the executed path matches * @param handler {Function} The handler to call if the route matches the executed path * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. */ _addListener : function(channel, type, handler, scope){ var listeners = this._listener[channel] = this._listener[channel] || { }; var id = this.__listenerIdCount++; var params = []; var param = null; // Convert the route to a regular expression. if(qx.lang.Type.isString(type)){ var paramsRegexp = /\{([\w\d]+)\}/g; while((param = paramsRegexp.exec(type)) !== null){ params.push(param[1]); }; type = new RegExp("^" + type.replace(paramsRegexp, "([^\/]+)") + "$"); }; listeners[id] = { regExp : type, params : params, handler : handler, scope : scope }; this.__channelToIdMapping[id] = channel; return id; }, /** * Removes a registered listener by the given id. * * @param id {String} The id of the registered listener. */ remove : function(id){ var channel = this.__channelToIdMapping[id]; var listener = this._listener[channel]; delete listener[id]; delete this.__channelToIdMapping[id]; }, /** * Sends a message on the given channel and informs all matching route handlers. * * @param channel {String} The channel of the message. * @param path {String} The path to execute * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated */ emit : function(channel, path, params, customData){ this._emit(channel, path, params, customData); }, /** * Executes a certain channel with a given path. Informs all * route handlers that match with the path. * * @param channel {String} The channel to execute. * @param path {String} The path to check * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated */ _emit : function(channel, path, params, customData){ var listenerMatchedAny = false; var listener = this._listener["any"]; listenerMatchedAny = this._emitListeners(channel, path, listener, params, customData); var listenerMatched = false; listener = this._listener[channel]; listenerMatched = this._emitListeners(channel, path, listener, params, customData); if(!listenerMatched && !listenerMatchedAny){ qx.Bootstrap.info("No listener found for " + path); }; }, /** * Executes all given listener for a certain channel. Checks all listeners if they match * with the given path and executes the stored handler of the matching route. * * @param channel {String} The channel to execute. * @param path {String} The path to check * @param listeners {Map[]} All routes to test and execute. * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated * * @return {Boolean} Whether the route has been executed */ _emitListeners : function(channel, path, listeners, params, customData){ if(!listeners || qx.lang.Object.isEmpty(listeners)){ return false; }; var listenerMatched = false; for(var id in listeners){ var listener = listeners[id]; listenerMatched |= this._emitRoute(channel, path, listener, params, customData); }; return listenerMatched; }, /** * Executes a certain listener. Checks if the listener matches the given path and * executes the stored handler of the route. * * @param channel {String} The channel to execute. * @param path {String} The path to check * @param listener {Map} The route data. * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated * * @return {Boolean} Whether the route has been executed */ _emitRoute : function(channel, path, listener, params, customData){ var match = listener.regExp.exec(path); if(match){ var params = params || { }; var param = null; var value = null; match.shift(); // first match is the whole path for(var i = 0;i < match.length;i++){ value = match[i]; param = listener.params[i]; if(param){ params[param] = value; } else { params[i] = value; }; }; listener.handler.call(listener.scope, { path : path, params : params, customData : customData }); }; return match != undefined; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.event.Messaging#on) #require(qx.event.Messaging#onAny) #require(qx.event.Messaging#remove) #require(qx.event.Messaging#emit) ************************************************************************ */ /** * Define messages to react on certain channels. * * The channel names will be used in the q.messaging.on method to define handlers which will * be called on certain channels and routes. The q.messaging.emit method can be used * to execute a given route on a channel. q.messaging.onAny defines a handler on any channel. */ qx.Bootstrap.define("qx.module.Messaging", { statics : { /** * Adds a route handler for the given channel. The route is called * if the {@link #emit} method finds a match. * * @attachStatic{qxWeb, messaging.on} * @param channel {String} The channel of the message. * @param type {String|RegExp} The type, used for checking if the executed path matches. * @param handler {Function} The handler to call if the route matches the executed path. * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. * @signature function(channel, type, handler, scope) */ on : null, /** * Adds a handler for the "any" channel. The "any" channel is called * before all other channels. * * @attachStatic{qxWeb, messaging.onAny} * @param type {String|RegExp} The route, used for checking if the executed path matches * @param handler {Function} The handler to call if the route matches the executed path * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. * @signature function(type, handler, scope) */ onAny : null, /** * Removes a registered listener by the given id. * * @attachStatic{qxWeb, messaging.remove} * @param id {String} The id of the registered listener. * @signature function(id) */ remove : null, /** * Sends a message on the given channel and informs all matching route handlers. * * @attachStatic{qxWeb, messaging.emit} * @param channel {String} The channel of the message. * @param path {String} The path to execute * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated * @signature function(channel, path, params, customData) */ emit : null }, defer : function(statics){ qxWeb.$attachStatic({ "messaging" : new qx.event.Messaging() }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Utility module to give some support to work with arrays. */ qx.Bootstrap.define("qx.module.util.Array", { statics : { /** * Converts an array like object to any other array like * object. * * Attention: The returned array may be same * instance as the incoming one if the constructor is identical! * * @signature function(object, constructor, offset) * @attachStatic {qxWeb, array.cast} * * @param object {var} any array-like object * @param constructor {Function} constructor of the new instance * @param offset {Number?0} position to start from * @return {Array} the converted array */ cast : qx.lang.Array.cast, /** * Check whether the two arrays have the same content. Checks only the * equality of the arrays' content. * * @signature function(arr1, arr2) * @attachStatic {qxWeb, array.equals} * * @param arr1 {Array} first array * @param arr2 {Array} second array * @return {Boolean} Whether the two arrays are equal */ equals : qx.lang.Array.equals, /** * Modifies the first array as it removes all elements * which are listed in the second array as well. * * @signature function(arr1, arr2) * @attachStatic {qxWeb, array.exclude} * * @param arr1 {Array} the array * @param arr2 {Array} the elements of this array will be excluded from the other one * @return {Array} The modified array. */ exclude : qx.lang.Array.exclude, /** * Convert an arguments object into an array. * * @signature function(args, offset) * @attachStatic {qxWeb, array.fromArguments} * * @param args {arguments} arguments object * @param offset {Number?0} position to start from * @return {Array} a newly created array (copy) with the content of the arguments object. */ fromArguments : qx.lang.Array.fromArguments, /** * Insert an element into the array after a given second element. * * @signature function(arr, obj, obj2) * @attachStatic {qxWeb, array.insertAfter} * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 after this object * @return {Array} The given array. */ insertAfter : qx.lang.Array.insertAfter, /** * Insert an element into the array before a given second element. * * @signature function(arr, obj, obj2) * @attachStatic {qxWeb, array.insertBefore} * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 before this object * @return {Array} The given array. */ insertBefore : qx.lang.Array.insertBefore, /** * Returns the highest value in the given array. Supports * numeric values only. * * @signature function(arr) * @attachStatic {qxWeb, array.max} * * @param arr {Array} Array to process. * @return {Number | undefined} The highest of all values or undefined if array is empty. */ max : qx.lang.Array.max, /** * Returns the lowest value in the given array. Supports * numeric values only. * * @signature function(arr) * @attachStatic {qxWeb, array.min} * * @param arr {Array} Array to process. * @return {Number | undefined} The lowest of all values or undefined if array is empty. */ min : qx.lang.Array.min, /** * Remove an element from the array. * * @signature function(arr, obj) * @attachStatic {qxWeb, array.remove} * * @param arr {Array} the array * @param obj {var} element to be removed from the array * @return {var} the removed element */ remove : qx.lang.Array.remove, /** * Remove all elements from the array * * @signature function(arr) * @attachStatic {qxWeb, array.removeAll} * * @param arr {Array} the array * @return {Array} empty array */ removeAll : qx.lang.Array.removeAll, /** * Recreates an array which is free of all duplicate elements from the original. * This method do not modifies the original array! * Keep in mind that this methods deletes undefined indexes. * * @signature function(arr) * @attachStatic {qxWeb, array.unique} * * @param arr {Array} Incoming array * @return {Array} Returns a copy with no duplicates * or the original array if no duplicates were found. */ unique : qx.lang.Array.unique }, defer : function(statics){ qxWeb.$attachStatic({ array : { cast : statics.cast, equals : statics.equals, exclude : statics.exclude, fromArguments : statics.fromArguments, insertAfter : statics.insertAfter, insertBefore : statics.insertBefore, max : statics.max, min : statics.min, remove : statics.remove, removeAll : statics.removeAll, unique : statics.unique } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Utility module to give some support to work with strings. */ qx.Bootstrap.define("qx.module.util.String", { statics : { /** * Converts a hyphenated string (separated by '-') to camel case. * * Example: * <pre class='javascript'>q.string.camelCase("I-like-cookies"); //returns "ILikeCookies"</pre> * * @attachStatic {qxWeb, string.camelCase} * @param str {String} hyphenated string * @return {String} camelcase string */ camelCase : function(str){ return qx.lang.String.camelCase.call(qx.lang.String, str); }, /** * Converts a camelcased string to a hyphenated (separated by '-') string. * * Example: * <pre class='javascript'>q.string.hyphenate("weLikeCookies"); //returns "we-like-cookies"</pre> * * @attachStatic {qxWeb, string.hyphenate} * @param str {String} camelcased string * @return {String} hyphenated string */ hyphenate : function(str){ return qx.lang.String.hyphenate.call(qx.lang.String, str); }, /** * Convert the first character of the string to upper case. * * @attachStatic {qxWeb, string.firstUp} * @signature function(str) * @param str {String} the string * @return {String} the string with an upper case first character */ firstUp : qx.lang.String.firstUp, /** * Convert the first character of the string to lower case. * * @attachStatic {qxWeb, string.firstLow} * @signature function(str) * @param str {String} the string * @return {String} the string with a lower case first character */ firstLow : qx.lang.String.firstLow, /** * Check whether the string starts with the given substring. * * @attachStatic {qxWeb, string.startsWith} * @signature function(fullstr, substr) * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string starts with the given substring */ startsWith : qx.lang.String.startsWith, /** * Check whether the string ends with the given substring. * * @attachStatic {qxWeb, string.endsWith} * @signature function(fullstr, substr) * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string ends with the given substring */ endsWith : qx.lang.String.endsWith, /** * Escapes all chars that have a special meaning in regular expressions. * * @attachStatic {qxWeb, string.escapeRegexpChars} * @signature function(str) * @param str {String} the string where to escape the chars. * @return {String} the string with the escaped chars. */ escapeRegexpChars : qx.lang.String.escapeRegexpChars }, defer : function(statics){ qxWeb.$attachStatic({ string : { camelCase : statics.camelCase, hyphenate : statics.hyphenate, firstUp : statics.firstUp, firstLow : statics.firstLow, startsWith : statics.startsWith, endsWith : statics.endsWith, escapeRegexpChars : statics.escapeRegexpChars } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class is responsible for applying CSS3 transforms to the collection. * The implementation is mostly a cross browser wrapper for applying the * transforms. * The API is keep to the spec as close as possible. * * http://www.w3.org/TR/css3-3d-transforms/ */ qx.Bootstrap.define("qx.module.Transform", { statics : { /** * Method to apply multiple transforms at once to the given element. It * takes a map containing the transforms you want to apply plus the values * e.g.<code>{scale: 2, rotate: "5deg"}</code>. * The values can be either singular, which means a single value will * be added to the CSS. If you give an array, the values will be split up * and each array entry will be used for the X, Y or Z dimension in that * order e.g. <code>{scale: [2, 0.5]}</code> will result in a element * double the size in X direction and half the size in Y direction. * Make sure your browser supports all transformations you apply. * * @attach {qxWeb} * @param transforms {Map} The map containing the transforms and value. * @return {qxWeb} This reference for chaining. */ transform : function(transforms){ this.forEach(function(el){ qx.bom.element.Transform.transform(el, transforms); }); return this; }, /** * Translates by the given value. For further details, take * a look at the {@link #transform} method. * * @attach {qxWeb} * @param value {String|Array} The value to translate e.g. <code>"10px"</code>. * @return {qxWeb} This reference for chaining. */ translate : function(value){ return this.transform({ translate : value }); }, /** * Scales by the given value. For further details, take * a look at the {@link #transform} method. * * @attach {qxWeb} * @param value {Number|Array} The value to scale. * @return {qxWeb} This reference for chaining. */ scale : function(value){ return this.transform({ scale : value }); }, /** * Rotates by the given value. For further details, take * a look at the {@link #transform} method. * @param value {String|Array} The value to rotate e.g. <code>"90deg"</code>. * @return {qxWeb} This reference for chaining. */ rotate : function(value){ return this.transform({ rotate : value }); }, /** * Skews by the given value. For further details, take * a look at the {@link #transform} method. * * @attach {qxWeb} * @param value {String|Array} The value to skew e.g. <code>"90deg"</code>. * @return {qxWeb} This reference for chaining. */ skew : function(value){ return this.transform({ skew : value }); }, /** * Sets the transform-origin property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * * @attach {qxWeb} * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. * @return {qxWeb} This reference for chaining. */ setTransformOrigin : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setOrigin(el, value); }); return this; }, /** * Returns the transform-origin property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * * @attach {qxWeb} * @return {String} The set property, e.g. <code>50% 50%</code> or null, * of the collection is empty. */ getTransformOrigin : function(){ if(this[0]){ return qx.bom.element.Transform.getOrigin(this[0]); }; return ""; }, /** * Sets the transform-style property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * * @attach {qxWeb} * @param value {String} Either <code>flat</code> or <code>preserve-3d</code>. * @return {qxWeb} This reference for chaining. */ setTransformStyle : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setStyle(el, value); }); return this; }, /** * Returns the transform-style property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * * @attach {qxWeb} * @return {String} The set property, either <code>flat</code> or * <code>preserve-3d</code>. */ getTransformStyle : function(){ if(this[0]){ return qx.bom.element.Transform.getStyle(this[0]); }; return ""; }, /** * Sets the perspective property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * * @attach {qxWeb} * @param value {Number} The perspective layer. Numbers between 100 * and 5000 give the best results. * @return {qxWeb} This reference for chaining. */ setTransformPerspective : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setPerspective(el, value); }); return this; }, /** * Returns the perspective property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * * @attach {qxWeb} * @return {String} The set property, e.g. <code>500</code> */ getTransformPerspective : function(){ if(this[0]){ return qx.bom.element.Transform.getPerspective(this[0]); }; return ""; }, /** * Sets the perspective-origin property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * * @attach {qxWeb} * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. * @return {qxWeb} This reference for chaining. */ setTransformPerspectiveOrigin : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setPerspectiveOrigin(el, value); }); return this; }, /** * Returns the perspective-origin property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * * @attach {qxWeb} * @return {String} The set property, e.g. <code>50% 50%</code> */ getTransformPerspectiveOrigin : function(){ if(this[0]){ return qx.bom.element.Transform.getPerspectiveOrigin(this[0]); }; return ""; }, /** * Sets the backface-visibility property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * * @attach {qxWeb} * @param value {Boolean} <code>true</code> if the backface should be visible. * @return {qxWeb} This reference for chaining. */ setTransformBackfaceVisibility : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setBackfaceVisibility(el, value); }); return this; }, /** * Returns the backface-visibility property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * * @attach {qxWeb} * @return {Boolean} <code>true</code>, if the backface is visible. */ getTransformBackfaceVisibility : function(){ if(this[0]){ return qx.bom.element.Transform.getBackfaceVisibility(this[0]); }; return ""; } }, defer : function(statics){ qxWeb.$attach({ "transform" : statics.transform, "translate" : statics.translate, "rotate" : statics.rotate, "skew" : statics.skew, "scale" : statics.scale, "setTransformStyle" : statics.setTransformStyle, "getTransformStyle" : statics.getTransformStyle, "setTransformOrigin" : statics.setTransformOrigin, "getTransformOrigin" : statics.getTransformOrigin, "setTransformPerspective" : statics.setTransformPerspective, "getTransformPerspective" : statics.getTransformPerspective, "setTransformPerspectiveOrigin" : statics.setTransformPerspectiveOrigin, "getTransformPerspectiveOrigin" : statics.getTransformPerspectiveOrigin, "setTransformBackfaceVisibility" : statics.setTransformBackfaceVisibility, "getTransformBackfaceVisibility" : statics.getTransformBackfaceVisibility }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Responsible for checking all relevant CSS transform properties. * * Specs: * http://www.w3.org/TR/css3-2d-transforms/ * http://www.w3.org/TR/css3-3d-transforms/ * * @internal */ qx.Bootstrap.define("qx.bom.client.CssTransform", { statics : { /** * Main check method which returns an object if CSS animations are * supported. This object contains all necessary keys to work with CSS * animations. * <ul> * <li><code>name</code> The name of the css transform style</li> * <li><code>style</code> The name of the css transform-style style</li> * <li><code>origin</code> The name of the transform-origin style</li> * <li><code>3d</code> Whether 3d transforms are supported</li> * <li><code>perspective</code> The name of the perspective style</li> * <li><code>perspective-origin</code> The name of the perspective-origin style</li> * <li><code>backface-visibility</code> The name of the backface-visibility style</li> * </ul> * * @internal * @return {Object|null} The described object or null, if animations are * not supported. */ getSupport : function(){ var name = qx.bom.client.CssTransform.getName(); if(name != null){ return { "name" : name, "style" : qx.bom.client.CssTransform.getStyle(), "origin" : qx.bom.client.CssTransform.getOrigin(), "3d" : qx.bom.client.CssTransform.get3D(), "perspective" : qx.bom.client.CssTransform.getPerspective(), "perspective-origin" : qx.bom.client.CssTransform.getPerspectiveOrigin(), "backface-visibility" : qx.bom.client.CssTransform.getBackFaceVisibility() }; }; return null; }, /** * Checks for the style name used to set the transform origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getStyle : function(){ return qx.bom.Style.getPropertyName("transformStyle"); }, /** * Checks for the style name used to set the transform origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getPerspective : function(){ return qx.bom.Style.getPropertyName("perspective"); }, /** * Checks for the style name used to set the perspective origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getPerspectiveOrigin : function(){ return qx.bom.Style.getPropertyName("perspectiveOrigin"); }, /** * Checks for the style name used to set the backface visibility. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getBackFaceVisibility : function(){ return qx.bom.Style.getPropertyName("backfaceVisibility"); }, /** * Checks for the style name used to set the transform origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getOrigin : function(){ return qx.bom.Style.getPropertyName("transformOrigin"); }, /** * Checks for the style name used for transforms. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getName : function(){ return qx.bom.Style.getPropertyName("transform"); }, /** * Checks if 3D transforms are supported. * @internal * @return {Boolean} <code>true</code>, if 3D transformations are supported */ get3D : function(){ return qx.bom.client.CssTransform.getPerspective() != null; } }, defer : function(statics){ qx.core.Environment.add("css.transform", statics.getSupport); qx.core.Environment.add("css.transform.3d", statics.get3D); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class is responsible for applying CSS3 transforms to plain DOM elements. * The implementation is mostly a cross browser wrapper for applying the * transforms. * The API is keep to the spec as close as possible. * * http://www.w3.org/TR/css3-3d-transforms/ */ qx.Bootstrap.define("qx.bom.element.Transform", { statics : { /** The dimensions of the transforms */ __dimensions : ["X", "Y", "Z"], /** Internal storage of the CSS names */ __cssKeys : qx.core.Environment.get("css.transform"), /** * Method to apply multiple transforms at once to the given element. It * takes a map containing the transforms you want to apply plus the values * e.g.<code>{scale: 2, rotate: "5deg"}</code>. * The values can be either singular, which means a single value will * be added to the CSS. If you give an array, the values will be split up * and each array entry will be used for the X, Y or Z dimension in that * order e.g. <code>{scale: [2, 0.5]}</code> will result in a element * double the size in X direction and half the size in Y direction. * Make sure your browser supports all transformations you apply. * @param el {Element} The element to apply the transformation. * @param transforms {Map} The map containing the transforms and value. */ transform : function(el, transforms){ var transformCss = this.__mapToCss(transforms); if(this.__cssKeys != null){ var style = this.__cssKeys["name"]; el.style[style] = transformCss; }; }, /** * Translates the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {String|Array} The value to translate e.g. <code>"10px"</code>. */ translate : function(el, value){ this.transform(el, { translate : value }); }, /** * Scales the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {Number|Array} The value to scale. */ scale : function(el, value){ this.transform(el, { scale : value }); }, /** * Rotates the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {String|Array} The value to rotate e.g. <code>"90deg"</code>. */ rotate : function(el, value){ this.transform(el, { rotate : value }); }, /** * Skews the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {String|Array} The value to skew e.g. <code>"90deg"</code>. */ skew : function(el, value){ this.transform(el, { skew : value }); }, /** * Converts the given map to a string which could be added to a css * stylesheet. * @param transforms {Map} The transforms map. For a detailed description, * take a look at the {@link #transform} method. * @return {String} The CSS value. */ getCss : function(transforms){ var transformCss = this.__mapToCss(transforms); if(this.__cssKeys != null){ var style = this.__cssKeys["name"]; return qx.bom.Style.getCssName(style) + ":" + transformCss + ";"; }; return ""; }, /** * Sets the transform-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * @param el {Element} The dom element to set the property. * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. */ setOrigin : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["origin"]] = value; }; }, /** * Returns the transform-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * @param el {Element} The dom element to read the property. * @return {String} The set property, e.g. <code>50% 50%</code> */ getOrigin : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["origin"]]; }; return ""; }, /** * Sets the transform-style property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * @param el {Element} The dom element to set the property. * @param value {String} Either <code>flat</code> or <code>preserve-3d</code>. */ setStyle : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["style"]] = value; }; }, /** * Returns the transform-style property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * @param el {Element} The dom element to read the property. * @return {String} The set property, either <code>flat</code> or * <code>preserve-3d</code>. */ getStyle : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["style"]]; }; return ""; }, /** * Sets the perspective property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * @param el {Element} The dom element to set the property. * @param value {Number} The perspective layer. Numbers between 100 * and 5000 give the best results. */ setPerspective : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["perspective"]] = value + "px"; }; }, /** * Returns the perspective property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * @param el {Element} The dom element to read the property. * @return {String} The set property, e.g. <code>500</code> */ getPerspective : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["perspective"]]; }; return ""; }, /** * Sets the perspective-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * @param el {Element} The dom element to set the property. * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. */ setPerspectiveOrigin : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["perspective-origin"]] = value; }; }, /** * Returns the perspective-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * @param el {Element} The dom element to read the property. * @return {String} The set property, e.g. <code>50% 50%</code> */ getPerspectiveOrigin : function(el){ if(this.__cssKeys != null){ var value = el.style[this.__cssKeys["perspective-origin"]]; if(value != ""){ return value; } else { var valueX = el.style[this.__cssKeys["perspective-origin"] + "X"]; var valueY = el.style[this.__cssKeys["perspective-origin"] + "Y"]; if(valueX != ""){ return valueX + " " + valueY; }; }; }; return ""; }, /** * Sets the backface-visibility property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * @param el {Element} The dom element to set the property. * @param value {Boolean} <code>true</code> if the backface should be visible. */ setBackfaceVisibility : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["backface-visibility"]] = value ? "visible" : "hidden"; }; }, /** * Returns the backface-visibility property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * @param el {Element} The dom element to read the property. * @return {Boolean} <code>true</code>, if the backface is visible. */ getBackfaceVisibility : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["backface-visibility"]] == "visible"; }; return true; }, /** * Internal helper which converts the given transforms map to a valid CSS * string. * @param transforms {Map} A map containing the transforms. * @return {String} The CSS transforms. */ __mapToCss : function(transforms){ var value = ""; for(var func in transforms){ var params = transforms[func]; // if an array is given if(qx.Bootstrap.isArray(params)){ for(var i = 0;i < params.length;i++){ if(params[i] == undefined){ continue; }; value += func + this.__dimensions[i] + "("; value += params[i]; value += ") "; }; } else { // single value case value += func + "(" + transforms[func] + ") "; }; }; return value; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) #require(qx.bom.Event#getTarget) #require(qx.bom.Event#getRelatedTarget) ************************************************************************ */ /** * Common normalizations for native events */ qx.Bootstrap.define("qx.module.event.Native", { statics : { /** * List of event types to be normalized */ TYPES : ["*"], /** * List of qx.bom.Event methods to be attached to native event objects * @internal */ FORWARD_METHODS : ["getTarget", "getRelatedTarget"], /** * List of qx.module.event.Native methods to be attached to native event objects * @internal */ BIND_METHODS : ["preventDefault", "stopPropagation", "getType"], /** * Prevent the native default behavior of the event. */ preventDefault : function(){ try{ // this allows us to prevent some key press events in IE. // See bug #1049 this.keyCode = 0; } catch(ex) { }; this.returnValue = false; }, /** * Stops the event's propagation to the element's parent */ stopPropagation : function(){ this.cancelBubble = true; }, /** * Returns the event's type * * @return {String} event type */ getType : function(){ return this._type || this.type; }, /** * Returns the target of the event. * Example: * <pre class="javascript"> * var collection = q("div.inline"); * collection.on("click", function(e) { * var clickedElement = e.getTarget(); * }); * </pre> * * @signature function() * @return {Object} Any valid native event target */ getTarget : function(){ }, /** * Computes the related target from the native DOM event * * Example: * <pre class="javascript"> * var collection = q("div.inline"); * collection.on("mouseout", function(e) { * // when using 'mouseout' events the 'relatedTarget' is pointing to the DOM element * // the device exited to. * // Useful for scenarios you only interested if e.g. the user moved away from a * // section at the website * var exitTarget = e.getRelatedTarget(); * }); * * collection.on("mouseover", function(e){ * // when using 'mouseover' events the 'relatedTarget' is pointing to the DOM element * // the device entered from. * var earlierElement = e.getRelatedTarget(); * }); * </pre> * * @signature function() * @return {Element} The related target */ getRelatedTarget : function(){ }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @return {Event} Normalized event object * @internal */ normalize : function(event, element){ if(!event){ return event; }; var fwdMethods = qx.module.event.Native.FORWARD_METHODS; for(var i = 0,l = fwdMethods.length;i < l;i++){ event[fwdMethods[i]] = qx.lang.Function.curry(qx.bom.Event[fwdMethods[i]], event); }; var bindMethods = qx.module.event.Native.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Native[bindMethods[i]].bind(event); }; }; event.getCurrentTarget = function(){ return event.currentTarget || element; }; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(statics.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson 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 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. ************************************************************************ */ /** * Methods to operate on nodes and elements on a DOM tree. This contains * special getters to query for child nodes, siblings, etc. This class also * supports to operate on one element and reorganize the content with * the insertion of new HTML or nodes. */ qx.Bootstrap.define("qx.dom.Hierarchy", { statics : { /** * Returns the DOM index of the given node * * @param node {Node} Node to look for * @return {Integer} The DOM index */ getNodeIndex : function(node){ var index = 0; while(node && (node = node.previousSibling)){ index++; }; return index; }, /** * Returns the DOM index of the given element (ignoring non-elements) * * @param element {Element} Element to look for * @return {Integer} The DOM index */ getElementIndex : function(element){ var index = 0; var type = qx.dom.Node.ELEMENT; while(element && (element = element.previousSibling)){ if(element.nodeType == type){ index++; }; }; return index; }, /** * Return the next element to the supplied element * * "nextSibling" is not good enough as it might return a text or comment element * * @param element {Element} Starting element node * @return {Element | null} Next element node */ getNextElementSibling : function(element){ while(element && (element = element.nextSibling) && !qx.dom.Node.isElement(element)){ continue; }; return element || null; }, /** * Return the previous element to the supplied element * * "previousSibling" is not good enough as it might return a text or comment element * * @param element {Element} Starting element node * @return {Element | null} Previous element node */ getPreviousElementSibling : function(element){ while(element && (element = element.previousSibling) && !qx.dom.Node.isElement(element)){ continue; }; return element || null; }, /** * Whether the first element contains the second one * * Uses native non-standard contains() in Internet Explorer, * Opera and Webkit (supported since Safari 3.0 beta) * * @param element {Element} Parent element * @param target {Node} Child node * @return {Boolean} */ contains : function(element, target){ if(qx.core.Environment.get("html.element.contains")){ if(qx.dom.Node.isDocument(element)){ var doc = qx.dom.Node.getDocument(target); return element && doc == element; } else if(qx.dom.Node.isDocument(target)){ return false; } else { return element.contains(target); }; } else if(qx.core.Environment.get("html.element.compareDocumentPosition")){ // https://developer.mozilla.org/en-US/docs/DOM:Node.compareDocumentPosition return !!(element.compareDocumentPosition(target) & 16); } else { while(target){ if(element == target){ return true; }; target = target.parentNode; }; return false; }; }, /** * Whether the element is inserted into the document * for which it was created. * * @param element {Element} DOM element to check * @return {Boolean} <code>true</code> when the element is inserted * into the document. */ isRendered : function(element){ var doc = element.ownerDocument || element.document; if(qx.core.Environment.get("html.element.contains")){ // Fast check for all elements which are not in the DOM if(!element.parentNode || !element.offsetParent){ return false; }; return doc.body.contains(element); } else if(qx.core.Environment.get("html.element.compareDocumentPosition")){ // Gecko way, DOM3 method return !!(doc.compareDocumentPosition(element) & 16); } else { while(element){ if(element == doc.body){ return true; }; element = element.parentNode; }; return false; }; }, /** * Checks if <code>element</code> is a descendant of <code>ancestor</code>. * * @param element {Element} first element * @param ancestor {Element} second element * @return {Boolean} Element is a descendant of ancestor */ isDescendantOf : function(element, ancestor){ return this.contains(ancestor, element); }, /** * Get the common parent element of two given elements. Returns * <code>null</code> when no common element has been found. * * Uses native non-standard contains() in Opera and Internet Explorer * * @param element1 {Element} First element * @param element2 {Element} Second element * @return {Element} the found parent, if none was found <code>null</code> */ getCommonParent : function(element1, element2){ if(element1 === element2){ return element1; }; if(qx.core.Environment.get("html.element.contains")){ while(element1 && qx.dom.Node.isElement(element1)){ if(element1.contains(element2)){ return element1; }; element1 = element1.parentNode; }; return null; } else { var known = []; while(element1 || element2){ if(element1){ if(qx.lang.Array.contains(known, element1)){ return element1; }; known.push(element1); element1 = element1.parentNode; }; if(element2){ if(qx.lang.Array.contains(known, element2)){ return element2; }; known.push(element2); element2 = element2.parentNode; }; }; return null; }; }, /** * Collects all of element's ancestors and returns them as an array of * elements. * * @param element {Element} DOM element to query for ancestors * @return {Array} list of all parents */ getAncestors : function(element){ return this._recursivelyCollect(element, "parentNode"); }, /** * Returns element's children. * * @param element {Element} DOM element to query for child elements * @return {Array} list of all child elements */ getChildElements : function(element){ element = element.firstChild; if(!element){ return []; }; var arr = this.getNextSiblings(element); if(element.nodeType === 1){ arr.unshift(element); }; return arr; }, /** * Collects all of element's descendants (deep) and returns them as an array * of elements. * * @param element {Element} DOM element to query for child elements * @return {Array} list of all found elements */ getDescendants : function(element){ return qx.lang.Array.fromCollection(element.getElementsByTagName("*")); }, /** * Returns the first child that is an element. This is opposed to firstChild DOM * property which will return any node (whitespace in most usual cases). * * @param element {Element} DOM element to query for first descendant * @return {Element} the first descendant */ getFirstDescendant : function(element){ element = element.firstChild; while(element && element.nodeType != 1){ element = element.nextSibling; }; return element; }, /** * Returns the last child that is an element. This is opposed to lastChild DOM * property which will return any node (whitespace in most usual cases). * * @param element {Element} DOM element to query for last descendant * @return {Element} the last descendant */ getLastDescendant : function(element){ element = element.lastChild; while(element && element.nodeType != 1){ element = element.previousSibling; }; return element; }, /** * Collects all of element's previous siblings and returns them as an array of elements. * * @param element {Element} DOM element to query for previous siblings * @return {Array} list of found DOM elements */ getPreviousSiblings : function(element){ return this._recursivelyCollect(element, "previousSibling"); }, /** * Collects all of element's next siblings and returns them as an array of * elements. * * @param element {Element} DOM element to query for next siblings * @return {Array} list of found DOM elements */ getNextSiblings : function(element){ return this._recursivelyCollect(element, "nextSibling"); }, /** * Recursively collects elements whose relationship is specified by * property. <code>property</code> has to be a property (a method won't * do!) of element that points to a single DOM node. Returns an array of * elements. * * @param element {Element} DOM element to start with * @param property {String} property to look for * @return {Array} result list */ _recursivelyCollect : function(element, property){ var list = []; while(element = element[property]){ if(element.nodeType == 1){ list.push(element); }; }; return list; }, /** * Collects all of element's siblings and returns them as an array of elements. * * @param element {var} DOM element to start with * @return {Array} list of all found siblings */ getSiblings : function(element){ return this.getPreviousSiblings(element).reverse().concat(this.getNextSiblings(element)); }, /** * Whether the given element is empty. * Inspired by Base2 (Dean Edwards) * * @param element {Element} The element to check * @return {Boolean} true when the element is empty */ isEmpty : function(element){ element = element.firstChild; while(element){ if(element.nodeType === qx.dom.Node.ELEMENT || element.nodeType === qx.dom.Node.TEXT){ return false; }; element = element.nextSibling; }; return true; }, /** * Removes all of element's text nodes which contain only whitespace * * @param element {Element} Element to cleanup */ cleanWhitespace : function(element){ var node = element.firstChild; while(node){ var nextNode = node.nextSibling; if(node.nodeType == 3 && !/\S/.test(node.nodeValue)){ element.removeChild(node); }; node = nextNode; }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.dom.Hierarchy#getSiblings) #require(qx.dom.Hierarchy#getNextSiblings) #require(qx.dom.Hierarchy#getPreviousSiblings) ************************************************************************ */ /** * DOM traversal module */ qx.Bootstrap.define("qx.module.Traversing", { statics : { /** * Adds an element to the collection * * @attach {qxWeb} * @param el {Element} DOM element to add to the collection * @return {qxWeb} The collection for chaining */ add : function(el){ this.push(el); return this; }, /** * Gets a set of elements containing all of the unique immediate children of * each of the matched set of elements. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?null} Optional selector to match * @return {qxWeb} Collection containing the child elements */ getChildren : function(selector){ var children = []; for(var i = 0;i < this.length;i++){ var found = qx.dom.Hierarchy.getChildElements(this[i]); if(selector){ found = qx.bom.Selector.matches(selector, found); }; children = children.concat(found); }; return qxWeb.$init(children); }, /** * Executes the provided callback function once for each item in the * collection. * * @attach {qxWeb} * @param fn {Function} Callback function * @param ctx {Object} Context object * @return {qxWeb} The collection for chaining */ forEach : function(fn, ctx){ for(var i = 0;i < this.length;i++){ fn.call(ctx, this[i], i, this); }; return this; }, /** * Gets a set of elements containing the parent of each element in the * collection. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?null} Optional selector to match * @return {qxWeb} Collection containing the parent elements */ getParents : function(selector){ var parents = []; for(var i = 0;i < this.length;i++){ var found = qx.dom.Element.getParentElement(this[i]); if(selector){ found = qx.bom.Selector.matches(selector, [found]); }; parents = parents.concat(found); }; return qxWeb.$init(parents); }, /** * Gets a set of elements containing all ancestors of each element in the * collection. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param filter {String?null} Optional selector to match * @return {qxWeb} Collection containing the ancestor elements */ getAncestors : function(filter){ return this.__getAncestors(null, filter); }, /** * Gets a set of elements containing all ancestors of each element in the * collection, up to (but not including) the element matched by the provided * selector. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String} Selector that indicates where to stop including * ancestor elements * @param filter {String?null} Optional selector to match * @return {qxWeb} Collection containing the ancestor elements */ getAncestorsUntil : function(selector, filter){ return this.__getAncestors(selector, filter); }, /** * Internal helper for getAncestors and getAncestorsUntil * * @attach {qxWeb} * @param selector {String} Selector that indicates where to stop including * ancestor elements * @param filter {String?null} Optional selector to match * @return {qxWeb} Collection containing the ancestor elements * @internal */ __getAncestors : function(selector, filter){ var ancestors = []; for(var i = 0;i < this.length;i++){ var parent = qx.dom.Element.getParentElement(this[i]); while(parent){ var found = [parent]; if(selector && qx.bom.Selector.matches(selector, found).length > 0){ break; }; if(filter){ found = qx.bom.Selector.matches(filter, found); }; ancestors = ancestors.concat(found); parent = qx.dom.Element.getParentElement(parent); }; }; return qxWeb.$init(ancestors); }, /** * Gets a set containing the closest matching ancestor for each item in * the collection. * If the item itself matches, it is added to the new set. Otherwise, the * item's parent chain will be traversed until a match is found. * * @attach {qxWeb} * @param selector {String} Selector expression to match * @return {qxWeb} New collection containing the closest matching ancestors */ getClosest : function(selector){ var closest = []; var findClosest = function findClosest(current){ var found = qx.bom.Selector.matches(selector, current); if(found.length){ closest.push(found[0]); } else { current = current.getParents(); // One up if(current[0] && current[0].parentNode){ findClosest(current); }; }; }; for(var i = 0;i < this.length;i++){ findClosest(qxWeb(this[i])); }; return qxWeb.$init(closest); }, /** * Searches the child elements of each item in the collection and returns * a new collection containing the children that match the provided selector * * @attach {qxWeb} * @param selector {String} Selector expression to match the child elements * against * @return {qxWeb} New collection containing the matching child elements */ find : function(selector){ var found = []; for(var i = 0;i < this.length;i++){ found = found.concat(qx.bom.Selector.query(selector, this[i])); }; return qxWeb.$init(found); }, /** * Gets a new set of elements containing the child nodes of each item in the * current set. * * @attach {qxWeb} * @return {qxWeb} New collection containing the child nodes */ getContents : function(){ var found = []; for(var i = 0;i < this.length;i++){ found = found.concat(qx.lang.Array.fromCollection(this[i].childNodes)); }; return qxWeb.$init(found); }, /** * Checks if at least one element in the collection passes the provided * filter. This can be either a selector expression or a filter * function * * @attach {qxWeb} * @param selector {String|Function} Selector expression or filter function * @return {Boolean} <code>true</code> if at least one element matches */ is : function(selector){ if(qx.lang.Type.isFunction(selector)){ return this.filter(selector).length > 0; }; return !!selector && qx.bom.Selector.matches(selector, this).length > 0; }, /** * Reduce the set of matched elements to a single element. * * @attach {qxWeb} * @param index {Number} The position of the element in the collection * @return {qxWeb} A new collection containing one element */ eq : function(index){ return this.slice(index, +index + 1); }, /** * Reduces the collection to the first element. * * @attach {qxWeb} * @return {qxWeb} A new collection containing one element */ getFirst : function(){ return this.slice(0, 1); }, /** * Reduces the collection to the last element. * * @attach {qxWeb} * @return {qxWeb} A new collection containing one element */ getLast : function(){ return this.slice(this.length - 1); }, /** * Gets a collection containing only the elements that have descendants * matching the given selector * * @attach {qxWeb} * @param selector {String} Selector expression * @return {qxWeb} a new collection containing only elements with matching descendants */ has : function(selector){ var found = []; for(var i = 0;i < this.length;i++){ var descendants = qx.bom.Selector.matches(selector, this.eq(i).getContents()); if(descendants.length > 0){ found.push(this[i]); }; }; return qxWeb.$init(found); }, /** * Gets a collection containing the next sibling element of each item in * the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing next siblings */ getNext : function(selector){ var found = this.map(qx.dom.Hierarchy.getNextElementSibling, qx.dom.Hierarchy); if(selector){ found = qx.bom.Selector.matches(selector, found); }; return found; }, /** * Gets a collection containing all following sibling elements of each * item in the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing following siblings */ getNextAll : function(selector){ var ret = qx.module.Traversing.__hierarchyHelper(this, "getNextSiblings", selector); return qxWeb.$init(ret); }, /** * Gets a collection containing the following sibling elements of each * item in the current set (ignoring text and comment nodes) up to but not * including any element that matches the given selector. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing following siblings */ getNextUntil : function(selector){ var found = []; this.forEach(function(item, index){ var nextSiblings = qx.dom.Hierarchy.getNextSiblings(item); for(var i = 0,l = nextSiblings.length;i < l;i++){ if(qx.bom.Selector.matches(selector, [nextSiblings[i]]).length > 0){ break; }; found.push(nextSiblings[i]); }; }); return qxWeb.$init(found); }, /** * Gets a collection containing the previous sibling element of each item in * the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing previous siblings */ getPrev : function(selector){ var found = this.map(qx.dom.Hierarchy.getPreviousElementSibling, qx.dom.Hierarchy); if(selector){ found = qx.bom.Selector.matches(selector, found); }; return found; }, /** * Gets a collection containing all preceding sibling elements of each * item in the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing preceding siblings */ getPrevAll : function(selector){ var ret = qx.module.Traversing.__hierarchyHelper(this, "getPreviousSiblings", selector); return qxWeb.$init(ret); }, /** * Gets a collection containing the preceding sibling elements of each * item in the current set (ignoring text and comment nodes) up to but not * including any element that matches the given selector. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing preceding siblings */ getPrevUntil : function(selector){ var found = []; this.forEach(function(item, index){ var previousSiblings = qx.dom.Hierarchy.getPreviousSiblings(item); for(var i = 0,l = previousSiblings.length;i < l;i++){ if(qx.bom.Selector.matches(selector, [previousSiblings[i]]).length > 0){ break; }; found.push(previousSiblings[i]); }; }); return qxWeb.$init(found); }, /** * Gets a collection containing all sibling elements of the items in the * current set. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing sibling elements */ getSiblings : function(selector){ var ret = qx.module.Traversing.__hierarchyHelper(this, "getSiblings", selector); return qxWeb.$init(ret); }, /** * Remove elements from the collection that do not pass the given filter. * This can be either a selector expression or a filter function * * @attach {qxWeb} * @param selector {String|Function} Selector or filter function * @return {qxWeb} Reduced collection */ not : function(selector){ if(qx.lang.Type.isFunction(selector)){ return this.filter(function(item, index, obj){ return !selector(item, index, obj); }); }; var res = qx.bom.Selector.matches(selector, this); return this.filter(function(value){ return res.indexOf(value) === -1; }); }, /** * Gets a new collection containing the offset parent of each item in the * current set. * * @attach {qxWeb} * @return {qxWeb} New collection containing offset parents */ getOffsetParent : function(){ return this.map(qx.bom.element.Location.getOffsetParent); }, /** * Whether the first element in the collection is inserted into * the document for which it was created. * * @return {Boolean} <code>true</code> when the element is inserted * into the document. */ isRendered : function(){ if(!this[0]){ return false; }; return qx.dom.Hierarchy.isRendered(this[0]); }, /** * Checks if the given object is a DOM element * * @attachStatic{qxWeb} * @param element {Object} Object to check * @return {Boolean} <code>true</code> if the object is a DOM element */ isElement : function(element){ return qx.dom.Node.isElement(element); }, /** * Checks if the given object is a DOM node * * @attachStatic{qxWeb} * @param node {Object} Object to check * @return {Boolean} <code>true</code> if the object is a DOM node */ isNode : function(node){ return qx.dom.Node.isNode(node); }, /** * Checks if the given object is a DOM document object * * @attachStatic{qxWeb} * @param node {Object} Object to check * @return {Boolean} <code>true</code> if the object is a DOM document */ isDocument : function(node){ return qx.dom.Node.isDocument(node); }, /** * Returns the DOM2 <code>defaultView</code> (window) for the given node. * * @attachStatic{qxWeb} * @param node {Node|Document|Window} Node to inspect * @return {Window} the <code>defaultView</code> for the given node */ getWindow : function(node){ return qx.dom.Node.getWindow(node); }, /** * Returns the owner document of the given node * * @attachStatic{qxWeb} * @param node {Node } Node to get the document for * @return {Document|null} The document of the given DOM node */ getDocument : function(node){ return qx.dom.Node.getDocument(node); }, /** * Helper function that iterates over a set of items and applies the given * qx.dom.Hierarchy method to each entry, storing the results in a new Array. * Duplicates are removed and the items are filtered if a selector is * provided. * * @attach{qxWeb} * @param collection {Array} Collection to iterate over (any Array-like object) * @param method {String} Name of the qx.dom.Hierarchy method to apply * @param selector {String?} Optional selector that elements to be included * must match * @return {Array} Result array * @internal */ __hierarchyHelper : function(collection, method, selector){ // Iterate ourself, as we want to directly combine the result var all = []; var Hierarchy = qx.dom.Hierarchy; for(var i = 0,l = collection.length;i < l;i++){ all.push.apply(all, Hierarchy[method](collection[i])); }; // Remove duplicates var ret = qx.lang.Array.unique(all); // Post reduce result by selector if(selector){ ret = qx.bom.Selector.matches(selector, ret); }; return ret; } }, defer : function(statics){ qxWeb.$attach({ "add" : statics.add, "getChildren" : statics.getChildren, "forEach" : statics.forEach, "getParents" : statics.getParents, "getAncestors" : statics.getAncestors, "getAncestorsUntil" : statics.getAncestorsUntil, "__getAncestors" : statics.__getAncestors, "getClosest" : statics.getClosest, "find" : statics.find, "getContents" : statics.getContents, "is" : statics.is, "eq" : statics.eq, "getFirst" : statics.getFirst, "getLast" : statics.getLast, "has" : statics.has, "getNext" : statics.getNext, "getNextAll" : statics.getNextAll, "getNextUntil" : statics.getNextUntil, "getPrev" : statics.getPrev, "getPrevAll" : statics.getPrevAll, "getPrevUntil" : statics.getPrevUntil, "getSiblings" : statics.getSiblings, "not" : statics.not, "getOffsetParent" : statics.getOffsetParent, "isRendered" : statics.isRendered }); qxWeb.$attachStatic({ "isElement" : statics.isElement, "isNode" : statics.isNode, "isDocument" : statics.isDocument, "getDocument" : statics.getDocument, "getWindow" : statics.getWindow }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /** * Attribute/Property handling for DOM elements. */ qx.Bootstrap.define("qx.module.Attribute", { statics : { /** * Returns the HTML content of the first item in the collection * @attach {qxWeb} * @return {String|null} HTML content or null if the collection is empty */ getHtml : function(){ if(this[0]){ return qx.bom.element.Attribute.get(this[0], "html"); }; return null; }, /** * Sets the HTML content of each item in the collection * * @attach {qxWeb} * @param html {String} HTML string * @return {qxWeb} The collection for chaining */ setHtml : function(html){ html = qx.bom.Html.fixEmptyTags(html); for(var i = 0;i < this.length;i++){ qx.bom.element.Attribute.set(this[i], "html", html); }; return this; }, /** * Sets an HTML attribute on each item in the collection * * @attach {qxWeb} * @param name {String} Attribute name * @param value {var} Attribute value * @return {qxWeb} The collection for chaining */ setAttribute : function(name, value){ for(var i = 0;i < this.length;i++){ qx.bom.element.Attribute.set(this[i], name, value); }; return this; }, /** * Returns the value of the given attribute for the first item in the * collection. * * @attach {qxWeb} * @param name {String} Attribute name * @return {var} Attribute value */ getAttribute : function(name){ if(this[0]){ return qx.bom.element.Attribute.get(this[0], name); }; return null; }, /** * Removes the given attribute from all elements in the collection * * @attach {qxWeb} * @param name {String} Attribute name * @return {qxWeb} The collection for chaining */ removeAttribute : function(name){ for(var i = 0;i < this.length;i++){ qx.bom.element.Attribute.set(this[i], name, null); }; return this; }, /** * Sets multiple attributes for each item in the collection. * * @attach {qxWeb} * @param attributes {Map} A map of attribute name/value pairs * @return {qxWeb} The collection for chaining */ setAttributes : function(attributes){ for(var name in attributes){ this.setAttribute(name, attributes[name]); }; return this; }, /** * Returns the values of multiple attributes for the first item in the collection * * @attach {qxWeb} * @param names {String[]} List of attribute names * @return {Map} Map of attribute name/value pairs */ getAttributes : function(names){ var attributes = { }; for(var i = 0;i < names.length;i++){ attributes[names[i]] = this.getAttribute(names[i]); }; return attributes; }, /** * Removes multiple attributes from each item in the collection. * * @attach {qxWeb} * @param attributes {String[]} List of attribute names * @return {qxWeb} The collection for chaining */ removeAttributes : function(attributes){ for(var i = 0,l = attributes.length;i < l;i++){ this.removeAttribute(attributes[i]); }; return this; }, /** * Sets a property on each item in the collection * * @attach {qxWeb} * @param name {String} Property name * @param value {var} Property value * @return {qxWeb} The collection for chaining */ setProperty : function(name, value){ for(var i = 0;i < this.length;i++){ this[i][name] = value; }; return this; }, /** * Returns the value of the given property for the first item in the * collection * * @attach {qxWeb} * @param name {String} Property name * @return {var} Property value */ getProperty : function(name){ if(this[0]){ return this[0][name]; }; return null; }, /** * Sets multiple properties for each item in the collection. * * @attach {qxWeb} * @param properties {Map} A map of property name/value pairs * @return {qxWeb} The collection for chaining */ setProperties : function(properties){ for(var name in properties){ this.setProperty(name, properties[name]); }; return this; }, /** * Returns the values of multiple properties for the first item in the collection * * @attach {qxWeb} * @param names {String[]} List of property names * @return {Map} Map of property name/value pairs */ getProperties : function(names){ var properties = { }; for(var i = 0;i < names.length;i++){ properties[names[i]] = this.getProperty(names[i]); }; return properties; }, /** * Returns the currently configured value for the first item in the collection. * Works with simple input fields as well as with select boxes or option * elements. Returns an array for select boxes with multi selection. In all * other cases, a string is returned. * * @attach {qxWeb} * @return {String|Array} */ getValue : function(){ if(this[0]){ return qx.bom.Input.getValue(this[0]); }; return null; }, /** * Applies the given value to each element in the collection. * Normally the value is given as a string/number value and applied to the * field content (textfield, textarea) or used to detect whether the field * is checked (checkbox, radiobutton). * Supports array values for selectboxes (multiple selection) and checkboxes * or radiobuttons (for convenience). * Please note: To modify the value attribute of a checkbox or radiobutton * use @link{#set} instead. * * @attach {qxWeb} * @param value {String|Number|Array} The value to apply * @return {qxWeb} The collection for chaining */ setValue : function(value){ for(var i = 0,l = this.length;i < l;i++){ qx.bom.Input.setValue(this[i], value); }; return this; } }, defer : function(statics){ qxWeb.$attach({ "getHtml" : statics.getHtml, "setHtml" : statics.setHtml, "getAttribute" : statics.getAttribute, "setAttribute" : statics.setAttribute, "removeAttribute" : statics.removeAttribute, "getAttributes" : statics.getAttributes, "setAttributes" : statics.setAttributes, "removeAttributes" : statics.removeAttributes, "getProperty" : statics.getProperty, "setProperty" : statics.setProperty, "getProperties" : statics.getProperties, "setProperties" : statics.setProperties, "getValue" : statics.getValue, "setValue" : statics.setValue }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 Sebastian Werner, http://sebastian-werner.net License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * jQuery http://jquery.com Version 1.3.1 Copyright: 2009 John Resig License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #ignore(qxWeb) ************************************************************************ */ /** * This class is mainly a convenience wrapper for DOM elements to * qooxdoo's event system. */ qx.Bootstrap.define("qx.bom.Html", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Helper method for XHTML replacement. * * @param all {String} Complete string * @param front {String} Front of the match * @param tag {String} Tag name * @return {String} XHTML corrected tag */ __fixNonDirectlyClosableHelper : function(all, front, tag){ return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ? all : front + "></" + tag + ">"; }, /** {Map} Contains wrap fragments for specific HTML matches */ __convertMap : { opt : [1, "<select multiple='multiple'>", "</select>"], // option or optgroup leg : [1, "<fieldset>", "</fieldset>"], table : [1, "<table>", "</table>"], tr : [2, "<table><tbody>", "</tbody></table>"], td : [3, "<table><tbody><tr>", "</tr></tbody></table>"], col : [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], def : qx.core.Environment.select("engine.name", { "mshtml" : [1, "div<div>", "</div>"], "default" : null }) }, /** * Fixes "XHTML"-style tags in all browsers. * Replaces tags which are not allowed to be closed directly such as * <code>div</code> or <code>p</code>. They are patched to use opening and * closing tags instead, e.g. <code>&lt;p&gt;</code> => <code>&lt;p&gt;&lt;/p&gt;</code> * * @param html {String} HTML to fix * @return {String} Fixed HTML */ fixEmptyTags : function(html){ return html.replace(/(<(\w+)[^>]*?)\/>/g, this.__fixNonDirectlyClosableHelper); }, /** * Translates a HTML string into an array of elements. * * @param html {String} HTML string * @param context {Document} Context document in which (helper) elements should be created * @return {Array} List of resulting elements */ __convertHtmlString : function(html, context){ var div = context.createElement("div"); html = qx.bom.Html.fixEmptyTags(html); // Trim whitespace, otherwise indexOf won't work as expected var tags = html.replace(/^\s+/, "").substring(0, 5).toLowerCase(); // Auto-wrap content into required DOM structure var wrap,map = this.__convertMap; if(!tags.indexOf("<opt")){ wrap = map.opt; } else if(!tags.indexOf("<leg")){ wrap = map.leg; } else if(tags.match(/^<(thead|tbody|tfoot|colg|cap)/)){ wrap = map.table; } else if(!tags.indexOf("<tr")){ wrap = map.tr; } else if(!tags.indexOf("<td") || !tags.indexOf("<th")){ wrap = map.td; } else if(!tags.indexOf("<col")){ wrap = map.col; } else { wrap = map.def; };;;;; // Omit string concat when no wrapping is needed if(wrap){ // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + html + wrap[2]; // Move to the right depth var depth = wrap[0]; while(depth--){ div = div.lastChild; }; } else { div.innerHTML = html; }; // Fix IE specific bugs if((qx.core.Environment.get("engine.name") == "mshtml")){ // Remove IE's autoinserted <tbody> from table fragments // String was a <table>, *may* have spurious <tbody> var hasBody = /<tbody/i.test(html); // String was a bare <thead> or <tfoot> var tbody = !tags.indexOf("<table") && !hasBody ? div.firstChild && div.firstChild.childNodes : wrap[1] == "<table>" && !hasBody ? div.childNodes : []; for(var j = tbody.length - 1;j >= 0;--j){ if(tbody[j].tagName.toLowerCase() === "tbody" && !tbody[j].childNodes.length){ tbody[j].parentNode.removeChild(tbody[j]); }; }; // IE completely kills leading whitespace when innerHTML is used if(/^\s/.test(html)){ div.insertBefore(context.createTextNode(html.match(/^\s*/)[0]), div.firstChild); }; }; return qx.lang.Array.fromCollection(div.childNodes); }, /** * Cleans-up the given HTML and append it to a fragment * * When no <code>context</code> is given the global document is used to * create new DOM elements. * * When a <code>fragment</code> is given the nodes are appended to this * fragment except the script tags. These are returned in a separate Array. * * Please note: HTML coming from user input must be validated prior * to passing it to this method. HTML is temporarily inserted to the DOM * using <code>innerHTML</code>. As a consequence, scripts included in * attribute event handlers may be executed. * * @param objs {Element[]|String[]} Array of DOM elements or HTML strings * @param context {Document?document} Context in which the elements should be created * @param fragment {Element?null} Document fragment to appends elements to * @return {Element[]} Array of elements (when a fragment is given it only contains script elements) */ clean : function(objs, context, fragment){ context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if(typeof context.createElement === "undefined"){ context = context.ownerDocument || context[0] && context[0].ownerDocument || document; }; // Fast-Path: // If a single string is passed in and it's a single tag // just do a createElement and skip the rest if(!fragment && objs.length === 1 && typeof objs[0] === "string"){ var match = /^<(\w+)\s*\/?>$/.exec(objs[0]); if(match){ return [context.createElement(match[1])]; }; }; // Interate through items in incoming array var obj,ret = []; for(var i = 0,l = objs.length;i < l;i++){ obj = objs[i]; // Convert HTML string into DOM nodes if(typeof obj === "string"){ obj = this.__convertHtmlString(obj, context); }; // Append or merge depending on type if(obj.nodeType){ ret.push(obj); } else if(obj instanceof qx.type.BaseArray || (typeof qxWeb !== "undefined" && obj instanceof qxWeb)){ ret.push.apply(ret, Array.prototype.slice.call(obj, 0)); } else if(obj.toElement){ ret.push(obj.toElement()); } else { ret.push.apply(ret, obj); };; }; // Append to fragment and filter out scripts... or... if(fragment){ var scripts = [],elem; for(var i = 0;ret[i];i++){ elem = ret[i]; if(elem.nodeType == 1 && elem.tagName.toLowerCase() === "script" && (!elem.type || elem.type.toLowerCase() === "text/javascript")){ // Trying to remove the element from DOM if(elem.parentNode){ elem.parentNode.removeChild(ret[i]); }; // Store in script list scripts.push(elem); } else { if(elem.nodeType === 1){ // Recursively search for scripts and append them to the list of elements to process var scriptList = qx.lang.Array.fromCollection(elem.getElementsByTagName("script")); ret.splice.apply(ret, [i + 1, 0].concat(scriptList)); }; // Finally append element to fragment fragment.appendChild(elem); }; }; return scripts; }; // Otherwise return the array of all elements return ret; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * jQuery http://jquery.com Version 1.3.1 Copyright: 2009 John Resig License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #require(qx.lang.Array#contains) ************************************************************************ */ /** * Cross browser abstractions to work with input elements. */ qx.Bootstrap.define("qx.bom.Input", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** {Map} Internal data structures with all supported input types */ __types : { text : 1, textarea : 1, select : 1, checkbox : 1, radio : 1, password : 1, hidden : 1, submit : 1, image : 1, file : 1, search : 1, reset : 1, button : 1 }, /** * Creates an DOM input/textarea/select element. * * Attributes may be given directly with this call. This is critical * for some attributes e.g. name, type, ... in many clients. * * Note: <code>select</code> and <code>textarea</code> elements are created * using the identically named <code>type</code>. * * @param type {String} Any valid type for HTML, <code>select</code> * and <code>textarea</code> * @param attributes {Map} Map of attributes to apply * @param win {Window} Window to create the element for * @return {Element} The created input node */ create : function(type, attributes, win){ { }; // Work on a copy to not modify given attributes map var attributes = attributes ? qx.lang.Object.clone(attributes) : { }; var tag; if(type === "textarea" || type === "select"){ tag = type; } else { tag = "input"; attributes.type = type; }; return qx.dom.Element.create(tag, attributes, win); }, /** * Applies the given value to the element. * * Normally the value is given as a string/number value and applied * to the field content (textfield, textarea) or used to * detect whether the field is checked (checkbox, radiobutton). * * Supports array values for selectboxes (multiple-selection) * and checkboxes or radiobuttons (for convenience). * * Please note: To modify the value attribute of a checkbox or * radiobutton use {@link qx.bom.element.Attribute#set} instead. * * @param element {Element} element to update * @param value {String|Number|Array} the value to apply */ setValue : function(element, value){ var tag = element.nodeName.toLowerCase(); var type = element.type; var Array = qx.lang.Array; var Type = qx.lang.Type; if(typeof value === "number"){ value += ""; }; if((type === "checkbox" || type === "radio")){ if(Type.isArray(value)){ element.checked = Array.contains(value, element.value); } else { element.checked = element.value == value; }; } else if(tag === "select"){ var isArray = Type.isArray(value); var options = element.options; var subel,subval; for(var i = 0,l = options.length;i < l;i++){ subel = options[i]; subval = subel.getAttribute("value"); if(subval == null){ subval = subel.text; }; subel.selected = isArray ? Array.contains(value, subval) : value == subval; }; if(isArray && value.length == 0){ element.selectedIndex = -1; }; } else if((type === "text" || type === "textarea") && (qx.core.Environment.get("engine.name") == "mshtml")){ // These flags are required to detect self-made property-change // events during value modification. They are used by the Input // event handler to filter events. element.$$inValueSet = true; element.value = value; element.$$inValueSet = null; } else { element.value = value; };; }, /** * Returns the currently configured value. * * Works with simple input fields as well as with * select boxes or option elements. * * Returns an array in cases of multi-selection in * select boxes but in all other cases a string. * * @param element {Element} DOM element to query * @return {String|Array} The value of the given element */ getValue : function(element){ var tag = element.nodeName.toLowerCase(); if(tag === "option"){ return (element.attributes.value || { }).specified ? element.value : element.text; }; if(tag === "select"){ var index = element.selectedIndex; // Nothing was selected if(index < 0){ return null; }; var values = []; var options = element.options; var one = element.type == "select-one"; var clazz = qx.bom.Input; var value; // Loop through all the selected options for(var i = one ? index : 0,max = one ? index + 1 : options.length;i < max;i++){ var option = options[i]; if(option.selected){ // Get the specifc value for the option value = clazz.getValue(option); // We don't need an array for one selects if(one){ return value; }; // Multi-Selects return an array values.push(value); }; }; return values; } else { return (element.value || "").replace(/\r/g, ""); }; }, /** * Sets the text wrap behaviour of a text area element. * This property uses the attribute "wrap" respectively * the style property "whiteSpace" * * @signature function(element, wrap) * @param element {Element} DOM element to modify * @param wrap {Boolean} Whether to turn text wrap on or off. */ setWrap : qx.core.Environment.select("engine.name", { "mshtml" : function(element, wrap){ var wrapValue = wrap ? "soft" : "off"; // Explicitly set overflow-y CSS property to auto when wrapped, // allowing the vertical scroll-bar to appear if necessary var styleValue = wrap ? "auto" : ""; element.wrap = wrapValue; element.style.overflowY = styleValue; }, "gecko|webkit" : function(element, wrap){ var wrapValue = wrap ? "soft" : "off"; var styleValue = wrap ? "" : "auto"; element.setAttribute("wrap", wrapValue); element.style.overflow = styleValue; }, "default" : function(element, wrap){ element.style.whiteSpace = wrap ? "normal" : "nowrap"; } }) } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #ignore(qx.bom.element.AnimationJs) #ignore(qx.bom) ************************************************************************ */ /** * DOM manipulation module */ qx.Bootstrap.define("qx.module.Manipulating", { statics : { /** * Creates a new collection from the given argument. This can either be an * HTML string, a single DOM element or an array of elements * * @attachStatic{qxWeb} * @param html {String|Element[]} HTML string or DOM element(s) * @return {qxWeb} Collection of elements */ create : function(html){ return qxWeb.$init(qx.bom.Html.clean([html])); }, /** * Clones the items in the current collection and returns them in a new set. * Event listeners can also be cloned. * * @attach{qxWeb} * @param events {Boolean} clone event listeners. Default: <pre>false</pre> * @return {qxWeb} New collection with clones */ clone : function(events){ var clones = []; for(var i = 0;i < this.length;i++){ clones[i] = this[i].cloneNode(true); }; if(events === true && this.copyEventsTo){ this.copyEventsTo(clones); }; return qxWeb(clones); }, /** * Appends content to each element in the current set. Accepts an HTML string, * a single DOM element or an array of elements * * @attach{qxWeb} * @param html {String|Element[]} HTML string or DOM element(s) to append * @return {qxWeb} The collection for chaining */ append : function(html){ var arr = qx.bom.Html.clean([html]); var children = qxWeb.$init(arr); for(var i = 0,l = this.length;i < l;i++){ for(var j = 0,m = children.length;j < m;j++){ if(i == 0){ // first parent: move the target node(s) qx.dom.Element.insertEnd(children[j], this[i]); } else { qx.dom.Element.insertEnd(children.eq(j).clone(true)[0], this[i]); }; }; }; return this; }, /** * Appends all items in the collection to the specified parents. If multiple * parents are given, the items will be moved to the first parent, while * clones of the items will be appended to subsequent parents. * * @attach{qxWeb} * @param parent {String|Element[]} Parent selector expression or list of * parent elements * @return {qxWeb} The collection for chaining */ appendTo : function(parent){ parent = qx.module.Manipulating.__getElementArray(parent); for(var i = 0,l = parent.length;i < l;i++){ for(var j = 0,m = this.length;j < m;j++){ if(i == 0){ // first parent: move the target node(s) qx.dom.Element.insertEnd(this[j], parent[i]); } else { // further parents: clone the target node(s) qx.dom.Element.insertEnd(this.eq(j).clone(true)[0], parent[i]); }; }; }; return this; }, /** * Inserts the current collection before each target item. The collection * items are moved before the first target. For subsequent targets, * clones of the collection items are created and inserted. * * @attach{qxWeb} * @param target {String|Element} Selector expression or DOM element * @return {qxWeb} The collection for chaining */ insertBefore : function(target){ target = qx.module.Manipulating.__getElementArray(target); for(var i = 0,l = target.length;i < l;i++){ for(var j = 0,m = this.length;j < m;j++){ if(i == 0){ // first target: move the target node(s) qx.dom.Element.insertBefore(this[j], target[i]); } else { // further targets: clone the target node(s) qx.dom.Element.insertBefore(this.eq(j).clone(true)[0], target[i]); }; }; }; return this; }, /** * Inserts the current collection after each target item. The collection * items are moved after the first target. For subsequent targets, * clones of the collection items are created and inserted. * * @attach{qxWeb} * @param target {String|Element} Selector expression or DOM element * @return {qxWeb} The collection for chaining */ insertAfter : function(target){ target = qx.module.Manipulating.__getElementArray(target); for(var i = 0,l = target.length;i < l;i++){ for(var j = this.length - 1;j >= 0;j--){ if(i == 0){ // first target: move the target node(s) qx.dom.Element.insertAfter(this[j], target[i]); } else { // further targets: clone the target node(s) qx.dom.Element.insertAfter(this.eq(j).clone(true)[0], target[i]); }; }; }; return this; }, /** * Returns an array from a selector expression or a single element * * @attach{qxWeb} * @param arg {String|Element} Selector expression or DOM element * @return {Element[]} Array of elements * @internal */ __getElementArray : function(arg){ if(!qx.lang.Type.isArray(arg)){ var fromSelector = qxWeb(arg); arg = fromSelector.length > 0 ? fromSelector : [arg]; }; return arg; }, /** * Wraps each element in the collection in a copy of an HTML structure. * Elements will be appended to the deepest nested element in the structure * as determined by a depth-first search. * * @attach{qxWeb} * @param wrapper {var} Selector expression, HTML string, DOM element or * list of DOM elements * @return {qxWeb} The collection for chaining */ wrap : function(wrapper){ var wrapper = qx.module.Manipulating.__getCollectionFromArgument(wrapper); if(wrapper.length == 0 || !qx.dom.Node.isElement(wrapper[0])){ return this; }; for(var i = 0,l = this.length;i < l;i++){ var clonedwrapper = wrapper.eq(0).clone(true); qx.dom.Element.insertAfter(clonedwrapper[0], this[i]); var innermost = qx.module.Manipulating.__getInnermostElement(clonedwrapper[0]); qx.dom.Element.insertEnd(this[i], innermost); }; return this; }, /** * Creates a new collection from the given argument * @param arg {var} Selector expression, HTML string, DOM element or list of * DOM elements * @return {qxWeb} Collection * @internal */ __getCollectionFromArgument : function(arg){ var coll; // Collection/array of DOM elements if(qx.lang.Type.isArray(arg)){ coll = qxWeb(arg); } else { var arr = qx.bom.Html.clean([arg]); if(arr.length > 0 && qx.dom.Node.isElement(arr[0])){ coll = qxWeb(arr); } else { coll = qxWeb(arg); }; }; return coll; }, /** * Returns the innermost element of a DOM tree as determined by a simple * depth-first search. * * @param element {Element} Root element * @return {Element} innermost element * @internal */ __getInnermostElement : function(element){ if(element.childNodes.length == 0){ return element; }; for(var i = 0,l = element.childNodes.length;i < l;i++){ if(element.childNodes[i].nodeType === 1){ return this.__getInnermostElement(element.childNodes[i]); }; }; return element; }, /** * Removes each element in the current collection from the DOM * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ remove : function(){ for(var i = 0;i < this.length;i++){ qx.dom.Element.remove(this[i]); }; return this; }, /** * Removes all content from the elements in the collection * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ empty : function(){ for(var i = 0;i < this.length;i++){ // don't use innerHTML="" because of [BUG #7323] // and don't use textContent="" because of missing IE8 support while(this[i].firstChild){ this[i].removeChild(this[i].firstChild); }; }; return this; }, /** * Inserts content before each element in the collection. This can either * be an HTML string, an array of HTML strings, a single DOM element or an * array of elements. * * @attach{qxWeb} * @param content {String[]|Element[]} HTML string(s) or DOM element(s) * @return {qxWeb} The collection for chaining */ before : function(content){ if(!qx.lang.Type.isArray(content)){ content = [content]; }; var fragment = document.createDocumentFragment(); qx.bom.Html.clean(content, document, fragment); this.forEach(function(item, index){ var kids = qx.lang.Array.cast(fragment.childNodes, Array); for(var i = 0,l = kids.length;i < l;i++){ var child; if(index < this.length - 1){ child = kids[i].cloneNode(true); } else { child = kids[i]; }; item.parentNode.insertBefore(child, item); }; }, this); return this; }, /** * Inserts content after each element in the collection. This can either * be an HTML string, an array of HTML strings, a single DOM element or an * array of elements. * * @attach{qxWeb} * @param content {String[]|Element[]} HTML string(s) or DOM element(s) * @return {qxWeb} The collection for chaining */ after : function(content){ if(!qx.lang.Type.isArray(content)){ content = [content]; }; var fragment = document.createDocumentFragment(); qx.bom.Html.clean(content, document, fragment); this.forEach(function(item, index){ var kids = qx.lang.Array.cast(fragment.childNodes, Array); for(var i = kids.length - 1;i >= 0;i--){ var child; if(index < this.length - 1){ child = kids[i].cloneNode(true); } else { child = kids[i]; }; item.parentNode.insertBefore(child, item.nextSibling); }; }, this); return this; }, /** * Returns the left scroll position of the first element in the collection. * * @attach{qxWeb} * @return {Number} Current left scroll position */ getScrollLeft : function(){ var obj = this[0]; if(!obj){ return null; }; var Node = qx.dom.Node; if(Node.isWindow(obj) || Node.isDocument(obj)){ return qx.bom.Viewport.getScrollLeft(); }; return obj.scrollLeft; }, /** * Returns the top scroll position of the first element in the collection. * * @attach{qxWeb} * @return {Number} Current top scroll position */ getScrollTop : function(){ var obj = this[0]; if(!obj){ return null; }; var Node = qx.dom.Node; if(Node.isWindow(obj) || Node.isDocument(obj)){ return qx.bom.Viewport.getScrollTop(); }; return obj.scrollTop; }, /** Default animation descriptions for animated scrolling **/ _animationDescription : { scrollLeft : { duration : 700, timing : "ease-in", keep : 100, keyFrames : { '0' : { }, '100' : { scrollLeft : 1 } } }, scrollTop : { duration : 700, timing : "ease-in", keep : 100, keyFrames : { '0' : { }, '100' : { scrollTop : 1 } } } }, /** * Performs animated scrolling * * @param property {String} Element property to animate: <code>scrollLeft</code> * or <code>scrollTop</code> * @param value {Number} Final scroll position * @param duration {Number} The animation's duration in ms * @return {q} The collection for chaining. */ __animateScroll : function(property, value, duration){ var desc = qx.lang.Object.clone(qx.module.Manipulating._animationDescription[property], true); desc.keyFrames[100][property] = value; return this.animate(desc, duration); }, /** * Scrolls the elements of the collection to the given coordinate. * * @attach{qxWeb} * @param value {Number} Left scroll position * @param duration {Number?} Optional: Duration in ms for animated scrolling * @return {qxWeb} The collection for chaining */ setScrollLeft : function(value, duration){ var Node = qx.dom.Node; if(duration && qx.bom.element && qx.bom.element.AnimationJs){ qx.module.Manipulating.__animateScroll.bind(this, "scrollLeft", value, duration)(); }; for(var i = 0,l = this.length,obj;i < l;i++){ obj = this[i]; if(Node.isElement(obj)){ if(!(duration && qx.bom.element && qx.bom.element.AnimationJs)){ obj.scrollLeft = value; }; } else if(Node.isWindow(obj)){ obj.scrollTo(value, this.getScrollTop(obj)); } else if(Node.isDocument(obj)){ Node.getWindow(obj).scrollTo(value, this.getScrollTop(obj)); };; }; return this; }, /** * Scrolls the elements of the collection to the given coordinate. * * @attach{qxWeb} * @param value {Number} Top scroll position * @param duration {Number?} Optional: Duration in ms for animated scrolling * @return {qxWeb} The collection for chaining */ setScrollTop : function(value, duration){ var Node = qx.dom.Node; if(duration && qx.bom.element && qx.bom.element.AnimationJs){ qx.module.Manipulating.__animateScroll.bind(this, "scrollTop", value, duration)(); }; for(var i = 0,l = this.length,obj;i < l;i++){ obj = this[i]; if(Node.isElement(obj)){ if(!(duration && qx.bom.element && qx.bom.element.AnimationJs)){ obj.scrollTop = value; }; } else if(Node.isWindow(obj)){ obj.scrollTo(this.getScrollLeft(obj), value); } else if(Node.isDocument(obj)){ Node.getWindow(obj).scrollTo(this.getScrollLeft(obj), value); };; }; return this; }, /** * Focuses the first element in the collection * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ focus : function(){ try{ this[0].focus(); } catch(ex) { }; return this; }, /** * Blurs each element in the collection * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ blur : function(){ this.forEach(function(item, index){ try{ item.blur(); } catch(ex) { }; }); return this; } }, defer : function(statics){ qxWeb.$attachStatic({ "create" : statics.create }); qxWeb.$attach({ "append" : statics.append, "appendTo" : statics.appendTo, "remove" : statics.remove, "empty" : statics.empty, "before" : statics.before, "insertBefore" : statics.insertBefore, "after" : statics.after, "insertAfter" : statics.insertAfter, "wrap" : statics.wrap, "clone" : statics.clone, "getScrollLeft" : statics.getScrollLeft, "setScrollLeft" : statics.setScrollLeft, "getScrollTop" : statics.getScrollTop, "setScrollTop" : statics.setScrollTop, "focus" : statics.focus, "blur" : statics.blur }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Manipulating) #require(qx.module.Css) #require(qx.module.Attribute) #require(qx.module.Event) #require(qx.module.Environment) #require(qx.module.Polyfill) #require(qx.module.Traversing) ************************************************************************ */ /** * The module supplies a fallback implementation for placeholders, which is * used on input and textarea elements. If the browser supports native placeholders * the API silently ignores all calls. If not, an element will be created for every * given input element and acts as placeholder. Most modern browsers support * placeholders which makes the fallback only relevant for IE < 10 and FF < 4. * * * <a href="http://dev.w3.org/html5/spec/single-page.html#the-placeholder-attribute">HTML Spec</a> * * * <a href="http://caniuse.com/#feat=input-placeholder">Browser Support</a> */ qx.Bootstrap.define("qx.module.Placeholder", { statics : { /** * String holding the property name which holds the placeholder * element for each input. */ PLACEHOLDER_NAME : "$qx_placeholder", /** * Queries for all input and textarea elements on the page and updates * their placeholder. * @attachStatic{qxWeb, placeholder.update} */ update : function(){ // ignore if native placeholder are supported if(!qxWeb.env.get("css.placeholder")){ qxWeb("input[placeholder], textarea[placeholder]").updatePlaceholder(); }; }, /** * Updates the placeholders for input's and textarea's in the collection. * This includes positioning, styles and DOM positioning. * In case the browser supports native placeholders, this methods simply * does nothing. * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ updatePlaceholder : function(){ // ignore everything if native placeholder are supported if(!qxWeb.env.get("css.placeholder")){ for(var i = 0;i < this.length;i++){ var item = qxWeb(this[i]); // ignore all not fitting items in the collection var placeholder = item.getAttribute("placeholder"); var tagName = item.getProperty("tagName"); if(!placeholder || (tagName != "TEXTAREA" && tagName != "INPUT")){ continue; }; // create the element if necessary var placeholderEl = item.getProperty(qx.module.Placeholder.PLACEHOLDER_NAME); if(!placeholderEl){ placeholderEl = qx.module.Placeholder.__createPlaceholderElement(item); }; // remove and add handling var itemInBody = item.isRendered(); var placeholderElInBody = placeholderEl.isRendered(); if(itemInBody && !placeholderElInBody){ item.before(placeholderEl); } else if(!itemInBody && placeholderElInBody){ placeholderEl.remove(); return this; }; qx.module.Placeholder.__syncStyles(item); }; }; return this; }, /** * Internal helper method to update the styles for a given input element. * @param item {qxWeb} The input element to update. */ __syncStyles : function(item){ var placeholder = item.getAttribute("placeholder"); var placeholderEl = item.getProperty(qx.module.Placeholder.PLACEHOLDER_NAME); var zIndex = item.getStyle("z-index"); var paddingHor = parseInt(item.getStyle("padding-left")) + 2 * parseInt(item.getStyle("padding-right")); var paddingVer = parseInt(item.getStyle("padding-top")) + 2 * parseInt(item.getStyle("padding-bottom")); placeholderEl.setHtml(placeholder).setStyles({ display : item.getValue() == "" ? "inline" : "none", zIndex : zIndex == "auto" ? 1 : zIndex + 1, textAlign : item.getStyle("text-align"), width : (item.getWidth() - paddingHor - 4) + "px", height : (item.getHeight() - paddingVer - 4) + "px", left : item.getOffset().left + "px", top : item.getOffset().top + "px", fontFamily : item.getStyle("font-family"), fontStyle : item.getStyle("font-style"), fontVariant : item.getStyle("font-variant"), fontWeight : item.getStyle("font-weight"), fontSize : item.getStyle("font-size"), paddingTop : (parseInt(item.getStyle("padding-top")) + 2) + "px", paddingRight : (parseInt(item.getStyle("padding-right")) + 2) + "px", paddingBottom : (parseInt(item.getStyle("padding-bottom")) + 2) + "px", paddingLeft : (parseInt(item.getStyle("padding-left")) + 2) + "px" }); }, /** * Creates a placeholder element based on the given input element. * @param item {qxWeb} The input element. * @return {qxWeb} The placeholder element. */ __createPlaceholderElement : function(item){ // create the label with initial styles var placeholderEl = qxWeb.create("<label>").setStyles({ position : "absolute", color : "#989898", overflow : "hidden", pointerEvents : "none" }); // store the label at the input field item.setProperty(qx.module.Placeholder.PLACEHOLDER_NAME, placeholderEl); // update the placeholders visibility on keyUp item.on("keyup", function(item){ var el = item.getProperty(qx.module.Placeholder.PLACEHOLDER_NAME); el.setStyle("display", item.getValue() == "" ? "inline" : "none"); }.bind(this, item)); // for browsers not supporting pointer events if(!qxWeb.env.get("event.pointer")){ placeholderEl.setStyle("cursor", "text").on("click", function(item){ item.focus(); }.bind(this, item)); }; return placeholderEl; } }, defer : function(statics){ qxWeb.$attachStatic({ "placeholder" : { update : statics.update } }); qxWeb.$attach({ "updatePlaceholder" : statics.updatePlaceholder }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * HTML templating module. This is a wrapper for mustache.js which is a * "framework-agnostic way to render logic-free views". * * Here is a basic example how to use it: * <pre class="javascript"> * var template = "Hi, my name is {{name}}!"; * var view = {name: "qooxdoo"}; * q.template.render(template, view); * // return "Hi, my name is qooxdoo!" * </pre> * * For further details, please visit the mustache.js documentation here: * https://github.com/janl/mustache.js/blob/master/README.md */ qx.Bootstrap.define("qx.module.Template", { statics : { /** * Helper method which provides direct access to templates stored as HTML in * the DOM. The DOM node with the given ID will be treated as a template, * parsed and a new DOM node will be returned containing the parsed data. * Keep in mind that templates can only have one root element. * Additionally, you should not put the template into a regular, hidden * DOM element because the template may not be valid HTML due to the containing * mustache tags. We suggest to put it into a script tag with the type * <code>text/template</code>. * * @attachStatic{qxWeb, template.get} * @param id {String} The id of the HTML template in the DOM. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {qxWeb} Collection containing a single DOM element with the parsed * template data. */ get : function(id, view, partials){ var el = qx.bom.Template.get(id, view, partials); return qxWeb.$init([el]); }, /** * Original and only template method of mustache.js. For further * documentation, please visit https://github.com/janl/mustache.js * * @attachStatic{qxWeb, template.render} * @param template {String} The String containing the template. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {String} The parsed template. */ render : function(template, view, partials){ return qx.bom.Template.render(template, view, partials); } }, defer : function(statics){ qxWeb.$attachStatic({ "template" : { get : statics.get, render : statics.render } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ====================================================================== This class contains code based on the following work: * Mustache.js version 0.7.0 Code: https://github.com/janl/mustache.js Copyright: (c) 2009 Chris Wanstrath (Ruby) (c) 2010 Jan Lehnardt (JavaScript) License: MIT: http://www.opensource.org/licenses/mit-license.php ---------------------------------------------------------------------- Copyright (c) 2009 Chris Wanstrath (Ruby) Copyright (c) 2010 Jan Lehnardt (JavaScript) 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. ************************************************************************ */ /* ************************************************************************ #ignore(module) ************************************************************************ */ /** * The is a template class which can be used for HTML templating. In fact, * this is a wrapper for mustache.js which is a "framework-agnostic way to * render logic-free views". * * Here is a basic example how to use it: * Template: * <pre class="javascript"> * var template = "Hi, my name is {{name}}!"; * var view = {name: "qooxdoo"}; * qx.bom.Template.render(template, view); * // return "Hi, my name is qooxdoo!" * </pre> * * For further details, please visit the mustache.js documentation here: * https://github.com/janl/mustache.js/blob/master/README.md * */ qx.Bootstrap.define("qx.bom.Template", { statics : { /** Contains the mustache.js version. */ version : null, /** * Original and only template method of mustache.js. For further * documentation, please visit https://github.com/janl/mustache.js * * @signature function(template, view, partials) * @param template {String} The String containing the template. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {String} The parsed template. */ render : null, /** * Helper method which provides you with a direct access to templates * stored as HTML in the DOM. The DOM node with the given ID will be used * as a template, parsed and a new DOM node will be returned containing the * parsed data. Keep in mind to have only one root DOM element in the the * template. * Additionally, you should not put the template into a regular, hidden * DOM element because the template may not be valid HTML due to the containing * mustache tags. We suggest to put it into a script tag with the type * <code>text/template</code>. * * @param id {String} The id of the HTML template in the DOM. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {Element} A DOM element holding the parsed template data. */ get : function(id, view, partials){ // get the content stored in the DOM var template = document.getElementById(id); var inner = template.innerHTML; // apply the view inner = this.render(inner, view, partials); // special case for text only conversion if(inner.search(/<|>/) === -1){ return document.createTextNode(inner); }; // create a helper to convert the string into DOM nodes var helper = qx.dom.Element.create("div"); helper.innerHTML = inner; return helper.children[0]; } } }); (function(){ /** * Below is the original mustache.js code. Snapshot date is mentioned in * the head of this file. * @lint ignoreUndefined(module) */ /*! * mustache.js - Logic-less {{mustache}} templates with JavaScript * http://github.com/janl/mustache.js */ /*global define: false*/ var Mustache; /** * @lint ignoreUndefined(module,define) */ (function(exports){ Mustache = exports; }((function(){ var exports = { }; exports.name = "mustache.js"; exports.version = "0.7.0"; exports.tags = ["{{", "}}"]; exports.Scanner = Scanner; exports.Context = Context; exports.Writer = Writer; var whiteRe = /\s*/; var spaceRe = /\s+/; var nonSpaceRe = /\S/; var eqRe = /\s*=/; var curlyRe = /\s*\}/; var tagRe = /#|\^|\/|>|\{|&|=|!/; // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577 // See https://github.com/janl/mustache.js/issues/189 function testRe(re, string){ return RegExp.prototype.test.call(re, string); }; function isWhitespace(string){ return !testRe(nonSpaceRe, string); }; var isArray = Array.isArray || function(obj){ return Object.prototype.toString.call(obj) === "[object Array]"; }; function escapeRe(string){ return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); }; var entityMap = { "&" : "&amp;", "<" : "&lt;", ">" : "&gt;", '"' : '&quot;', "'" : '&#39;', "/" : '&#x2F;' }; function escapeHtml(string){ return String(string).replace(/[&<>"'\/]/g, function(s){ return entityMap[s]; }); }; // Export the escaping function so that the user may override it. // See https://github.com/janl/mustache.js/issues/244 exports.escape = escapeHtml; function Scanner(string){ this.string = string; this.tail = string; this.pos = 0; }; /** * Returns `true` if the tail is empty (end of string). */ Scanner.prototype.eos = function(){ return this.tail === ""; }; /** * Tries to match the given regular expression at the current position. * Returns the matched text if it can match, the empty string otherwise. */ Scanner.prototype.scan = function(re){ var match = this.tail.match(re); if(match && match.index === 0){ this.tail = this.tail.substring(match[0].length); this.pos += match[0].length; return match[0]; }; return ""; }; /** * Skips all text until the given regular expression can be matched. Returns * the skipped string, which is the entire tail if no match can be made. */ Scanner.prototype.scanUntil = function(re){ var match,pos = this.tail.search(re); switch(pos){case -1: match = this.tail; this.pos += this.tail.length; this.tail = ""; break;case 0: match = ""; break;default: match = this.tail.substring(0, pos); this.tail = this.tail.substring(pos); this.pos += pos;}; return match; }; function Context(view, parent){ this.view = view; this.parent = parent; this.clearCache(); }; Context.make = function(view){ return (view instanceof Context) ? view : new Context(view); }; Context.prototype.clearCache = function(){ this._cache = { }; }; Context.prototype.push = function(view){ return new Context(view, this); }; Context.prototype.lookup = function(name){ var value = this._cache[name]; if(!value){ if(name === "."){ value = this.view; } else { var context = this; while(context){ if(name.indexOf(".") > 0){ var names = name.split("."),i = 0; value = context.view; while(value && i < names.length){ value = value[names[i++]]; }; } else { value = context.view[name]; }; if(value != null){ break; }; context = context.parent; }; }; this._cache[name] = value; }; if(typeof value === "function"){ value = value.call(this.view); }; return value; }; function Writer(){ this.clearCache(); }; Writer.prototype.clearCache = function(){ this._cache = { }; this._partialCache = { }; }; Writer.prototype.compile = function(template, tags){ var fn = this._cache[template]; if(!fn){ var tokens = exports.parse(template, tags); fn = this._cache[template] = this.compileTokens(tokens, template); }; return fn; }; Writer.prototype.compilePartial = function(name, template, tags){ var fn = this.compile(template, tags); this._partialCache[name] = fn; return fn; }; Writer.prototype.compileTokens = function(tokens, template){ var fn = compileTokens(tokens); var self = this; return function(view, partials){ if(partials){ if(typeof partials === "function"){ self._loadPartial = partials; } else { for(var name in partials){ self.compilePartial(name, partials[name]); }; }; }; return fn(self, Context.make(view), template); }; }; Writer.prototype.render = function(template, view, partials){ return this.compile(template)(view, partials); }; Writer.prototype._section = function(name, context, text, callback){ var value = context.lookup(name); switch(typeof value){case "object": if(isArray(value)){ var buffer = ""; for(var i = 0,len = value.length;i < len;++i){ buffer += callback(this, context.push(value[i])); }; return buffer; }; return value ? callback(this, context.push(value)) : "";case "function": var self = this; var scopedRender = function(template){ return self.render(template, context); }; return value.call(context.view, text, scopedRender) || "";default: if(value){ return callback(this, context); };}; return ""; }; Writer.prototype._inverted = function(name, context, callback){ var value = context.lookup(name); // Use JavaScript's definition of falsy. Include empty arrays. // See https://github.com/janl/mustache.js/issues/186 if(!value || (isArray(value) && value.length === 0)){ return callback(this, context); }; return ""; }; Writer.prototype._partial = function(name, context){ if(!(name in this._partialCache) && this._loadPartial){ this.compilePartial(name, this._loadPartial(name)); }; var fn = this._partialCache[name]; return fn ? fn(context) : ""; }; Writer.prototype._name = function(name, context){ var value = context.lookup(name); if(typeof value === "function"){ value = value.call(context.view); }; return (value == null) ? "" : String(value); }; Writer.prototype._escaped = function(name, context){ return exports.escape(this._name(name, context)); }; /** * Calculates the bounds of the section represented by the given `token` in * the original template by drilling down into nested sections to find the * last token that is part of that section. Returns an array of [start, end]. */ function sectionBounds(token){ var start = token[3]; var end = start; var tokens; while((tokens = token[4]) && tokens.length){ token = tokens[tokens.length - 1]; end = token[3]; }; return [start, end]; }; /** * Low-level function that compiles the given `tokens` into a function * that accepts three arguments: a Writer, a Context, and the template. */ function compileTokens(tokens){ var subRenders = { }; function subRender(i, tokens, template){ if(!subRenders[i]){ var fn = compileTokens(tokens); subRenders[i] = function(writer, context){ return fn(writer, context, template); }; }; return subRenders[i]; }; return function(writer, context, template){ var buffer = ""; var token,sectionText; for(var i = 0,len = tokens.length;i < len;++i){ token = tokens[i]; switch(token[0]){case "#": sectionText = template.slice.apply(template, sectionBounds(token)); buffer += writer._section(token[1], context, sectionText, subRender(i, token[4], template)); break;case "^": buffer += writer._inverted(token[1], context, subRender(i, token[4], template)); break;case ">": buffer += writer._partial(token[1], context); break;case "&": buffer += writer._name(token[1], context); break;case "name": buffer += writer._escaped(token[1], context); break;case "text": buffer += token[1]; break;}; }; return buffer; }; }; /** * Forms the given array of `tokens` into a nested tree structure where * tokens that represent a section have a fifth item: an array that contains * all tokens in that section. */ function nestTokens(tokens){ var tree = []; var collector = tree; var sections = []; var token,section; for(var i = 0;i < tokens.length;++i){ token = tokens[i]; switch(token[0]){case "#":case "^": token[4] = []; sections.push(token); collector.push(token); collector = token[4]; break;case "/": if(sections.length === 0){ throw new Error("Unopened section: " + token[1]); }; section = sections.pop(); if(section[1] !== token[1]){ throw new Error("Unclosed section: " + section[1]); }; if(sections.length > 0){ collector = sections[sections.length - 1][4]; } else { collector = tree; }; break;default: collector.push(token);}; }; // Make sure there were no open sections when we're done. section = sections.pop(); if(section){ throw new Error("Unclosed section: " + section[1]); }; return tree; }; /** * Combines the values of consecutive text tokens in the given `tokens` array * to a single token. */ function squashTokens(tokens){ var token,lastToken; for(var i = 0;i < tokens.length;++i){ token = tokens[i]; if(lastToken && lastToken[0] === "text" && token[0] === "text"){ lastToken[1] += token[1]; lastToken[3] = token[3]; tokens.splice(i--, 1); } else { lastToken = token; }; }; }; function escapeTags(tags){ if(tags.length !== 2){ throw new Error("Invalid tags: " + tags.join(" ")); }; return [new RegExp(escapeRe(tags[0]) + "\\s*"), new RegExp("\\s*" + escapeRe(tags[1]))]; }; /** * Breaks up the given `template` string into a tree of token objects. If * `tags` is given here it must be an array with two string values: the * opening and closing tags used in the template (e.g. ["<%", "%>"]). Of * course, the default is to use mustaches (i.e. Mustache.tags). */ exports.parse = function(template, tags){ tags = tags || exports.tags; var tagRes = escapeTags(tags); var scanner = new Scanner(template); var tokens = [],// Buffer to hold the tokens spaces = [],// Indices of whitespace tokens on the current line hasTag = false,// Is there a {{tag}} on the current line? nonSpace = false; // Is there a non-space char on the current line? // Strips all whitespace tokens array for the current line // if there was a {{#tag}} on it and otherwise only space. function stripSpace(){ if(hasTag && !nonSpace){ while(spaces.length){ tokens.splice(spaces.pop(), 1); }; } else { spaces = []; }; hasTag = false; nonSpace = false; }; var start,type,value,chr; while(!scanner.eos()){ start = scanner.pos; value = scanner.scanUntil(tagRes[0]); if(value){ for(var i = 0,len = value.length;i < len;++i){ chr = value.charAt(i); if(isWhitespace(chr)){ spaces.push(tokens.length); } else { nonSpace = true; }; tokens.push(["text", chr, start, start + 1]); start += 1; if(chr === "\n"){ stripSpace(); }; }; }; start = scanner.pos; // Match the opening tag. if(!scanner.scan(tagRes[0])){ break; }; hasTag = true; type = scanner.scan(tagRe) || "name"; // Skip any whitespace between tag and value. scanner.scan(whiteRe); // Extract the tag value. if(type === "="){ value = scanner.scanUntil(eqRe); scanner.scan(eqRe); scanner.scanUntil(tagRes[1]); } else if(type === "{"){ var closeRe = new RegExp("\\s*" + escapeRe("}" + tags[1])); value = scanner.scanUntil(closeRe); scanner.scan(curlyRe); scanner.scanUntil(tagRes[1]); type = "&"; } else { value = scanner.scanUntil(tagRes[1]); }; // Match the closing tag. if(!scanner.scan(tagRes[1])){ throw new Error("Unclosed tag at " + scanner.pos); }; tokens.push([type, value, start, scanner.pos]); if(type === "name" || type === "{" || type === "&"){ nonSpace = true; }; // Set the tags for the next time around. if(type === "="){ tags = value.split(spaceRe); tagRes = escapeTags(tags); }; }; squashTokens(tokens); return nestTokens(tokens); }; // The high-level clearCache, compile, compilePartial, and render functions // use this default writer. var _writer = new Writer(); /** * Clears all cached templates and partials in the default writer. */ exports.clearCache = function(){ return _writer.clearCache(); }; /** * Compiles the given `template` to a reusable function using the default * writer. */ exports.compile = function(template, tags){ return _writer.compile(template, tags); }; /** * Compiles the partial with the given `name` and `template` to a reusable * function using the default writer. */ exports.compilePartial = function(name, template, tags){ return _writer.compilePartial(name, template, tags); }; /** * Compiles the given array of tokens (the output of a parse) to a reusable * function using the default writer. */ exports.compileTokens = function(tokens, template){ return _writer.compileTokens(tokens, template); }; /** * Renders the `template` with the given `view` and `partials` using the * default writer. */ exports.render = function(template, view, partials){ return _writer.render(template, view, partials); }; // This is here for backwards compatibility with 0.4.x. exports.to_html = function(template, view, partials, send){ var result = exports.render(template, view, partials); if(typeof send === "function"){ send(result); } else { return result; }; }; return exports; }()))); /** * Above is the original mustache code. */ // EXPOSE qooxdoo variant qx.bom.Template.version = Mustache.version; qx.bom.Template.render = Mustache.render; })(); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Orientation handler which is responsible for registering and unregistering a * {@link qx.event.handler.OrientationCore} handler for each given element. */ qx.Bootstrap.define("qx.module.event.OrientationHandler", { statics : { /** * List of events that require an orientation handler * @type {Array} */ TYPES : ["orientationchange"], /** * Creates an orientation handler for the given window when an * orientationchange event listener is attached to it * * @param element {Window} DOM Window */ register : function(element){ if(!qx.dom.Node.isWindow(element)){ throw new Error("The 'orientationchange' event is only available on window objects!"); }; if(!element.__orientationHandler){ if(!element.__emitter){ element.__emitter = new qx.event.Emitter(); }; element.__orientationHandler = new qx.event.handler.OrientationCore(element, element.__emitter); }; }, /** * Removes the orientation event handler from the element if there are no more * orientationchange event listeners attached to it * @param element {Element} DOM element */ unregister : function(element){ if(element.__orientationHandler){ if(!element.__emitter){ element.__orientationHandler = null; } else { var hasListener = false; var listeners = element.__emitter.getListeners(); qx.module.event.OrientationHandler.TYPES.forEach(function(type){ if(type in listeners && listeners[type].length > 0){ hasListener = true; }; }); if(!hasListener){ element.__orientationHandler = null; }; }; }; } }, defer : function(statics){ qxWeb.$registerEventHook(statics.TYPES, statics.register, statics.unregister); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tino Butz (tbtz) * Daniel Wagner (danielwagner) ====================================================================== This class contains code based on the following work: * Unify Project Homepage: http://unify-project.org Copyright: 2009-2010 Deutsche Telekom AG, Germany, http://telekom.com License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /** * Listens for native orientation change events */ qx.Bootstrap.define("qx.event.handler.OrientationCore", { extend : Object, /** * * @param targetWindow {Window} DOM window object * @param emitter {qx.event.Emitter} Event emitter object */ construct : function(targetWindow, emitter){ this._window = targetWindow || window; this.__emitter = emitter; this._initObserver(); }, members : { __emitter : null, _window : null, _currentOrientation : null, __onNativeWrapper : null, __nativeEventType : null, /* --------------------------------------------------------------------------- OBSERVER INIT --------------------------------------------------------------------------- */ /** * Initializes the native orientation change event listeners. */ _initObserver : function(){ this.__onNativeWrapper = qx.lang.Function.listener(this._onNative, this); // Handle orientation change event for Android devices by the resize event. // See http://stackoverflow.com/questions/1649086/detect-rotation-of-android-phone-in-the-browser-with-javascript // for more information. this.__nativeEventType = qx.bom.Event.supportsEvent(this._window, "orientationchange") ? "orientationchange" : "resize"; qx.bom.Event.addNativeListener(this._window, this.__nativeEventType, this.__onNativeWrapper); }, /* --------------------------------------------------------------------------- OBSERVER STOP --------------------------------------------------------------------------- */ /** * Disconnects the native orientation change event listeners. */ _stopObserver : function(){ qx.bom.Event.removeNativeListener(this._window, this.__nativeEventType, this.__onNativeWrapper); }, /* --------------------------------------------------------------------------- NATIVE EVENT OBSERVERS --------------------------------------------------------------------------- */ /** * Handler for the native orientation change event. * * @signature function(domEvent) * @param domEvent {Event} The touch event from the browser. */ _onNative : function(domEvent){ var orientation = qx.bom.Viewport.getOrientation(); if(this._currentOrientation != orientation){ this._currentOrientation = orientation; var mode = qx.bom.Viewport.isLandscape() ? "landscape" : "portrait"; domEvent._orientation = orientation; domEvent._mode = mode; if(this.__emitter){ this.__emitter.emit("orientationchange", domEvent); }; }; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function(){ this._stopObserver(); this.__manager = this.__emitter = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /* ************************************************************************ #ignore(XDomainRequest) #require(qx.bom.request.Xhr#open) #require(qx.bom.request.Xhr#send) #require(qx.bom.request.Xhr#on) #require(qx.bom.request.Xhr#onreadystatechange) #require(qx.bom.request.Xhr#onload) #require(qx.bom.request.Xhr#onloadend) #require(qx.bom.request.Xhr#onerror) #require(qx.bom.request.Xhr#onabort) #require(qx.bom.request.Xhr#ontimeout) #require(qx.bom.request.Xhr#setRequestHeader) #require(qx.bom.request.Xhr#getAllResponseHeaders) #require(qx.bom.request.Xhr#getRequest) ************************************************************************ */ /** * A wrapper of the XMLHttpRequest host object (or equivalent). The interface is * similar to <a href="http://www.w3.org/TR/XMLHttpRequest/">XmlHttpRequest</a>. * * Hides browser inconsistencies and works around bugs found in popular * implementations. * * <div class="desktop"> * Example: * * <pre class="javascript"> * var req = new qx.bom.request.Xhr(); * req.onload = function() { * // Handle data received * req.responseText; * } * * req.open("GET", url); * req.send(); * </pre> * </div> */ qx.Bootstrap.define("qx.bom.request.Xhr", { construct : function(){ this.__onNativeReadyStateChangeBound = qx.Bootstrap.bind(this.__onNativeReadyStateChange, this); this.__onNativeAbortBound = qx.Bootstrap.bind(this.__onNativeAbort, this); this.__onTimeoutBound = qx.Bootstrap.bind(this.__onTimeout, this); this.__initNativeXhr(); this._emitter = new qx.event.Emitter(); // BUGFIX: IE // IE keeps connections alive unless aborted on unload if(window.attachEvent){ this.__onUnloadBound = qx.Bootstrap.bind(this.__onUnload, this); window.attachEvent("onunload", this.__onUnloadBound); }; }, statics : { UNSENT : 0, OPENED : 1, HEADERS_RECEIVED : 2, LOADING : 3, DONE : 4 }, events : { /** Fired at ready state changes. */ "readystatechange" : "qx.bom.request.Xhr", /** Fired on error. */ "error" : "qx.bom.request.Xhr", /** Fired at loadend. */ "loadend" : "qx.bom.request.Xhr", /** Fired on timeouts. */ "timeout" : "qx.bom.request.Xhr", /** Fired when the request is aborted. */ "abort" : "qx.bom.request.Xhr", /** Fired on successful retrieval. */ "load" : "qx.bom.request.Xhr" }, members : { /* --------------------------------------------------------------------------- PUBLIC --------------------------------------------------------------------------- */ /** * {Number} Ready state. * * States can be: * UNSENT: 0, * OPENED: 1, * HEADERS_RECEIVED: 2, * LOADING: 3, * DONE: 4 */ readyState : 0, /** * {String} The response of the request as text. */ responseText : "", /** * {Object} The response of the request as a Document object. */ responseXML : null, /** * {Number} The HTTP status code. */ status : 0, /** * {String} The HTTP status text. */ statusText : "", /** * {Number} Timeout limit in milliseconds. * * 0 (default) means no timeout. Not supported for synchronous requests. */ timeout : 0, /** * Initializes (prepares) request. * * @lint ignoreUndefined(XDomainRequest) * * @param method {String?"GET"} * The HTTP method to use. * @param url {String} * The URL to which to send the request. * @param async {Boolean?true} * Whether or not to perform the operation asynchronously. * @param user {String?null} * Optional user name to use for authentication purposes. * @param password {String?null} * Optional password to use for authentication purposes. */ open : function(method, url, async, user, password){ this.__checkDisposed(); // Mimick native behavior if(typeof url === "undefined"){ throw new Error("Not enough arguments"); } else if(typeof method === "undefined"){ method = "GET"; }; // Reset flags that may have been set on previous request this.__abort = false; this.__send = false; this.__conditional = false; // Store URL for later checks this.__url = url; if(typeof async == "undefined"){ async = true; }; this.__async = async; // BUGFIX // IE < 9 and FF < 3.5 cannot reuse the native XHR to issue many requests if(!this.__supportsManyRequests() && this.readyState > qx.bom.request.Xhr.UNSENT){ // XmlHttpRequest Level 1 requires open() to abort any pending requests // associated to the object. Since we're dealing with a new object here, // we have to emulate this behavior. Moreover, allow old native XHR to be garbage collected // // Dispose and abort. // this.dispose(); // Replace the underlying native XHR with a new one that can // be used to issue new requests. this.__initNativeXhr(); }; // Restore handler in case it was removed before this.__nativeXhr.onreadystatechange = this.__onNativeReadyStateChangeBound; try{ { }; this.__nativeXhr.open(method, url, async, user, password); } catch(OpenError) { // Only work around exceptions caused by cross domain request attempts if(!qx.util.Request.isCrossDomain(url)){ // Is same origin throw OpenError; }; if(!this.__async){ this.__openError = OpenError; }; if(this.__async){ // Try again with XDomainRequest // (Success case not handled on purpose) // - IE 9 if(window.XDomainRequest){ this.readyState = 4; this.__nativeXhr = new XDomainRequest(); this.__nativeXhr.onerror = qx.Bootstrap.bind(function(){ this._emit("readystatechange"); this._emit("error"); this._emit("loadend"); }, this); { }; this.__nativeXhr.open(method, url, async, user, password); return; }; // Access denied // - IE 6: -2146828218 // - IE 7: -2147024891 // - Legacy Firefox window.setTimeout(qx.Bootstrap.bind(function(){ if(this.__disposed){ return; }; this.readyState = 4; this._emit("readystatechange"); this._emit("error"); this._emit("loadend"); }, this)); }; }; // BUGFIX: IE < 9 // IE < 9 tends to cache overly agressive. This may result in stale // representations. Force validating freshness of cached representation. if(qx.core.Environment.get("engine.name") === "mshtml" && qx.core.Environment.get("browser.documentmode") < 9 && this.__nativeXhr.readyState > 0){ this.__nativeXhr.setRequestHeader("If-Modified-Since", "-1"); }; // BUGFIX: Firefox // Firefox < 4 fails to trigger onreadystatechange OPENED for sync requests if(qx.core.Environment.get("engine.name") === "gecko" && parseInt(qx.core.Environment.get("engine.version"), 10) < 2 && !this.__async){ // Native XHR is already set to readyState DONE. Fake readyState // and call onreadystatechange manually. this.readyState = qx.bom.request.Xhr.OPENED; this._emit("readystatechange"); }; }, /** * Sets an HTTP request header to be used by the request. * * Note: The request must be initialized before using this method. * * @param key {String} * The name of the header whose value is to be set. * @param value {String} * The value to set as the body of the header. * @return {qx.bom.request.Xhr} Self for chaining. */ setRequestHeader : function(key, value){ this.__checkDisposed(); // Detect conditional requests if(key == "If-Match" || key == "If-Modified-Since" || key == "If-None-Match" || key == "If-Range"){ this.__conditional = true; }; this.__nativeXhr.setRequestHeader(key, value); return this; }, /** * Sends request. * * @param data {String|Document?null} * Optional data to send. * @return {qx.bom.request.Xhr} Self for chaining. */ send : function(data){ this.__checkDisposed(); // BUGFIX: IE & Firefox < 3.5 // For sync requests, some browsers throw error on open() // while it should be on send() // if(!this.__async && this.__openError){ throw this.__openError; }; // BUGFIX: Opera // On network error, Opera stalls at readyState HEADERS_RECEIVED // This violates the spec. See here http://www.w3.org/TR/XMLHttpRequest2/#send // (Section: If there is a network error) // // To fix, assume a default timeout of 10 seconds. Note: The "error" // event will be fired correctly, because the error flag is inferred // from the statusText property. Of course, compared to other // browsers there is an additional call to ontimeout(), but this call // should not harm. // if(qx.core.Environment.get("engine.name") === "opera" && this.timeout === 0){ this.timeout = 10000; }; // Timeout if(this.timeout > 0){ this.__timerId = window.setTimeout(this.__onTimeoutBound, this.timeout); }; // BUGFIX: Firefox 2 // "NS_ERROR_XPC_NOT_ENOUGH_ARGS" when calling send() without arguments data = typeof data == "undefined" ? null : data; // Some browsers may throw an error when sending of async request fails. // This violates the spec which states only sync requests should. try{ { }; this.__nativeXhr.send(data); } catch(SendError) { if(!this.__async){ throw SendError; }; // BUGFIX // Some browsers throws error when file not found via file:// protocol. // Synthesize readyState changes. if(this._getProtocol() === "file:"){ this.readyState = 2; this.__readyStateChange(); var that = this; window.setTimeout(function(){ if(that.__disposed){ return; }; that.readyState = 3; that.__readyStateChange(); that.readyState = 4; that.__readyStateChange(); }); }; }; // BUGFIX: Firefox // Firefox fails to trigger onreadystatechange DONE for sync requests if(qx.core.Environment.get("engine.name") === "gecko" && !this.__async){ // Properties all set, only missing native readystatechange event this.__onNativeReadyStateChange(); }; // Set send flag this.__send = true; return this; }, /** * Abort request - i.e. cancels any network activity. * * Note: * On Windows 7 every browser strangely skips the loading phase * when this method is called (because readyState never gets 3). * * So keep this in mind if you rely on the phases which are * passed through. They will be "opened", "sent", "abort" * instead of normally "opened", "sent", "loading", "abort". * * @return {qx.bom.request.Xhr} Self for chaining. */ abort : function(){ this.__checkDisposed(); this.__abort = true; this.__nativeXhr.abort(); if(this.__nativeXhr){ this.readyState = this.__nativeXhr.readyState; }; return this; }, /** * Helper to emit events and call the callback methods. * @param event {String} The name of the event. */ _emit : function(event){ this["on" + event](); this._emitter.emit(event, this); }, /** * Event handler for XHR event that fires at every state change. * * Replace with custom method to get informed about the communication progress. */ onreadystatechange : function(){ }, /** * Event handler for XHR event "load" that is fired on successful retrieval. * * Note: This handler is called even when the HTTP status indicates an error. * * Replace with custom method to listen to the "load" event. */ onload : function(){ }, /** * Event handler for XHR event "loadend" that is fired on retrieval. * * Note: This handler is called even when a network error (or similar) * occurred. * * Replace with custom method to listen to the "loadend" event. */ onloadend : function(){ }, /** * Event handler for XHR event "error" that is fired on a network error. * * Replace with custom method to listen to the "error" event. */ onerror : function(){ }, /** * Event handler for XHR event "abort" that is fired when request * is aborted. * * Replace with custom method to listen to the "abort" event. */ onabort : function(){ }, /** * Event handler for XHR event "timeout" that is fired when timeout * interval has passed. * * Replace with custom method to listen to the "timeout" event. */ ontimeout : function(){ }, /** * Add an event listener for the given event name. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function to execute when the event is fired * @param ctx {var?} The context of the listener. * @return {qx.bom.request.Xhr} Self for chaining. */ on : function(name, listener, ctx){ this._emitter.on(name, listener, ctx); return this; }, /** * Get a single response header from response. * * @param header {String} * Key of the header to get the value from. * @return {String} * Response header. */ getResponseHeader : function(header){ this.__checkDisposed(); return this.__nativeXhr.getResponseHeader(header); }, /** * Get all response headers from response. * * @return {String} All response headers. */ getAllResponseHeaders : function(){ this.__checkDisposed(); return this.__nativeXhr.getAllResponseHeaders(); }, /** * Get wrapped native XMLHttpRequest (or equivalent). * * Can be XMLHttpRequest or ActiveX. * * @return {Object} XMLHttpRequest or equivalent. */ getRequest : function(){ return this.__nativeXhr; }, /* --------------------------------------------------------------------------- HELPER --------------------------------------------------------------------------- */ /** * Dispose object and wrapped native XHR. * @return {Boolean} <code>true</code> if the object was successfully disposed */ dispose : function(){ if(this.__disposed){ return false; }; window.clearTimeout(this.__timerId); // Remove unload listener in IE. Aborting on unload is no longer required // for this instance. if(window.detachEvent){ window.detachEvent("onunload", this.__onUnloadBound); }; // May fail in IE try{ this.__nativeXhr.onreadystatechange; } catch(PropertiesNotAccessable) { return false; }; // Clear out listeners var noop = function(){ }; this.__nativeXhr.onreadystatechange = noop; this.__nativeXhr.onload = noop; this.__nativeXhr.onerror = noop; // Abort any network activity this.abort(); // Remove reference to native XHR this.__nativeXhr = null; this.__disposed = true; return true; }, /* --------------------------------------------------------------------------- PROTECTED --------------------------------------------------------------------------- */ /** * Create XMLHttpRequest (or equivalent). * * @return {Object} XMLHttpRequest or equivalent. */ _createNativeXhr : function(){ var xhr = qx.core.Environment.get("io.xhr"); if(xhr === "xhr"){ return new XMLHttpRequest(); }; if(xhr == "activex"){ return new window.ActiveXObject("Microsoft.XMLHTTP"); }; qx.Bootstrap.error(this, "No XHR support available."); }, /** * Get protocol of requested URL. * * @return {String} The used protocol. */ _getProtocol : function(){ var url = this.__url; var protocolRe = /^(\w+:)\/\//; // Could be http:// from file:// if(url !== null && url.match){ var match = url.match(protocolRe); if(match && match[1]){ return match[1]; }; }; return window.location.protocol; }, /* --------------------------------------------------------------------------- PRIVATE --------------------------------------------------------------------------- */ /** * {Object} XMLHttpRequest or equivalent. */ __nativeXhr : null, /** * {Boolean} Whether request is async. */ __async : null, /** * {Function} Bound __onNativeReadyStateChange handler. */ __onNativeReadyStateChangeBound : null, /** * {Function} Bound __onNativeAbort handler. */ __onNativeAbortBound : null, /** * {Function} Bound __onUnload handler. */ __onUnloadBound : null, /** * {Function} Bound __onTimeout handler. */ __onTimeoutBound : null, /** * {Boolean} Send flag */ __send : null, /** * {String} Requested URL */ __url : null, /** * {Boolean} Abort flag */ __abort : null, /** * {Boolean} Timeout flag */ __timeout : null, /** * {Boolean} Whether object has been disposed. */ __disposed : null, /** * {Number} ID of timeout timer. */ __timerId : null, /** * {Error} Error thrown on open, if any. */ __openError : null, /** * {Boolean} Conditional get flag */ __conditional : null, /** * Init native XHR. */ __initNativeXhr : function(){ // Create native XHR or equivalent and hold reference this.__nativeXhr = this._createNativeXhr(); // Track native ready state changes this.__nativeXhr.onreadystatechange = this.__onNativeReadyStateChangeBound; // Track native abort, when supported if(this.__nativeXhr.onabort){ this.__nativeXhr.onabort = this.__onNativeAbortBound; }; // Reset flags this.__disposed = this.__send = this.__abort = false; }, /** * Track native abort. * * In case the end user cancels the request by other * means than calling abort(). */ __onNativeAbort : function(){ // When the abort that triggered this method was not a result from // calling abort() if(!this.__abort){ this.abort(); }; }, /** * Handle native onreadystatechange. * * Calls user-defined function onreadystatechange on each * state change and syncs the XHR status properties. */ __onNativeReadyStateChange : function(){ var nxhr = this.__nativeXhr,propertiesReadable = true; { }; // BUGFIX: IE, Firefox // onreadystatechange() is called twice for readyState OPENED. // // Call onreadystatechange only when readyState has changed. if(this.readyState == nxhr.readyState){ return; }; // Sync current readyState this.readyState = nxhr.readyState; // BUGFIX: IE // Superfluous onreadystatechange DONE when aborting OPENED // without send flag if(this.readyState === qx.bom.request.Xhr.DONE && this.__abort && !this.__send){ return; }; // BUGFIX: IE // IE fires onreadystatechange HEADERS_RECEIVED and LOADING when sync // // According to spec, only onreadystatechange OPENED and DONE should // be fired. if(!this.__async && (nxhr.readyState == 2 || nxhr.readyState == 3)){ return; }; // Default values according to spec. this.status = 0; this.statusText = this.responseText = ""; this.responseXML = null; if(this.readyState >= qx.bom.request.Xhr.HEADERS_RECEIVED){ // In some browsers, XHR properties are not readable // while request is in progress. try{ this.status = nxhr.status; this.statusText = nxhr.statusText; this.responseText = nxhr.responseText; this.responseXML = nxhr.responseXML; } catch(XhrPropertiesNotReadable) { propertiesReadable = false; }; if(propertiesReadable){ this.__normalizeStatus(); this.__normalizeResponseXML(); }; }; this.__readyStateChange(); // BUGFIX: IE // Memory leak in XMLHttpRequest (on-page) if(this.readyState == qx.bom.request.Xhr.DONE){ // Allow garbage collecting of native XHR if(nxhr){ nxhr.onreadystatechange = function(){ }; }; }; }, /** * Handle readystatechange. Called internally when readyState is changed. */ __readyStateChange : function(){ var that = this; // Cancel timeout before invoking handlers because they may throw if(this.readyState === qx.bom.request.Xhr.DONE){ // Request determined DONE. Cancel timeout. window.clearTimeout(this.__timerId); }; // BUGFIX: IE // IE < 8 fires LOADING and DONE on open() - before send() - when from cache if(qx.core.Environment.get("engine.name") == "mshtml" && qx.core.Environment.get("browser.documentmode") < 8){ // Detect premature events when async. LOADING and DONE is // illogical to happen before request was sent. if(this.__async && !this.__send && this.readyState >= qx.bom.request.Xhr.LOADING){ if(this.readyState == qx.bom.request.Xhr.LOADING){ // To early to fire, skip. return; }; if(this.readyState == qx.bom.request.Xhr.DONE){ window.setTimeout(function(){ if(that.__disposed){ return; }; // Replay previously skipped that.readyState = 3; that._emit("readystatechange"); that.readyState = 4; that._emit("readystatechange"); that.__readyStateChangeDone(); }); return; }; }; }; // Always fire "readystatechange" this._emit("readystatechange"); if(this.readyState === qx.bom.request.Xhr.DONE){ this.__readyStateChangeDone(); }; }, /** * Handle readystatechange. Called internally by * {@link #__readyStateChange} when readyState is DONE. */ __readyStateChangeDone : function(){ // Fire "timeout" if timeout flag is set if(this.__timeout){ this._emit("timeout"); // BUGFIX: Opera // Since Opera does not fire "error" on network error, fire additional // "error" on timeout (may well be related to network error) if(qx.core.Environment.get("engine.name") === "opera"){ this._emit("error"); }; this.__timeout = false; } else { if(this.__abort){ this._emit("abort"); } else { if(this.__isNetworkError()){ this._emit("error"); } else { this._emit("load"); }; }; }; // Always fire "onloadend" when DONE this._emit("loadend"); }, /** * Check for network error. * * @return {Boolean} Whether a network error occured. */ __isNetworkError : function(){ var error; // Infer the XHR internal error flag from statusText when not aborted. // See http://www.w3.org/TR/XMLHttpRequest2/#error-flag and // http://www.w3.org/TR/XMLHttpRequest2/#the-statustext-attribute // // With file://, statusText is always falsy. Assume network error when // response is empty. if(this._getProtocol() === "file:"){ error = !this.responseText; } else { error = !this.statusText; }; return error; }, /** * Handle faked timeout. */ __onTimeout : function(){ // Basically, mimick http://www.w3.org/TR/XMLHttpRequest2/#timeout-error var nxhr = this.__nativeXhr; this.readyState = qx.bom.request.Xhr.DONE; // Set timeout flag this.__timeout = true; // No longer consider request. Abort. nxhr.abort(); this.responseText = ""; this.responseXML = null; // Signal readystatechange this.__readyStateChange(); }, /** * Normalize status property across browsers. */ __normalizeStatus : function(){ var isDone = this.readyState === qx.bom.request.Xhr.DONE; // BUGFIX: Most browsers // Most browsers tell status 0 when it should be 200 for local files if(this._getProtocol() === "file:" && this.status === 0 && isDone){ if(!this.__isNetworkError()){ this.status = 200; }; }; // BUGFIX: IE // IE sometimes tells 1223 when it should be 204 if(this.status === 1223){ this.status = 204; }; // BUGFIX: Opera // Opera tells 0 for conditional requests when it should be 304 // // Detect response to conditional request that signals fresh cache. if(qx.core.Environment.get("engine.name") === "opera"){ if(isDone && // Done this.__conditional && // Conditional request !this.__abort && // Not aborted this.status === 0){ this.status = 304; }; }; }, /** * Normalize responseXML property across browsers. */ __normalizeResponseXML : function(){ // BUGFIX: IE // IE does not recognize +xml extension, resulting in empty responseXML. // // Check if Content-Type is +xml, verify missing responseXML then parse // responseText as XML. if(qx.core.Environment.get("engine.name") == "mshtml" && (this.getResponseHeader("Content-Type") || "").match(/[^\/]+\/[^\+]+\+xml/) && this.responseXML && !this.responseXML.documentElement){ var dom = new window.ActiveXObject("Microsoft.XMLDOM"); dom.async = false; dom.validateOnParse = false; dom.loadXML(this.responseText); this.responseXML = dom; }; }, /** * Handler for native unload event. */ __onUnload : function(){ try{ // Abort and dispose if(this){ this.dispose(); }; } catch(e) { }; }, /** * Helper method to determine whether browser supports reusing the * same native XHR to send more requests. * @return {Boolean} <code>true</code> if request object reuse is supported */ __supportsManyRequests : function(){ var name = qx.core.Environment.get("engine.name"); var version = qx.core.Environment.get("browser.version"); return !(name == "mshtml" && version < 9 || name == "gecko" && version < 3.5); }, /** * Throw when already disposed. */ __checkDisposed : function(){ if(this.__disposed){ throw new Error("Already disposed"); }; } }, defer : function(){ qx.core.Environment.add("qx.debug.io", false); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /** * Static helpers for handling requests. */ qx.Bootstrap.define("qx.util.Request", { statics : { /** * Whether URL given points to resource that is cross-domain, * i.e. not of same origin. * * @param url {String} URL. * @return {Boolean} Whether URL is cross domain. */ isCrossDomain : function(url){ var result = qx.util.Uri.parseUri(url),location = window.location; if(!location){ return false; }; var protocol = location.protocol; // URL is relative in the sence that it points to origin host if(!(url.indexOf("//") !== -1)){ return false; }; if(protocol.substr(0, protocol.length - 1) == result.protocol && location.host === result.host && location.port === result.port){ return false; }; return true; }, /** * Determine if given HTTP status is considered successful. * * @param status {Number} HTTP status. * @return {Boolean} Whether status is considered successful. */ isSuccessful : function(status){ return (status >= 200 && status < 300 || status === 304); }, /** * Request body is ignored for HTTP method GET and HEAD. * * See http://www.w3.org/TR/XMLHttpRequest2/#the-send-method. * * @param method {String} The HTTP method. * @return {Boolean} Whether request may contain body. */ methodAllowsRequestBody : function(method){ return !((/^(GET)|(HEAD)$/).test(method)); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Carsten Lergenmueller (carstenl) * Fabian Jakobs (fbjakobs) * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Determines browser-dependent information about the transport layer. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Transport", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Returns the maximum number of parallel requests the current browser * supports per host addressed. * * Note that this assumes one connection can support one request at a time * only. Technically, this is not correct when pipelining is enabled (which * it currently is only for IE 8 and Opera). In this case, the number * returned will be too low, as one connection supports multiple pipelined * requests. This is accepted for now because pipelining cannot be * detected from JavaScript and because modern browsers have enough * parallel connections already - it's unlikely an app will require more * than 4 parallel XMLHttpRequests to one server at a time. * * @internal * @return {Integer} Maximum number of parallel requests */ getMaxConcurrentRequestCount : function(){ var maxConcurrentRequestCount; // Parse version numbers. var versionParts = qx.bom.client.Engine.getVersion().split("."); var versionMain = 0; var versionMajor = 0; var versionMinor = 0; // Main number if(versionParts[0]){ versionMain = versionParts[0]; }; // Major number if(versionParts[1]){ versionMajor = versionParts[1]; }; // Minor number if(versionParts[2]){ versionMinor = versionParts[2]; }; // IE 8 gives the max number of connections in a property // see http://msdn.microsoft.com/en-us/library/cc197013(VS.85).aspx if(window.maxConnectionsPerServer){ maxConcurrentRequestCount = window.maxConnectionsPerServer; } else if(qx.bom.client.Engine.getName() == "opera"){ // Opera: 8 total // see http://operawiki.info/HttpProtocol maxConcurrentRequestCount = 8; } else if(qx.bom.client.Engine.getName() == "webkit"){ // Safari: 4 // http://www.stevesouders.com/blog/2008/03/20/roundup-on-parallel-connections/ // Bug #6917: Distinguish Chrome from Safari, Chrome has 6 connections // according to // http://stackoverflow.com/questions/561046/how-many-concurrent-ajax-xmlhttprequest-requests-are-allowed-in-popular-browser maxConcurrentRequestCount = 4; } else if(qx.bom.client.Engine.getName() == "gecko" && ((versionMain > 1) || ((versionMain == 1) && (versionMajor > 9)) || ((versionMain == 1) && (versionMajor == 9) && (versionMinor >= 1)))){ // FF 3.5 (== Gecko 1.9.1): 6 Connections. // see http://gemal.dk/blog/2008/03/18/firefox_3_beta_5_will_have_improved_connection_parallelism/ maxConcurrentRequestCount = 6; } else { // Default is 2, as demanded by RFC 2616 // see http://blogs.msdn.com/ie/archive/2005/04/11/407189.aspx maxConcurrentRequestCount = 2; };;; return maxConcurrentRequestCount; }, /** * Checks whether the app is loaded with SSL enabled which means via https. * * @internal * @return {Boolean} <code>true</code>, if the app runs on https */ getSsl : function(){ return window.location.protocol === "https:"; }, /** * Checks what kind of XMLHttpRequest object the browser supports * for the current protocol, if any. * * The standard XMLHttpRequest is preferred over ActiveX XMLHTTP. * * @internal * @return {String} * <code>"xhr"</code>, if the browser provides standard XMLHttpRequest.<br/> * <code>"activex"</code>, if the browser provides ActiveX XMLHTTP.<br/> * <code>""</code>, if there is not XHR support at all. */ getXmlHttpRequest : function(){ // Standard XHR can be disabled in IE's security settings, // therefore provide ActiveX as fallback. Additionaly, // standard XHR in IE7 is broken for file protocol. var supports = window.ActiveXObject ? (function(){ if(window.location.protocol !== "file:"){ try{ new window.XMLHttpRequest(); return "xhr"; } catch(noXhr) { }; }; try{ new window.ActiveXObject("Microsoft.XMLHTTP"); return "activex"; } catch(noActiveX) { }; })() : (function(){ try{ new window.XMLHttpRequest(); return "xhr"; } catch(noXhr) { }; })(); return supports || ""; } }, defer : function(statics){ qx.core.Environment.add("io.maxrequests", statics.getMaxConcurrentRequestCount); qx.core.Environment.add("io.ssl", statics.getSsl); qx.core.Environment.add("io.xhr", statics.getXmlHttpRequest); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.request.Xhr#open) ************************************************************************ */ /** * This module provides basic IO functionality. It contains three ways to load * data: * * * XMLHttpRequest: {@link #xhr} * * Script tag: {@link #script} * * Script tag using JSONP: {@link #jsonp} */ qx.Bootstrap.define("qx.module.Io", { statics : { /** * Returns a configured XMLHttpRequest object. Using the send method will * finally send the request. * * @param url {String} Mandatory URL to load the data from. * @param settings {Map?} Optional settings map which may contain one of * the following settings: * <ul> * <li><code>method</code> The method of the request. Default: <code>GET</code></li> * <li><code>async</code> flag to mark the request as asynchronous. Default: <code>true</code></li> * <li><code>header</code> A map of request headers.</li> * </ul> * * @attachStatic {qxWeb, io.xhr} * @return {qx.bom.request.Xhr} The request object. */ xhr : function(url, settings){ if(!settings){ settings = { }; }; var xhr = new qx.bom.request.Xhr(); xhr.open(settings.method, url, settings.async); if(settings.header){ var header = settings.header; for(var key in header){ xhr.setRequestHeader(key, header[key]); }; }; return xhr; }, /** * Returns a predefined script tag wrapper which can be used to load data * from cross-domain origins. * * @param url {String} Mandatory URL to load the data from. * @attachStatic {qxWeb, io.script} * @return {qx.bom.request.Script} The request object. */ script : function(url){ var script = new qx.bom.request.Script(); script.open("get", url); return script; }, /** * Returns a predefined script tag wrapper which can be used to load data * from cross-domain origins via JSONP. * * @param url {String} Mandatory URL to load the data from. * @param settings {Map?} Optional settings map which may contain one of * the following settings: * * * <code>callbackName</code>: The name of the callback which will * be called by the loaded script. * * <code>callbackParam</code>: The name of the callback expected by the server * @attachStatic {qxWeb, io.jsonp} * @return {qx.bom.request.Jsonp} The request object. */ jsonp : function(url, settings){ var script = new qx.bom.request.Jsonp(); if(settings && settings.callbackName){ script.setCallbackName(settings.callbackName); }; if(settings && settings.callbackParam){ script.setCallbackParam(settings.callbackParam); }; script.setPrefix("qxWeb.$$"); // needed in case no callback name is given script.open("get", url); return script; } }, defer : function(statics){ qxWeb.$attachStatic({ io : { xhr : statics.xhr, script : statics.script, jsonp : statics.jsonp } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /** * Script loader with interface similar to * <a href="http://www.w3.org/TR/XMLHttpRequest/">XmlHttpRequest</a>. * * The script loader can be used to load scripts from arbitrary sources. * <span class="desktop"> * For JSONP requests, consider the {@link qx.bom.request.Jsonp} transport * that derives from the script loader. * </span> * * <div class="desktop"> * Example: * * <pre class="javascript"> * var req = new qx.bom.request.Script(); * req.onload = function() { * // Script is loaded and parsed and * // globals set are available * } * * req.open("GET", url); * req.send(); * </pre> * </div> */ /* ************************************************************************ #ignore(qx.core.Environment) #require(qx.bom.request.Script#_success) #require(qx.bom.request.Script#abort) #require(qx.bom.request.Script#dispose) #require(qx.bom.request.Script#getAllResponseHeaders) #require(qx.bom.request.Script#getResponseHeader) #require(qx.bom.request.Script#setDetermineSuccess) #require(qx.bom.request.Script#setRequestHeader) ************************************************************************ */ qx.Bootstrap.define("qx.bom.request.Script", { construct : function(){ this.__initXhrProperties(); this.__onNativeLoadBound = qx.Bootstrap.bind(this._onNativeLoad, this); this.__onNativeErrorBound = qx.Bootstrap.bind(this._onNativeError, this); this.__onTimeoutBound = qx.Bootstrap.bind(this._onTimeout, this); this.__headElement = document.head || document.getElementsByTagName("head")[0] || document.documentElement; this._emitter = new qx.event.Emitter(); // BUGFIX: Browsers not supporting error handler // Set default timeout to capture network errors // // Note: The script is parsed and executed, before a "load" is fired. this.timeout = this.__supportsErrorHandler() ? 0 : 15000; }, events : { /** Fired at ready state changes. */ "readystatechange" : "qx.bom.request.Script", /** Fired on error. */ "error" : "qx.bom.request.Script", /** Fired at loadend. */ "loadend" : "qx.bom.request.Script", /** Fired on timeouts. */ "timeout" : "qx.bom.request.Script", /** Fired when the request is aborted. */ "abort" : "qx.bom.request.Script", /** Fired on successful retrieval. */ "load" : "qx.bom.request.Script" }, members : { /** * {Number} Ready state. * * States can be: * UNSENT: 0, * OPENED: 1, * LOADING: 2, * LOADING: 3, * DONE: 4 * * Contrary to {@link qx.bom.request.Xhr#readyState}, the script transport * does not receive response headers. For compatibility, another LOADING * state is implemented that replaces the HEADERS_RECEIVED state. */ readyState : null, /** * {Number} The status code. * * Note: The script transport cannot determine the HTTP status code. */ status : null, /** * {String} The status text. * * The script transport does not receive response headers. For compatibility, * the statusText property is set to the status casted to string. */ statusText : null, /** * {Number} Timeout limit in milliseconds. * * 0 (default) means no timeout. */ timeout : null, /** * {Function} Function that is executed once the script was loaded. */ __determineSuccess : null, /** * Add an event listener for the given event name. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function to execute when the event is fired * @param ctx {var?} The context of the listener. * @return {qx.bom.request.Script} Self for chaining. */ on : function(name, listener, ctx){ this._emitter.on(name, listener, ctx); return this; }, /** * Initializes (prepares) request. * * @param method {String} * The HTTP method to use. * This parameter exists for compatibility reasons. The script transport * does not support methods other than GET. * @param url {String} * The URL to which to send the request. */ open : function(method, url){ if(this.__disposed){ return; }; // Reset XHR properties that may have been set by previous request this.__initXhrProperties(); this.__abort = null; this.__url = url; if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Open native request with " + "url: " + url); }; this._readyStateChange(1); }, /** * Appends a query parameter to URL. * * This method exists for compatibility reasons. The script transport * does not support request headers. However, many services parse query * parameters like request headers. * * Note: The request must be initialized before using this method. * * @param key {String} * The name of the header whose value is to be set. * @param value {String} * The value to set as the body of the header. * @return {qx.bom.request.Script} Self for chaining. */ setRequestHeader : function(key, value){ if(this.__disposed){ return null; }; var param = { }; if(this.readyState !== 1){ throw new Error("Invalid state"); }; param[key] = value; this.__url = qx.util.Uri.appendParamsToUrl(this.__url, param); return this; }, /** * Sends request. * @return {qx.bom.request.Script} Self for chaining. */ send : function(){ if(this.__disposed){ return null; }; var script = this.__createScriptElement(),head = this.__headElement,that = this; if(this.timeout > 0){ this.__timeoutId = window.setTimeout(this.__onTimeoutBound, this.timeout); }; if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Send native request"); }; // Attach script to DOM head.insertBefore(script, head.firstChild); // The resource is loaded once the script is in DOM. // Assume HEADERS_RECEIVED and LOADING and dispatch async. window.setTimeout(function(){ that._readyStateChange(2); that._readyStateChange(3); }); return this; }, /** * Aborts request. * @return {qx.bom.request.Script} Self for chaining. */ abort : function(){ if(this.__disposed){ return null; }; this.__abort = true; this.__disposeScriptElement(); this._emit("abort"); return this; }, /** * Helper to emit events and call the callback methods. * @param event {String} The name of the event. */ _emit : function(event){ this["on" + event](); this._emitter.emit(event, this); }, /** * Event handler for an event that fires at every state change. * * Replace with custom method to get informed about the communication progress. */ onreadystatechange : function(){ }, /** * Event handler for XHR event "load" that is fired on successful retrieval. * * Note: This handler is called even when an invalid script is returned. * * Warning: Internet Explorer < 9 receives a false "load" for invalid URLs. * This "load" is fired about 2 seconds after sending the request. To * distinguish from a real "load", consider defining a custom check * function using {@link #setDetermineSuccess} and query the status * property. However, the script loaded needs to have a known impact on * the global namespace. If this does not work for you, you may be able * to set a timeout lower than 2 seconds, depending on script size, * complexity and execution time. * * Replace with custom method to listen to the "load" event. */ onload : function(){ }, /** * Event handler for XHR event "loadend" that is fired on retrieval. * * Note: This handler is called even when a network error (or similar) * occurred. * * Replace with custom method to listen to the "loadend" event. */ onloadend : function(){ }, /** * Event handler for XHR event "error" that is fired on a network error. * * Note: Some browsers do not support the "error" event. * * Replace with custom method to listen to the "error" event. */ onerror : function(){ }, /** * Event handler for XHR event "abort" that is fired when request * is aborted. * * Replace with custom method to listen to the "abort" event. */ onabort : function(){ }, /** * Event handler for XHR event "timeout" that is fired when timeout * interval has passed. * * Replace with custom method to listen to the "timeout" event. */ ontimeout : function(){ }, /** * Get a single response header from response. * * Note: This method exists for compatibility reasons. The script * transport does not receive response headers. * * @param key {String} * Key of the header to get the value from. * @return {String|null} Warning message or <code>null</code> if the request * is disposed */ getResponseHeader : function(key){ if(this.__disposed){ return null; }; if(this.__environmentGet("qx.debug")){ qx.Bootstrap.debug("Response header cannot be determined for " + "requests made with script transport."); }; return "unknown"; }, /** * Get all response headers from response. * * Note: This method exists for compatibility reasons. The script * transport does not receive response headers. * @return {String|null} Warning message or <code>null</code> if the request * is disposed */ getAllResponseHeaders : function(){ if(this.__disposed){ return null; }; if(this.__environmentGet("qx.debug")){ qx.Bootstrap.debug("Response headers cannot be determined for" + "requests made with script transport."); }; return "Unknown response headers"; }, /** * Determine if loaded script has expected impact on global namespace. * * The function is called once the script was loaded and must return a * boolean indicating if the response is to be considered successful. * * @param check {Function} Function executed once the script was loaded. * */ setDetermineSuccess : function(check){ this.__determineSuccess = check; }, /** * Dispose object. */ dispose : function(){ var script = this.__scriptElement; if(!this.__disposed){ // Prevent memory leaks if(script){ script.onload = script.onreadystatechange = null; this.__disposeScriptElement(); }; if(this.__timeoutId){ window.clearTimeout(this.__timeoutId); }; this.__disposed = true; }; }, /* --------------------------------------------------------------------------- PROTECTED --------------------------------------------------------------------------- */ /** * Get URL of request. * * @return {String} URL of request. */ _getUrl : function(){ return this.__url; }, /** * Get script element used for request. * * @return {Element} Script element. */ _getScriptElement : function(){ return this.__scriptElement; }, /** * Handle timeout. */ _onTimeout : function(){ this.__failure(); if(!this.__supportsErrorHandler()){ this._emit("error"); }; this._emit("timeout"); if(!this.__supportsErrorHandler()){ this._emit("loadend"); }; }, /** * Handle native load. */ _onNativeLoad : function(){ var script = this.__scriptElement,determineSuccess = this.__determineSuccess,that = this; // Aborted request must not fire load if(this.__abort){ return; }; // BUGFIX: IE < 9 // When handling "readystatechange" event, skip if readyState // does not signal loaded script if(this.__environmentGet("engine.name") === "mshtml" && this.__environmentGet("browser.documentmode") < 9){ if(!(/loaded|complete/).test(script.readyState)){ return; } else { if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Received native readyState: loaded"); }; }; }; if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Received native load"); }; // Determine status by calling user-provided check function if(determineSuccess){ // Status set before has higher precedence if(!this.status){ this.status = determineSuccess() ? 200 : 500; }; }; if(this.status === 500){ if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Detected error"); }; }; if(this.__timeoutId){ window.clearTimeout(this.__timeoutId); }; window.setTimeout(function(){ that._success(); that._readyStateChange(4); that._emit("load"); that._emit("loadend"); }); }, /** * Handle native error. */ _onNativeError : function(){ this.__failure(); this._emit("error"); this._emit("loadend"); }, /* --------------------------------------------------------------------------- PRIVATE --------------------------------------------------------------------------- */ /** * {Element} Script element */ __scriptElement : null, /** * {Element} Head element */ __headElement : null, /** * {String} URL */ __url : "", /** * {Function} Bound _onNativeLoad handler. */ __onNativeLoadBound : null, /** * {Function} Bound _onNativeError handler. */ __onNativeErrorBound : null, /** * {Function} Bound _onTimeout handler. */ __onTimeoutBound : null, /** * {Number} Timeout timer iD. */ __timeoutId : null, /** * {Boolean} Whether request was aborted. */ __abort : null, /** * {Boolean} Whether request was disposed. */ __disposed : null, /* --------------------------------------------------------------------------- HELPER --------------------------------------------------------------------------- */ /** * Initialize properties. */ __initXhrProperties : function(){ this.readyState = 0; this.status = 0; this.statusText = ""; }, /** * Change readyState. * * @param readyState {Number} The desired readyState */ _readyStateChange : function(readyState){ this.readyState = readyState; this._emit("readystatechange"); }, /** * Handle success. */ _success : function(){ this.__disposeScriptElement(); this.readyState = 4; // By default, load is considered successful if(!this.status){ this.status = 200; }; this.statusText = "" + this.status; }, /** * Handle failure. */ __failure : function(){ this.__disposeScriptElement(); this.readyState = 4; this.status = 0; this.statusText = null; }, /** * Looks up whether browser supports error handler. * * @return {Boolean} Whether browser supports error handler. */ __supportsErrorHandler : function(){ var isLegacyIe = this.__environmentGet("engine.name") === "mshtml" && this.__environmentGet("browser.documentmode") < 9; var isOpera = this.__environmentGet("engine.name") === "opera"; return !(isLegacyIe || isOpera); }, /** * Create and configure script element. * * @return {Element} Configured script element. */ __createScriptElement : function(){ var script = this.__scriptElement = document.createElement("script"); script.src = this.__url; script.onerror = this.__onNativeErrorBound; script.onload = this.__onNativeLoadBound; // BUGFIX: IE < 9 // Legacy IEs do not fire the "load" event for script elements. // Instead, they support the "readystatechange" event if(this.__environmentGet("engine.name") === "mshtml" && this.__environmentGet("browser.documentmode") < 9){ script.onreadystatechange = this.__onNativeLoadBound; }; return script; }, /** * Remove script element from DOM. */ __disposeScriptElement : function(){ var script = this.__scriptElement; if(script && script.parentNode){ this.__headElement.removeChild(script); }; }, /** * Proxy Environment.get to guard against env not being present yet. * * @param key {String} Environment key. * @return {var} Value of the queried environment key * @lint environmentNonLiteralKey(key) */ __environmentGet : function(key){ if(qx && qx.core && qx.core.Environment){ return qx.core.Environment.get(key); } else { if(key === "engine.name"){ return qx.bom.client.Engine.getName(); }; if(key === "browser.documentmode"){ return qx.bom.client.Browser.getDocumentMode(); }; if(key == "qx.debug.io"){ return false; }; throw new Error("Unknown environment key at this phase"); }; } }, defer : function(){ if(qx && qx.core && qx.core.Environment){ qx.core.Environment.add("qx.debug.io", false); }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.request.Script#open) #require(qx.bom.request.Script#on) #require(qx.bom.request.Script#onreadystatechange) #require(qx.bom.request.Script#onload) #require(qx.bom.request.Script#onloadend) #require(qx.bom.request.Script#onerror) #require(qx.bom.request.Script#onabort) #require(qx.bom.request.Script#ontimeout) #require(qx.bom.request.Script#send) ************************************************************************ */ /** * A special script loader handling JSONP responses. Automatically * provides callbacks and populates responseJson property. * * Example: * * <pre class="javascript"> * var req = new qx.bom.request.Jsonp(); * * // Some services have a fixed callback name * // req.setCallbackName("callback"); * * req.onload = function() { * // Handle data received * req.responseJson; * } * * req.open("GET", url); * req.send(); * </pre> */ qx.Bootstrap.define("qx.bom.request.Jsonp", { extend : qx.bom.request.Script, construct : function(){ // Borrow super-class constructor qx.bom.request.Script.apply(this); this.__generateId(); }, members : { /** * {Object} Parsed JSON response. */ responseJson : null, /** * {Number} Identifier of this instance. */ __id : null, /** * {String} Callback parameter. */ __callbackParam : null, /** * {String} Callback name. */ __callbackName : null, /** * {Boolean} Whether callback was called. */ __callbackCalled : null, /** * {Boolean} Whether a custom callback was created automatically. */ __customCallbackCreated : null, /** * {String} The generated URL for the current request */ __generatedUrl : null, /** * {Boolean} Whether request was disposed. */ __disposed : null, /** Prefix used for the internal callback name. */ __prefix : "", /** * Initializes (prepares) request. * * @param method {String} * The HTTP method to use. * This parameter exists for compatibility reasons. The script transport * does not support methods other than GET. * @param url {String} * The URL to which to send the request. */ open : function(method, url){ if(this.__disposed){ return; }; var query = { },callbackParam,callbackName,that = this; // Reset properties that may have been set by previous request this.responseJson = null; this.__callbackCalled = false; callbackParam = this.__callbackParam || "callback"; callbackName = this.__callbackName || this.__prefix + "qx.bom.request.Jsonp." + this.__id + ".callback"; // Default callback if(!this.__callbackName){ // Store globally available reference to this object this.constructor[this.__id] = this; } else { // Dynamically create globally available callback (if it does not // exist yet) with user defined name. Delegate to this object’s // callback method. if(!window[this.__callbackName]){ this.__customCallbackCreated = true; window[this.__callbackName] = function(data){ that.callback(data); }; } else { { }; }; }; { }; query[callbackParam] = callbackName; this.__generatedUrl = url = qx.util.Uri.appendParamsToUrl(url, query); this.__callBase("open", [method, url]); }, /** * Callback provided for JSONP response to pass data. * * Called internally to populate responseJson property * and indicate successful status. * * Note: If you write a custom callback you’ll need to call * this method in order to notify the request about the data * loaded. Writing a custom callback should not be necessary * in most cases. * * @param data {Object} JSON */ callback : function(data){ if(this.__disposed){ return; }; // Signal callback was called this.__callbackCalled = true; { }; // Set response this.responseJson = data; // Delete global reference to this this.constructor[this.__id] = undefined; this.__deleteCustomCallback(); }, /** * Set callback parameter. * * Some JSONP services expect the callback name to be passed labeled with a * special URL parameter key, e.g. "jsonp" in "?jsonp=myCallback". The * default is "callback". * * @param param {String} Name of the callback parameter. * @return {qx.bom.request.Jsonp} Self reference for chaining. */ setCallbackParam : function(param){ this.__callbackParam = param; return this; }, /** * Set callback name. * * Must be set to the name of the callback function that is called by the * script returned from the JSONP service. By default, the callback name * references this instance’s {@link #callback} method, allowing to connect * multiple JSONP responses to different requests. * * If the JSONP service allows to set custom callback names, it should not * be necessary to change the default. However, some services use a fixed * callback name. This is when setting the callbackName is useful. A * function is created and made available globally under the given name. * The function receives the JSON data and dispatches it to this instance’s * {@link #callback} method. Please note that this function is only created * if it does not exist before. * * @param name {String} Name of the callback function. * @return {qx.bom.request.Jsonp} Self reference for chaining. */ setCallbackName : function(name){ this.__callbackName = name; return this; }, /** * Set the prefix used in front of 'qx.' in case 'qx' is not available * (for qx.Website e.g.) * @internal * @param prefix {String} The prefix to put in front of 'qx' */ setPrefix : function(prefix){ this.__prefix = prefix; }, /** * Returns the generated URL for the current / last request * * @internal * @return {String} The current generated URL for the request */ getGeneratedUrl : function(){ return this.__generatedUrl; }, dispose : function(){ // In case callback was not called this.__deleteCustomCallback(); this.__callBase("dispose"); }, /** * Handle native load. */ _onNativeLoad : function(){ // Indicate erroneous status (500) if callback was not called. // // Why 500? 5xx belongs to the range of server errors. If the callback was // not called, it is assumed the server failed to provide an appropriate // response. Since the exact reason of the error is unknown, the most // generic message ("500 Internal Server Error") is chosen. this.status = this.__callbackCalled ? 200 : 500; this.__callBase("_onNativeLoad"); }, /** * Delete custom callback if dynamically created before. */ __deleteCustomCallback : function(){ if(this.__customCallbackCreated && window[this.__callbackName]){ window[this.__callbackName] = undefined; this.__customCallbackCreated = false; }; }, /** * Call overriden method. * * @param method {String} Name of the overriden method. * @param args {Array} Arguments. */ __callBase : function(method, args){ qx.bom.request.Script.prototype[method].apply(this, args || []); }, /** * Generate ID. */ __generateId : function(){ // Add random digits to date to allow immediately following requests // that may be send at the same time this.__id = "qx" + (new Date().valueOf()) + ("" + Math.random()).substring(2, 5); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Environment) #require(qx.module.Manipulating) #require(qx.module.Traversing) #require(qx.module.Css) #require(qx.module.Attribute) ************************************************************************ */ /** * Provides a way to block elements so they will no longer receive (native) * events by overlaying them with a div. * For Internet Explorer, an additional Iframe element will be overlayed since * native form controls cannot be blocked otherwise. * * The blocker can also be applied to the entire document, e.g.: * * <pre class="javascript"> * q(document).block(); * </pre> */ qxWeb.define("qx.module.Blocker", { statics : { /** * Attaches a blocker div (and additionally a blocker Iframe for IE) to the * given element. * * @param item {Element|Document} The element to be overlaid with the blocker * @param color {String} The color for the blocker element (any CSS color value) * @param opacity {Number} The CSS opacity value for the blocker * @param zIndex {Number} The zIndex value for the blocker */ __attachBlocker : function(item, color, opacity, zIndex){ var win = qxWeb.getWindow(item); var isDocument = qxWeb.isDocument(item); if(!item.__blocker){ item.__blocker = { div : qxWeb.create("<div/>") }; if((qxWeb.env.get("engine.name") == "mshtml")){ item.__blocker.iframe = qx.module.Blocker.__getIframeElement(win); }; }; qx.module.Blocker.__styleBlocker(item, color, opacity, zIndex, isDocument); item.__blocker.div.appendTo(win.document.body); if(item.__blocker.iframe){ item.__blocker.iframe.appendTo(win.document.body); }; if(isDocument){ qxWeb(win).on("resize", qx.module.Blocker.__onWindowResize); }; }, /** * Styles the blocker element(s) * * @param item {Element|Document} The element to be overlaid with the blocker * @param color {String} The color for the blocker element (any CSS color value) * @param opacity {Number} The CSS opacity value for the blocker * @param zIndex {Number} The zIndex value for the blocker * @param isDocument {Boolean} Whether the item is a document node */ __styleBlocker : function(item, color, opacity, zIndex, isDocument){ var qItem = qxWeb(item); var styles = { "zIndex" : zIndex, "display" : "block", "position" : "absolute", "backgroundColor" : color, "opacity" : opacity, "width" : qItem.getWidth() + "px", "height" : qItem.getHeight() + "px" }; if(isDocument){ styles.top = 0 + "px"; styles.left = 0 + "px"; } else { var pos = qItem.getOffset(); styles.top = pos.top + "px"; styles.left = pos.left + "px"; }; item.__blocker.div.setStyles(styles); if(item.__blocker.iframe){ styles.zIndex = styles.zIndex - 1; styles.backgroundColor = "transparent"; styles.opacity = 0; item.__blocker.iframe.setStyles(styles); }; }, /** * Creates an iframe element used as a blocker in IE * * @param win {Window} The parent window of the item to be blocked * @return {Element} Iframe blocker */ __getIframeElement : function(win){ var iframe = qxWeb.create('<iframe></iframe>'); iframe.setAttributes({ frameBorder : 0, frameSpacing : 0, marginWidth : 0, marginHeight : 0, hspace : 0, vspace : 0, border : 0, allowTransparency : false, src : "javascript:false" }); return iframe; }, /** * Callback for the Window's resize event. Applies the window's new sizes * to the blocker element(s). * * @param ev {Event} resize event */ __onWindowResize : function(ev){ var win = this[0]; var size = { width : this.getWidth() + "px", height : this.getHeight() + "px" }; qxWeb(win.document.__blocker.div).setStyles(size); if(win.document.__blocker.iframe){ qxWeb(win.document.__blocker.iframe).setStyles(size); }; }, /** * Removes the given item's blocker element(s) from the DOM * * @param item {Element} Blocked element * @param index {Number} index of the item in the collection */ __detachBlocker : function(item, index){ if(!item.__blocker){ return; }; item.__blocker.div.remove(); if(item.__blocker.iframe){ item.__blocker.iframe.remove(); }; if(qxWeb.isDocument(item)){ qxWeb(qxWeb.getWindow(item)).off("resize", qx.module.Blocker.__onWindowResize); }; }, /** * Adds an overlay to all items in the collection that intercepts mouse * events. * * @attach {qxWeb} * @param color {String ? transparent} The color for the blocker element (any CSS color value) * @param opacity {Float ? 0} The CSS opacity value for the blocker * @param zIndex {Number ? 10000} The zIndex value for the blocker * @return {qxWeb} The collection for chaining */ block : function(color, opacity, zIndex){ if(!this[0]){ return this; }; color = color || "transparent"; opacity = opacity || 0; zIndex = zIndex || 10000; this.forEach(function(item, index){ qx.module.Blocker.__attachBlocker(item, color, opacity, zIndex); }); return this; }, /** * Removes the blockers from all items in the collection * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ unblock : function(){ if(!this[0]){ return this; }; this.forEach(qx.module.Blocker.__detachBlocker); return this; } }, defer : function(statics){ qxWeb.$attach({ "block" : statics.block, "unblock" : statics.unblock }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Css) #require(qx.module.Event) ************************************************************************ */ /** * Cross browser animation layer. It uses feature detection to check if CSS * animations are available and ready to use. If not, a JavaScript-based * fallback will be used. */ qx.Bootstrap.define("qx.module.Animation", { events : { /** Fired when an animation starts. */ "animationStart" : undefined, /** Fired when an animation has ended one iteration. */ "animationIteration" : undefined, /** Fired when an animation has ended. */ "animationEnd" : undefined }, statics : { /** * Returns the stored animation handles. The handles are only * available while an animation is running. * * @internal * @return {Array} An array of animation handles. */ getAnimationHandles : function(){ var animationHandles = []; for(var i = 0;i < this.length;i++){ animationHandles[i] = this[i].$$animation; }; return animationHandles; }, /** * Animation description used in {@link #fadeOut}. */ _fadeOut : { duration : 700, timing : "ease-out", keep : 100, keyFrames : { '0' : { opacity : 1 }, '100' : { opacity : 0, display : "none" } } }, /** * Animation description used in {@link #fadeIn}. */ _fadeIn : { duration : 700, timing : "ease-in", keep : 100, keyFrames : { '0' : { opacity : 0 }, '100' : { opacity : 1 } } }, /** * Starts the animation with the given description. * The description should be a map, which could look like this: * * <pre class="javascript"> * { * "duration": 1000, * "keep": 100, * "keyFrames": { * 0 : {"opacity": 1, "scale": 1}, * 100 : {"opacity": 0, "scale": 0} * }, * "origin": "50% 50%", * "repeat": 1, * "timing": "ease-out", * "alternate": false, * "delay": 2000 * } * </pre> * * *duration* is the time in milliseconds one animation cycle should take. * * *keep* is the key frame to apply at the end of the animation. (optional) * * *keyFrames* is a map of separate frames. Each frame is defined by a * number which is the percentage value of time in the animation. The value * is a map itself which holds css properties or transforms * (Transforms only for CSS Animations). * * *origin* maps to the transform origin {@link qx.bom.element.Transform#setOrigin} * (Only for CSS animations). * * *repeat* is the amount of time the animation should be run in * sequence. You can also use "infinite". * * *timing* takes one of these predefined values: * <code>ease</code> | <code>linear</code> | <code>ease-in</code> * | <code>ease-out</code> | <code>ease-in-out</code> | * <code>cubic-bezier(&lt;number&gt;, &lt;number&gt;, &lt;number&gt;, &lt;number&gt;)</code> * (cubic-bezier only available for CSS animations) * * *alternate* defines if every other animation should be run in reverse order. * * *delay* is the time in milliseconds the animation should wait before start. * * @attach {qxWeb} * @param desc {Map} The animation's description. * @param duration {Number?} The duration in milliseconds of the animation, * which will override the duration given in the description. * @return {qxWeb} The collection for chaining. */ animate : function(desc, duration){ qx.module.Animation._animate.bind(this)(desc, duration, false); return this; }, /** * Starts an animation in reversed order. For further details, take a look at * the {@link #animate} method. * @attach {qxWeb} * @param desc {Map} The animation's description. * @param duration {Number?} The duration in milliseconds of the animation, * which will override the duration given in the description. * @return {qxWeb} The collection for chaining. */ animateReverse : function(desc, duration){ qx.module.Animation._animate.bind(this)(desc, duration, true); return this; }, /** * Animation execute either regular or reversed direction. * @param desc {Map} The animation's description. * @param duration {Number?} The duration in milliseconds of the animation, * which will override the duration given in the description. * @param reverse {Boolean} <code>true</code>, if the animation should be reversed */ _animate : function(desc, duration, reverse){ for(var i = 0;i < this.length;i++){ var el = this[i]; // stop all running animations if(el.$$animation){ el.$$animation.stop(); }; if(reverse){ var handle = qx.bom.element.Animation.animateReverse(el, desc, duration); } else { var handle = qx.bom.element.Animation.animate(el, desc, duration); }; var self = this; // only register for the first element if(i == 0){ handle.on("start", function(){ self.emit("animationStart"); }, handle); handle.on("iteration", function(){ self.emit("animationIteration"); }, handle); }; handle.on("end", function(){ for(var i = 0;i < self.length;i++){ if(self[i].$$animation){ return; }; }; self.emit("animationEnd"); }, el); }; }, /** * Manipulates the play state of the animation. * This can be used to continue an animation when paused. * @attach {qxWeb} * @return {qxWeb} The collection for chaining. */ play : function(){ for(var i = 0;i < this.length;i++){ var handle = this[i].$$animation; if(handle){ handle.play(); }; }; return this; }, /** * Manipulates the play state of the animation. * This can be used to pause an animation when running. * @attach {qxWeb} * @return {qxWeb} The collection for chaining. */ pause : function(){ for(var i = 0;i < this.length;i++){ var handle = this[i].$$animation; if(handle){ handle.pause(); }; }; return this; }, /** * Stops a running animation. * @attach {qxWeb} * @return {qxWeb} The collection for chaining. */ stop : function(){ for(var i = 0;i < this.length;i++){ var handle = this[i].$$animation; if(handle){ handle.stop(); }; }; return this; }, /** * Returns whether an animation is running or not. * @attach {qxWeb} * @return {Boolean} <code>true</code>, if an animation is running. */ isPlaying : function(){ for(var i = 0;i < this.length;i++){ var handle = this[i].$$animation; if(handle && handle.isPlaying()){ return true; }; }; return false; }, /** * Returns whether an animation has ended or not. * @attach {qxWeb} * @return {Boolean} <code>true</code>, if an animation has ended. */ isEnded : function(){ for(var i = 0;i < this.length;i++){ var handle = this[i].$$animation; if(handle && !handle.isEnded()){ return false; }; }; return true; }, /** * Fades in all elements in the collection. * @attach {qxWeb} * @param duration {Number?} The duration in milliseconds. * @return {qxWeb} The collection for chaining. */ fadeIn : function(duration){ // remove 'display: none' style this.setStyle("display", ""); return this.animate(qx.module.Animation._fadeIn, duration); }, /** * Fades out all elements in the collection. * @attach {qxWeb} * @param duration {Number?} The duration in milliseconds. * @return {qxWeb} The collection for chaining. */ fadeOut : function(duration){ return this.animate(qx.module.Animation._fadeOut, duration); } }, defer : function(statics){ qxWeb.$attach({ "animate" : statics.animate, "animateReverse" : statics.animateReverse, "fadeIn" : statics.fadeIn, "fadeOut" : statics.fadeOut, "play" : statics.play, "pause" : statics.pause, "stop" : statics.stop, "isEnded" : statics.isEnded, "isPlaying" : statics.isPlaying, "getAnimationHandles" : statics.getAnimationHandles }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Wrapper for {@link qx.bom.element.AnimationCss} and * {@link qx.bom.element.AnimationJs}. It offers the pubilc API and decides using * feature checks either to use CSS animations or JS animations. * * If you use this class, the restrictions of the JavaScript animations apply. * This means that you can not use transforms and custom bezier timing functions. */ qx.Bootstrap.define("qx.bom.element.Animation", { statics : { /** * This function takes care of the feature check and starts the animation. * It takes a DOM element to apply the animation to, and a description. * The description should be a map, which could look like this: * * <pre class="javascript"> * { * "duration": 1000, * "keep": 100, * "keyFrames": { * 0 : {"opacity": 1, "scale": 1}, * 100 : {"opacity": 0, "scale": 0} * }, * "origin": "50% 50%", * "repeat": 1, * "timing": "ease-out", * "alternate": false, * "delay" : 2000 * } * </pre> * * *duration* is the time in milliseconds one animation cycle should take. * * *keep* is the key frame to apply at the end of the animation. (optional) * Keep in mind that the keep key is reversed in case you use an reverse * animation or set the alternate key and a even repeat count. * * *keyFrames* is a map of separate frames. Each frame is defined by a * number which is the percentage value of time in the animation. The value * is a map itself which holds css properties or transforms * {@link qx.bom.element.Transform} (Transforms only for CSS Animations). * * *origin* maps to the transform origin {@link qx.bom.element.Transform#setOrigin} * (Only for CSS animations). * * *repeat* is the amount of time the animation should be run in * sequence. You can also use "infinite". * * *timing* takes one of the predefined value: * <code>ease</code> | <code>linear</code> | <code>ease-in</code> * | <code>ease-out</code> | <code>ease-in-out</code> | * <code>cubic-bezier(&lt;number&gt;, &lt;number&gt;, &lt;number&gt;, &lt;number&gt;)</code> * (cubic-bezier only available for CSS animations) * * *alternate* defines if every other animation should be run in reverse order. * * *delay* is the time in milliseconds the animation should wait before start. * * @param el {Element} The element to animate. * @param desc {Map} The animations description. * @param duration {Integer?} The duration in milliseconds of the animation * which will override the duration given in the description. * @return {qx.bom.element.AnimationHandle} AnimationHandle instance to control * the animation. */ animate : function(el, desc, duration){ var onlyCssKeys = qx.bom.element.Animation.__hasOnlyCssKeys(el, desc.keyFrames); if(qx.core.Environment.get("css.animation") && onlyCssKeys){ return qx.bom.element.AnimationCss.animate(el, desc, duration); } else { return qx.bom.element.AnimationJs.animate(el, desc, duration); }; }, /** * Starts an animation in reversed order. For further details, take a look at * the {@link #animate} method. * @param el {Element} The element to animate. * @param desc {Map} The animations description. * @param duration {Integer?} The duration in milliseconds of the animation * which will override the duration given in the description. * @return {qx.bom.element.AnimationHandle} AnimationHandle instance to control * the animation. */ animateReverse : function(el, desc, duration){ var onlyCssKeys = qx.bom.element.Animation.__hasOnlyCssKeys(el, desc.keyFrames); if(qx.core.Environment.get("css.animation") && onlyCssKeys){ return qx.bom.element.AnimationCss.animateReverse(el, desc, duration); } else { return qx.bom.element.AnimationJs.animateReverse(el, desc, duration); }; }, /** * Detection helper which detects if only CSS keys are in * the animations key frames. * @param el {Element} The element to check for the styles. * @param keyFrames {Map} The keyFrames of the animation. * @return {Boolean} <code>true</code> if only css properties are included. */ __hasOnlyCssKeys : function(el, keyFrames){ var keys = []; for(var nr in keyFrames){ var frame = keyFrames[nr]; for(var key in frame){ if(keys.indexOf(key) == -1){ keys.push(key); }; }; }; var transformKeys = ["scale", "rotate", "skew", "translate"]; for(var i = 0;i < keys.length;i++){ var key = qx.lang.String.camelCase(keys[i]); if(!(key in el.style)){ // check for transform keys if(transformKeys.indexOf(keys[i]) != -1){ continue; }; return false; }; }; return true; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.Stylesheet) ************************************************************************ */ /** * Responsible for checking all relevant animation properties. * * Spec: http://www.w3.org/TR/css3-animations/ * * @internal */ qx.Bootstrap.define("qx.bom.client.CssAnimation", { statics : { /** * Main check method which returns an object if CSS animations are * supported. This object contains all necessary keys to work with CSS * animations. * <ul> * <li><code>name</code> The name of the css animation style</li> * <li><code>play-state</code> The name of the play-state style</li> * <li><code>start-event</code> The name of the start event</li> * <li><code>iternation-event</code> The name of the iternation event</li> * <li><code>end-event</code> The name of the end event</li> * <li><code>fill-mode</code> The fill-mode style</li> * <li><code>keyframes</code> The name of the keyframes selector.</li> * </ul> * * @internal * @return {Object|null} The described object or null, if animations are * not supported. */ getSupport : function(){ var name = qx.bom.client.CssAnimation.getName(); if(name != null){ return { "name" : name, "play-state" : qx.bom.client.CssAnimation.getPlayState(), "start-event" : qx.bom.client.CssAnimation.getAnimationStart(), "iteration-event" : qx.bom.client.CssAnimation.getAnimationIteration(), "end-event" : qx.bom.client.CssAnimation.getAnimationEnd(), "fill-mode" : qx.bom.client.CssAnimation.getFillMode(), "keyframes" : qx.bom.client.CssAnimation.getKeyFrames() }; }; return null; }, /** * Checks for the 'animation-fill-mode' CSS style. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getFillMode : function(){ return qx.bom.Style.getPropertyName("AnimationFillMode"); }, /** * Checks for the 'animation-play-state' CSS style. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getPlayState : function(){ return qx.bom.Style.getPropertyName("AnimationPlayState"); }, /** * Checks for the style name used for animations. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getName : function(){ return qx.bom.Style.getPropertyName("animation"); }, /** * Checks for the event name of animation start. * @internal * @return {String} The name of the event. */ getAnimationStart : function(){ var mapping = { "msAnimation" : "MSAnimationStart", "WebkitAnimation" : "webkitAnimationStart", "MozAnimation" : "animationstart", "OAnimation" : "oAnimationStart", "animation" : "animationstart" }; return mapping[this.getName()]; }, /** * Checks for the event name of animation end. * @internal * @return {String} The name of the event. */ getAnimationIteration : function(){ var mapping = { "msAnimation" : "MSAnimationIteration", "WebkitAnimation" : "webkitAnimationIteration", "MozAnimation" : "animationiteration", "OAnimation" : "oAnimationIteration", "animation" : "animationiteration" }; return mapping[this.getName()]; }, /** * Checks for the event name of animation end. * @internal * @return {String} The name of the event. */ getAnimationEnd : function(){ var mapping = { "msAnimation" : "MSAnimationEnd", "WebkitAnimation" : "webkitAnimationEnd", "MozAnimation" : "animationend", "OAnimation" : "oAnimationEnd", "animation" : "animationend" }; return mapping[this.getName()]; }, /** * Checks what selector should be used to add keyframes to stylesheets. * @internal * @return {String|null} The name of the selector or null, if the selector * is not supported. */ getKeyFrames : function(){ var prefixes = qx.bom.Style.VENDOR_PREFIXES; var keyFrames = []; for(var i = 0;i < prefixes.length;i++){ var key = "@" + qx.bom.Style.getCssName(prefixes[i]) + "-keyframes"; keyFrames.push(key); }; keyFrames.unshift("@keyframes"); var sheet = qx.bom.Stylesheet.createElement(); for(var i = 0;i < keyFrames.length;i++){ try{ qx.bom.Stylesheet.addRule(sheet, keyFrames[i] + " name", ""); return keyFrames[i]; } catch(e) { }; }; return null; }, /** * Checks for the requestAnimationFrame method and return the prefixed name. * @internal * @return {String|null} A string the method name or null, if the method * is not supported. */ getRequestAnimationFrame : function(){ var choices = ["requestAnimationFrame", "msRequestAnimationFrame", "webkitRequestAnimationFrame", "mozRequestAnimationFrame", "oRequestAnimationFrame"]; for(var i = 0;i < choices.length;i++){ if(window[choices[i]] != undefined){ return choices[i]; }; }; return null; } }, defer : function(statics){ qx.core.Environment.add("css.animation", statics.getSupport); qx.core.Environment.add("css.animation.requestframe", statics.getRequestAnimationFrame); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is responsible for applying CSS3 animations to plain DOM elements. * * The implementation is mostly a cross-browser wrapper for applying the * animations, including transforms. If the browser does not support * CSS animations, but you have set a keep frame, the keep frame will be applied * immediately, thus making the animations optional. * * The API aligns closely to the spec wherever possible. * * http://www.w3.org/TR/css3-animations/ * * {@link qx.bom.element.Animation} is the class, which takes care of the * feature detection for CSS animations and decides which implementation * (CSS or JavaScript) should be used. Most likely, this implementation should * be the one to use. */ qx.Bootstrap.define("qx.bom.element.AnimationCss", { statics : { // initialization __sheet : null, __rulePrefix : "Anni", __id : 0, /** Static map of rules */ __rules : { }, /** The used keys for transforms. */ __transitionKeys : { "scale" : true, "rotate" : true, "skew" : true, "translate" : true }, /** Map of cross browser CSS keys. */ __cssAnimationKeys : qx.core.Environment.get("css.animation"), /** * This is the main function to start the animation in reverse mode. * For further details, take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animateReverse : function(el, desc, duration){ return this._animate(el, desc, duration, true); }, /** * This is the main function to start the animation. For further details, * take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animate : function(el, desc, duration){ return this._animate(el, desc, duration, false); }, /** * Internal method to start an animation either reverse or not. * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @param reverse {Boolean} <code>true</code>, if the animation should be * reversed. * @return {qx.bom.element.AnimationHandle} The handle. */ _animate : function(el, desc, duration, reverse){ this.__normalizeDesc(desc); { }; // reverse the keep property if the animation is reverse as well var keep = desc.keep; if(keep != null && (reverse || (desc.alternate && desc.repeat % 2 == 0))){ keep = 100 - keep; }; if(!this.__sheet){ this.__sheet = qx.bom.Stylesheet.createElement(); }; var keyFrames = desc.keyFrames; if(duration == undefined){ duration = desc.duration; }; // if animations are supported if(this.__cssAnimationKeys != null){ var name = this.__addKeyFrames(keyFrames, reverse); var style = name + " " + duration + "ms " + desc.repeat + " " + desc.timing + " " + (desc.delay ? desc.delay + "ms " : "") + (desc.alternate ? "alternate" : ""); qx.bom.Event.addNativeListener(el, this.__cssAnimationKeys["start-event"], this.__onAnimationStart); qx.bom.Event.addNativeListener(el, this.__cssAnimationKeys["iteration-event"], this.__onAnimationIteration); qx.bom.Event.addNativeListener(el, this.__cssAnimationKeys["end-event"], this.__onAnimationEnd); el.style[qx.lang.String.camelCase(this.__cssAnimationKeys["name"])] = style; // use the fill mode property if available and suitable if(keep && keep == 100 && this.__cssAnimationKeys["fill-mode"]){ el.style[this.__cssAnimationKeys["fill-mode"]] = "forwards"; }; }; var animation = new qx.bom.element.AnimationHandle(); animation.desc = desc; animation.el = el; animation.keep = keep; el.$$animation = animation; // additional transform keys if(desc.origin != null){ qx.bom.element.Transform.setOrigin(el, desc.origin); }; // fallback for browsers not supporting animations if(this.__cssAnimationKeys == null){ window.setTimeout(function(){ qx.bom.element.AnimationCss.__onAnimationEnd({ target : el }); }, 0); }; return animation; }, /** * Handler for the animation start. * @param e {Event} The native event from the browser. */ __onAnimationStart : function(e){ e.target.$$animation.emit("start", e.target); }, /** * Handler for the animation iteration. * @param e {Event} The native event from the browser. */ __onAnimationIteration : function(e){ // It could happen that an animation end event is fired before an // animation iteration appears [BUG #6928] if(e.target != null && e.target.$$animation != null){ e.target.$$animation.emit("iteration", e.target); }; }, /** * Handler for the animation end. * @param e {Event} The native event from the browser. */ __onAnimationEnd : function(e){ var el = e.target; var animation = el.$$animation; // ignore events when already cleaned up if(!animation){ return; }; var desc = animation.desc; if(qx.bom.element.AnimationCss.__cssAnimationKeys != null){ // reset the styling var key = qx.lang.String.camelCase(qx.bom.element.AnimationCss.__cssAnimationKeys["name"]); el.style[key] = ""; qx.bom.Event.removeNativeListener(el, qx.bom.element.AnimationCss.__cssAnimationKeys["name"], qx.bom.element.AnimationCss.__onAnimationEnd); }; if(desc.origin != null){ qx.bom.element.Transform.setOrigin(el, ""); }; qx.bom.element.AnimationCss.__keepFrame(el, desc.keyFrames[animation.keep]); el.$$animation = null; animation.el = null; animation.ended = true; animation.emit("end", el); }, /** * Helper method which takes an element and a key frame description and * applies the properties defined in the given frame to the element. This * method is used to keep the state of the animation. * @param el {Element} The element to apply the frame to. * @param endFrame {Map} The description of the end frame, which is basically * a map containing CSS properties and values including transforms. */ __keepFrame : function(el, endFrame){ // keep the element at this animation step var transforms; for(var style in endFrame){ if(style in qx.bom.element.AnimationCss.__transitionKeys){ if(!transforms){ transforms = { }; }; transforms[style] = endFrame[style]; } else { el.style[qx.lang.String.camelCase(style)] = endFrame[style]; }; }; // transform keeping if(transforms){ qx.bom.element.Transform.transform(el, transforms); }; }, /** * Preprocessing of the description to make sure every necessary key is * set to its default. * @param desc {Map} The description of the animation. */ __normalizeDesc : function(desc){ if(!desc.hasOwnProperty("alternate")){ desc.alternate = false; }; if(!desc.hasOwnProperty("keep")){ desc.keep = null; }; if(!desc.hasOwnProperty("repeat")){ desc.repeat = 1; }; if(!desc.hasOwnProperty("timing")){ desc.timing = "linear"; }; if(!desc.hasOwnProperty("origin")){ desc.origin = null; }; }, /** * Debugging helper to validate the description. * @signature function(desc) * @param desc {Map} The description of the animation. */ __validateDesc : null, /** * Helper to add the given frames to an internal CSS stylesheet. It parses * the description and adds the key frames to the sheet. * @param frames {Map} A map of key frames that describe the animation. * @param reverse {Boolean} <code>true</code>, if the key frames should * be added in reverse order. * @return {String} The generated name of the keyframes rule. */ __addKeyFrames : function(frames, reverse){ var rule = ""; // for each key frame for(var position in frames){ rule += (reverse ? -(position - 100) : position) + "% {"; var frame = frames[position]; var transforms; // each style for(var style in frame){ if(style in this.__transitionKeys){ if(!transforms){ transforms = { }; }; transforms[style] = frame[style]; } else { rule += style + ":" + frame[style] + ";"; }; }; // transform handling if(transforms){ rule += qx.bom.element.Transform.getCss(transforms); }; rule += "} "; }; // cached shorthand if(this.__rules[rule]){ return this.__rules[rule]; }; var name = this.__rulePrefix + this.__id++; var selector = this.__cssAnimationKeys["keyframes"] + " " + name; qx.bom.Stylesheet.addRule(this.__sheet, selector, rule); this.__rules[rule] = name; return name; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #ignore(qx.bom.element.AnimationJs) ************************************************************************ */ /** * This is a simple handle, which will be returned when an animation is * started using the {@link qx.bom.element.Animation#animate} method. It * basically controls the animation. */ qx.Bootstrap.define("qx.bom.element.AnimationHandle", { extend : qx.event.Emitter, construct : function(){ var css = qx.core.Environment.get("css.animation"); this.__playState = css && css["play-state"]; this.__playing = true; }, events : { /** Fired when the animation started via {@link qx.bom.element.Animation}. */ "start" : "Element", /** * Fired when the animation started via {@link qx.bom.element.Animation} has * ended. */ "end" : "Element", /** Fired on every iteration of the animation. */ "iteration" : "Element" }, members : { __playState : null, __playing : false, __ended : false, /** * Accessor of the playing state. * @return {Boolean} <code>true</code>, if the animations is playing. */ isPlaying : function(){ return this.__playing; }, /** * Accessor of the ended state. * @return {Boolean} <code>true</code>, if the animations has ended. */ isEnded : function(){ return this.__ended; }, /** * Accessor of the paused state. * @return {Boolean} <code>true</code>, if the animations is paused. */ isPaused : function(){ return this.el.style[this.__playState] == "paused"; }, /** * Pauses the animation, if running. If not running, it will be ignored. */ pause : function(){ if(this.el){ this.el.style[this.__playState] = "paused"; this.el.$$animation.__playing = false; // in case the animation is based on JS if(this.animationId && qx.bom.element.AnimationJs){ qx.bom.element.AnimationJs.pause(this); }; }; }, /** * Resumes an animation. This does not start the animation once it has ended. * You need to create start a new Animation if you want to restart the animation. */ play : function(){ if(this.el){ this.el.style[this.__playState] = "running"; this.el.$$animation.__playing = true; // in case the animation is based on JS if(this.i != undefined && qx.bom.element.AnimationJs){ qx.bom.element.AnimationJs.play(this); }; }; }, /** * Stops the animation if running. */ stop : function(){ if(this.el && qx.core.Environment.get("css.animation") && !this.jsAnimation){ this.el.style[this.__playState] = ""; this.el.style[qx.core.Environment.get("css.animation").name] = ""; this.el.$$animation.__playing = false; this.el.$$animation.__ended = true; } else if(this.jsAnimation){ this.stopped = true; qx.bom.element.AnimationJs.stop(this); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #ignore(qx.bom.element.Style) #use(qx.bom.element.AnimationJs#play) ************************************************************************ */ /** * This class offers the same API as the CSS3 animation layer in * {@link qx.bom.element.AnimationCss} but uses JavaScript to fake the behavior. * * {@link qx.bom.element.Animation} is the class, which takes care of the * feature detection for CSS animations and decides which implementation * (CSS or JavaScript) should be used. Most likely, this implementation should * be the one to use. */ qx.Bootstrap.define("qx.bom.element.AnimationJs", { statics : { /** * The maximal time a frame should take. */ __maxStepTime : 30, /** * The supported CSS units. */ __units : ["%", "in", "cm", "mm", "em", "ex", "pt", "pc", "px"], /** * This is the main function to start the animation. For further details, * take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animate : function(el, desc, duration){ return this._animate(el, desc, duration, false); }, /** * This is the main function to start the animation in reversed mode. * For further details, take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animateReverse : function(el, desc, duration){ return this._animate(el, desc, duration, true); }, /** * Helper to start the animation, either in reversed order or not. * * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @param reverse {Boolean} <code>true</code>, if the animation should be * reversed. * @return {qx.bom.element.AnimationHandle} The handle. */ _animate : function(el, desc, duration, reverse){ // stop if an animation is already running if(el.$$animation){ return el.$$animation; }; desc = qx.lang.Object.clone(desc, true); if(duration == undefined){ duration = desc.duration; }; var keyFrames = desc.keyFrames; var keys = this.__getOrderedKeys(keyFrames); var stepTime = this.__getStepTime(duration, keys); var steps = parseInt(duration / stepTime, 10); this.__normalizeKeyFrames(keyFrames, el); var delta = this.__calculateDelta(steps, stepTime, keys, keyFrames, duration, desc.timing); var handle = new qx.bom.element.AnimationHandle(); handle.jsAnimation = true; if(reverse){ delta.reverse(); handle.reverse = true; }; handle.desc = desc; handle.el = el; handle.delta = delta; handle.stepTime = stepTime; handle.steps = steps; el.$$animation = handle; handle.i = 0; handle.initValues = { }; handle.repeatSteps = this.__applyRepeat(steps, desc.repeat); var delay = desc.delay || 0; var self = this; handle.delayId = window.setTimeout(function(){ handle.delayId = null; self.play(handle); }, delay); return handle; }, /** * Try to normalize the keyFrames by adding the default / set values of the * element. * @param keyFrames {Map} The map of key frames. * @param el {Element} The element to animate. */ __normalizeKeyFrames : function(keyFrames, el){ // collect all possible keys and its units var units = { }; for(var percent in keyFrames){ for(var name in keyFrames[percent]){ if(units[name] == undefined){ var item = keyFrames[percent][name]; if(typeof item == "string"){ units[name] = item.substring((parseInt(item, 10) + "").length, item.length); } else { units[name] = ""; }; }; }; }; // add all missing keys for(var percent in keyFrames){ var frame = keyFrames[percent]; for(var name in units){ if(frame[name] == undefined){ if(name in el.style){ // get the computed style if possible if(window.getComputedStyle){ frame[name] = getComputedStyle(el, null)[name]; } else { frame[name] = el.style[name]; }; } else { frame[name] = el[name]; }; // if its a unit we know, set 0 as fallback if(frame[name] === "" && this.__units.indexOf(units[name]) != -1){ frame[name] = "0" + units[name]; }; }; }; }; }, /** * Precalculation of the delta which will be applied during the animation. * The whole deltas will be calculated prior to the animation and stored * in a single array. This method takes care of that calculation. * * @param steps {Integer} The amount of steps to take to the end of the * animation. * @param stepTime {Integer} The amount of milliseconds each step takes. * @param keys {Array} Ordered list of keys in the key frames map. * @param keyFrames {Map} The map of key frames. * @param duration {Integer} Time in milliseconds the animation should take. * @param timing {String} The given timing function. * @return {Array} An array containing the animation deltas. */ __calculateDelta : function(steps, stepTime, keys, keyFrames, duration, timing){ var delta = new Array(steps); var keyIndex = 1; delta[0] = keyFrames[0]; var last = keyFrames[0]; var next = keyFrames[keys[keyIndex]]; // for every step for(var i = 1;i < delta.length;i++){ // switch key frames if we crossed a percent border if(i * stepTime / duration * 100 > keys[keyIndex]){ last = next; keyIndex++; next = keyFrames[keys[keyIndex]]; }; delta[i] = { }; // for every property for(var name in next){ var nItem = next[name] + ""; // color values if(nItem.charAt(0) == "#"){ // get the two values from the frames as RGB arrays var value0 = qx.util.ColorUtil.cssStringToRgb(last[name]); var value1 = qx.util.ColorUtil.cssStringToRgb(nItem); var stepValue = []; // calculate every color chanel for(var j = 0;j < value0.length;j++){ var range = value0[j] - value1[j]; stepValue[j] = parseInt(value0[j] - range * qx.bom.AnimationFrame.calculateTiming(timing, i / steps), 10); }; delta[i][name] = qx.util.ColorUtil.rgbToHexString(stepValue); } else if(!isNaN(parseInt(nItem, 10))){ var unit = nItem.substring((parseInt(nItem, 10) + "").length, nItem.length); var range = parseFloat(nItem) - parseFloat(last[name]); delta[i][name] = (parseFloat(last[name]) + range * qx.bom.AnimationFrame.calculateTiming(timing, i / steps)) + unit; } else { delta[i][name] = last[name] + ""; }; }; }; // make sure the last key frame is right delta[delta.length - 1] = keyFrames[100]; return delta; }, /** * Internal helper for the {@link qx.bom.element.AnimationHandle} to play * the animation. * @internal * @param handle {qx.bom.element.AnimationHandle} The hand which * represents the animation. * @return {qx.bom.element.AnimationHandle} The handle for chaining. */ play : function(handle){ handle.emit("start", handle.el); var id = window.setInterval(function(){ handle.repeatSteps--; var values = handle.delta[handle.i % handle.steps]; // save the init values if(handle.i === 0){ for(var name in values){ if(handle.initValues[name] === undefined){ // animate element property if(handle.el[name] !== undefined){ handle.initValues[name] = handle.el[name]; } else if(qx.bom.element.Style){ handle.initValues[name] = qx.bom.element.Style.get(handle.el, qx.lang.String.camelCase(name)); } else { handle.initValues[name] = handle.el.style[qx.lang.String.camelCase(name)]; }; }; }; }; qx.bom.element.AnimationJs.__applyStyles(handle.el, values); handle.i++; // iteration condition if(handle.i % handle.steps == 0){ handle.emit("iteration", handle.el); if(handle.desc.alternate){ handle.delta.reverse(); }; }; // end condition if(handle.repeatSteps < 0){ qx.bom.element.AnimationJs.stop(handle); }; }, handle.stepTime); handle.animationId = id; return handle; }, /** * Internal helper for the {@link qx.bom.element.AnimationHandle} to pause * the animation. * @internal * @param handle {qx.bom.element.AnimationHandle} The hand which * represents the animation. * @return {qx.bom.element.AnimationHandle} The handle for chaining. */ pause : function(handle){ // stop the interval window.clearInterval(handle.animationId); handle.animationId = null; return handle; }, /** * Internal helper for the {@link qx.bom.element.AnimationHandle} to stop * the animation. * @internal * @param handle {qx.bom.element.AnimationHandle} The hand which * represents the animation. * @return {qx.bom.element.AnimationHandle} The handle for chaining. */ stop : function(handle){ var desc = handle.desc; var el = handle.el; var initValues = handle.initValues; if(handle.animationId){ window.clearInterval(handle.animationId); }; // clear the delay if the animation has not been started if(handle.delayId){ window.clearTimeout(handle.delayId); }; // check if animation is already stopped if(el == undefined){ return handle; }; // if we should keep a frame var keep = desc.keep; if(keep != undefined && !handle.stopped){ if(handle.reverse || (desc.alternate && desc.repeat && desc.repeat % 2 == 0)){ keep = 100 - keep; }; this.__applyStyles(el, desc.keyFrames[keep]); } else { this.__applyStyles(el, initValues); }; el.$$animation = null; handle.el = null; handle.ended = true; handle.animationId = null; handle.emit("end", el); return handle; }, /** * Takes care of the repeat key of the description. * @param steps {Integer} The number of steps one iteration would take. * @param repeat {Integer|String} It can be either a number how often the * animation should be repeated or the string 'infinite'. * @return {Integer} The number of steps to animate. */ __applyRepeat : function(steps, repeat){ if(repeat == undefined){ return steps; }; if(repeat == "infinite"){ return Number.MAX_VALUE; }; return steps * repeat; }, /** * Central method to apply css styles and element properties. * @param el {Element} The DOM element to apply the styles. * @param styles {Map} A map containing styles and values. */ __applyStyles : function(el, styles){ for(var key in styles){ // ignore undefined values (might be a bad detection) if(styles[key] === undefined){ continue; }; // apply element property value - only if a CSS property // is *not* available if(typeof el.style[key] === "undefined" && key in el){ el[key] = styles[key]; continue; }; var name = qx.lang.String.camelCase(key); if(qx.bom.element.Style){ qx.bom.element.Style.set(el, name, styles[key]); } else { el.style[name] = styles[key]; }; }; }, /** * Dynamic calculation of the steps time considering a max step time. * @param duration {Number} The duration of the animation. * @param keys {Array} An array containing the orderd set of key frame keys. * @return {Integer} The best suited step time. */ __getStepTime : function(duration, keys){ // get min difference var minDiff = 100; for(var i = 0;i < keys.length - 1;i++){ minDiff = Math.min(minDiff, keys[i + 1] - keys[i]); }; var stepTime = duration * minDiff / 100; while(stepTime > this.__maxStepTime){ stepTime = stepTime / 2; }; return Math.round(stepTime); }, /** * Helper which returns the orderd keys of the key frame map. * @param keyFrames {Map} The map of key frames. * @return {Array} An orderd list of kyes. */ __getOrderedKeys : function(keyFrames){ var keys = Object.keys(keyFrames); for(var i = 0;i < keys.length;i++){ keys[i] = parseInt(keys[i], 10); }; keys.sort(function(a, b){ return a - b; }); return keys; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Christian Hagendorn (cs) ************************************************************************ */ /* ************************************************************************ #ignore(qx.theme.*) #ignore(qx.theme) #ignore(qx.Class) ************************************************************************ */ /** * Methods to convert colors between different color spaces. */ qx.Bootstrap.define("qx.util.ColorUtil", { statics : { /** * Regular expressions for color strings */ REGEXP : { hex3 : /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6 : /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, rgb : /^rgb\(\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*\)$/, rgba : /^rgba\(\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*\)$/ }, /** * CSS3 system color names. */ SYSTEM : { activeborder : true, activecaption : true, appworkspace : true, background : true, buttonface : true, buttonhighlight : true, buttonshadow : true, buttontext : true, captiontext : true, graytext : true, highlight : true, highlighttext : true, inactiveborder : true, inactivecaption : true, inactivecaptiontext : true, infobackground : true, infotext : true, menu : true, menutext : true, scrollbar : true, threeddarkshadow : true, threedface : true, threedhighlight : true, threedlightshadow : true, threedshadow : true, window : true, windowframe : true, windowtext : true }, /** * Named colors, only the 16 basic colors plus the following ones: * transparent, grey, magenta, orange and brown */ NAMED : { black : [0, 0, 0], silver : [192, 192, 192], gray : [128, 128, 128], white : [255, 255, 255], maroon : [128, 0, 0], red : [255, 0, 0], purple : [128, 0, 128], fuchsia : [255, 0, 255], green : [0, 128, 0], lime : [0, 255, 0], olive : [128, 128, 0], yellow : [255, 255, 0], navy : [0, 0, 128], blue : [0, 0, 255], teal : [0, 128, 128], aqua : [0, 255, 255], // Additional values transparent : [-1, -1, -1], magenta : [255, 0, 255], // alias for fuchsia orange : [255, 165, 0], brown : [165, 42, 42] }, /** * Whether the incoming value is a named color. * * @param value {String} the color value to test * @return {Boolean} true if the color is a named color */ isNamedColor : function(value){ return this.NAMED[value] !== undefined; }, /** * Whether the incoming value is a system color. * * @param value {String} the color value to test * @return {Boolean} true if the color is a system color */ isSystemColor : function(value){ return this.SYSTEM[value] !== undefined; }, /** * Whether the color theme manager is loaded. Generally * part of the GUI of qooxdoo. * * @return {Boolean} <code>true</code> when color theme support is ready. **/ supportsThemes : function(){ if(qx.Class){ return qx.Class.isDefined("qx.theme.manager.Color"); }; return false; }, /** * Whether the incoming value is a themed color. * * @param value {String} the color value to test * @return {Boolean} true if the color is a themed color */ isThemedColor : function(value){ if(!this.supportsThemes()){ return false; }; if(qx.theme && qx.theme.manager && qx.theme.manager.Color){ return qx.theme.manager.Color.getInstance().isDynamic(value); }; return false; }, /** * Try to convert an incoming string to an RGB array. * Supports themed, named and system colors, but also RGB strings, * hex3 and hex6 values. * * @param str {String} any string * @return {Array} returns an array of red, green, blue on a successful transformation * @throws {Error} if the string could not be parsed */ stringToRgb : function(str){ if(this.supportsThemes() && this.isThemedColor(str)){ var str = qx.theme.manager.Color.getInstance().resolveDynamic(str); }; if(this.isNamedColor(str)){ return this.NAMED[str]; } else if(this.isSystemColor(str)){ throw new Error("Could not convert system colors to RGB: " + str); } else if(this.isRgbString(str)){ return this.__rgbStringToRgb(); } else if(this.isHex3String(str)){ return this.__hex3StringToRgb(); } else if(this.isHex6String(str)){ return this.__hex6StringToRgb(); };;;; throw new Error("Could not parse color: " + str); }, /** * Try to convert an incoming string to an RGB array. * Support named colors, RGB strings, hex3 and hex6 values. * * @param str {String} any string * @return {Array} returns an array of red, green, blue on a successful transformation * @throws {Error} if the string could not be parsed */ cssStringToRgb : function(str){ if(this.isNamedColor(str)){ return this.NAMED[str]; } else if(this.isSystemColor(str)){ throw new Error("Could not convert system colors to RGB: " + str); } else if(this.isRgbString(str)){ return this.__rgbStringToRgb(); } else if(this.isRgbaString(str)){ return this.__rgbaStringToRgb(); } else if(this.isHex3String(str)){ return this.__hex3StringToRgb(); } else if(this.isHex6String(str)){ return this.__hex6StringToRgb(); };;;;; throw new Error("Could not parse color: " + str); }, /** * Try to convert an incoming string to an RGB string, which can be used * for all color properties. * Supports themed, named and system colors, but also RGB strings, * hex3 and hex6 values. * * @param str {String} any string * @return {String} a RGB string * @throws {Error} if the string could not be parsed */ stringToRgbString : function(str){ return this.rgbToRgbString(this.stringToRgb(str)); }, /** * Converts a RGB array to an RGB string * * @param rgb {Array} an array with red, green and blue * @return {String} a RGB string */ rgbToRgbString : function(rgb){ return "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")"; }, /** * Converts a RGB array to an hex6 string * * @param rgb {Array} an array with red, green and blue * @return {String} a hex6 string (#xxxxxx) */ rgbToHexString : function(rgb){ return ("#" + qx.lang.String.pad(rgb[0].toString(16).toUpperCase(), 2) + qx.lang.String.pad(rgb[1].toString(16).toUpperCase(), 2) + qx.lang.String.pad(rgb[2].toString(16).toUpperCase(), 2)); }, /** * Detects if a string is a valid qooxdoo color * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid qooxdoo color */ isValidPropertyValue : function(str){ return (this.isThemedColor(str) || this.isNamedColor(str) || this.isHex3String(str) || this.isHex6String(str) || this.isRgbString(str) || this.isRgbaString(str)); }, /** * Detects if a string is a valid CSS color string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid CSS color string */ isCssString : function(str){ return (this.isSystemColor(str) || this.isNamedColor(str) || this.isHex3String(str) || this.isHex6String(str) || this.isRgbString(str) || this.isRgbaString(str)); }, /** * Detects if a string is a valid hex3 string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid hex3 string */ isHex3String : function(str){ return this.REGEXP.hex3.test(str); }, /** * Detects if a string is a valid hex6 string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid hex6 string */ isHex6String : function(str){ return this.REGEXP.hex6.test(str); }, /** * Detects if a string is a valid RGB string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid RGB string */ isRgbString : function(str){ return this.REGEXP.rgb.test(str); }, /** * Detects if a string is a valid RGBA string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid RGBA string */ isRgbaString : function(str){ return this.REGEXP.rgba.test(str); }, /** * Converts a regexp object match of a rgb string to an RGB array. * * @return {Array} an array with red, green, blue */ __rgbStringToRgb : function(){ var red = parseInt(RegExp.$1, 10); var green = parseInt(RegExp.$2, 10); var blue = parseInt(RegExp.$3, 10); return [red, green, blue]; }, /** * Converts a regexp object match of a rgba string to an RGB array. * * @return {Array} an array with red, green, blue */ __rgbaStringToRgb : function(){ var red = parseInt(RegExp.$1, 10); var green = parseInt(RegExp.$2, 10); var blue = parseInt(RegExp.$3, 10); return [red, green, blue]; }, /** * Converts a regexp object match of a hex3 string to an RGB array. * * @return {Array} an array with red, green, blue */ __hex3StringToRgb : function(){ var red = parseInt(RegExp.$1, 16) * 17; var green = parseInt(RegExp.$2, 16) * 17; var blue = parseInt(RegExp.$3, 16) * 17; return [red, green, blue]; }, /** * Converts a regexp object match of a hex6 string to an RGB array. * * @return {Array} an array with red, green, blue */ __hex6StringToRgb : function(){ var red = (parseInt(RegExp.$1, 16) * 16) + parseInt(RegExp.$2, 16); var green = (parseInt(RegExp.$3, 16) * 16) + parseInt(RegExp.$4, 16); var blue = (parseInt(RegExp.$5, 16) * 16) + parseInt(RegExp.$6, 16); return [red, green, blue]; }, /** * Converts a hex3 string to an RGB array * * @param value {String} a hex3 (#xxx) string * @return {Array} an array with red, green, blue */ hex3StringToRgb : function(value){ if(this.isHex3String(value)){ return this.__hex3StringToRgb(value); }; throw new Error("Invalid hex3 value: " + value); }, /** * Converts a hex3 (#xxx) string to a hex6 (#xxxxxx) string. * * @param value {String} a hex3 (#xxx) string * @return {String} The hex6 (#xxxxxx) string or the passed value when the * passed value is not an hex3 (#xxx) value. */ hex3StringToHex6String : function(value){ if(this.isHex3String(value)){ return this.rgbToHexString(this.hex3StringToRgb(value)); }; return value; }, /** * Converts a hex6 string to an RGB array * * @param value {String} a hex6 (#xxxxxx) string * @return {Array} an array with red, green, blue */ hex6StringToRgb : function(value){ if(this.isHex6String(value)){ return this.__hex6StringToRgb(value); }; throw new Error("Invalid hex6 value: " + value); }, /** * Converts a hex string to an RGB array * * @param value {String} a hex3 (#xxx) or hex6 (#xxxxxx) string * @return {Array} an array with red, green, blue */ hexStringToRgb : function(value){ if(this.isHex3String(value)){ return this.__hex3StringToRgb(value); }; if(this.isHex6String(value)){ return this.__hex6StringToRgb(value); }; throw new Error("Invalid hex value: " + value); }, /** * Convert RGB colors to HSB * * @param rgb {Number[]} red, blue and green as array * @return {Array} an array with hue, saturation and brightness */ rgbToHsb : function(rgb){ var hue,saturation,brightness; var red = rgb[0]; var green = rgb[1]; var blue = rgb[2]; var cmax = (red > green) ? red : green; if(blue > cmax){ cmax = blue; }; var cmin = (red < green) ? red : green; if(blue < cmin){ cmin = blue; }; brightness = cmax / 255.0; if(cmax != 0){ saturation = (cmax - cmin) / cmax; } else { saturation = 0; }; if(saturation == 0){ hue = 0; } else { var redc = (cmax - red) / (cmax - cmin); var greenc = (cmax - green) / (cmax - cmin); var bluec = (cmax - blue) / (cmax - cmin); if(red == cmax){ hue = bluec - greenc; } else if(green == cmax){ hue = 2.0 + redc - bluec; } else { hue = 4.0 + greenc - redc; }; hue = hue / 6.0; if(hue < 0){ hue = hue + 1.0; }; }; return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)]; }, /** * Convert HSB colors to RGB * * @param hsb {Number[]} an array with hue, saturation and brightness * @return {Integer[]} an array with red, green, blue */ hsbToRgb : function(hsb){ var i,f,p,q,t; var hue = hsb[0] / 360; var saturation = hsb[1] / 100; var brightness = hsb[2] / 100; if(hue >= 1.0){ hue %= 1.0; }; if(saturation > 1.0){ saturation = 1.0; }; if(brightness > 1.0){ brightness = 1.0; }; var tov = Math.floor(255 * brightness); var rgb = { }; if(saturation == 0.0){ rgb.red = rgb.green = rgb.blue = tov; } else { hue *= 6.0; i = Math.floor(hue); f = hue - i; p = Math.floor(tov * (1.0 - saturation)); q = Math.floor(tov * (1.0 - (saturation * f))); t = Math.floor(tov * (1.0 - (saturation * (1.0 - f)))); switch(i){case 0: rgb.red = tov; rgb.green = t; rgb.blue = p; break;case 1: rgb.red = q; rgb.green = tov; rgb.blue = p; break;case 2: rgb.red = p; rgb.green = tov; rgb.blue = t; break;case 3: rgb.red = p; rgb.green = q; rgb.blue = tov; break;case 4: rgb.red = t; rgb.green = p; rgb.blue = tov; break;case 5: rgb.red = tov; rgb.green = p; rgb.blue = q; break;}; }; return [rgb.red, rgb.green, rgb.blue]; }, /** * Creates a random color. * * @return {String} a valid qooxdoo/CSS rgb color string. */ randomColor : function(){ var r = Math.round(Math.random() * 255); var g = Math.round(Math.random() * 255); var b = Math.round(Math.random() * 255); return this.rgbToRgbString([r, g, b]); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #ignore(performance) #ignore(performance.timing) ************************************************************************* */ /** * This is a cross browser wrapper for requestAnimationFrame. For further * information about the feature, take a look at spec: * http://www.w3.org/TR/animation-timing/ * * This class offers two ways of using this feature. First, the plain * API the spec describes. * * Here is a sample usage: * <pre class='javascript'>var start = +(new Date()); * var clb = function(time) { * if (time >= start + duration) { * // ... do some last tasks * } else { * var timePassed = time - start; * // ... calculate the current step and apply it * qx.bom.AnimationFrame.request(clb, this); * } * }; * qx.bom.AnimationFrame.request(clb, this); * </pre> * * Another way of using it is to use it as an instance emitting events. * * Here is a sample usage of that API: * <pre class='javascript'>var frame = new qx.bom.AnimationFrame(); * frame.on("end", function() { * // ... do some last tasks * }, this); * frame.on("frame", function(timePassed) { * // ... calculate the current step and apply it * }, this); * frame.startSequence(duration); * </pre> */ qx.Bootstrap.define("qx.bom.AnimationFrame", { extend : qx.event.Emitter, events : { /** Fired as soon as the animation has ended. */ "end" : undefined, /** Fired on every frame having the passed time as value. */ "frame" : "Number" }, members : { /** * Method used to start a series of animation frames. The series will end as * soon as the given duration is over. * * @param duration {Number} The duration the sequence should take. */ startSequence : function(duration){ var start = +(new Date()); var clb = function(){ var time = +(new Date()); // final call if(time >= start + duration){ this.emit("end"); this.id = null; } else { var timePassed = time - start; this.emit("frame", timePassed); this.id = qx.bom.AnimationFrame.request(clb, this); }; }; this.id = qx.bom.AnimationFrame.request(clb, this); } }, statics : { /** * The default time in ms the timeout fallback implementation uses. */ TIMEOUT : 30, /** * Calculation of the predefined timing functions. Approximation of the real * bezier curves has ben used for easier calculation. This is good and close * enough for the predefined functions like <code>ease</code> or * <code>linear</code>. * * @param func {String} The defined timing function. One of the following values: * <code>"ease-in"</code>, <code>"ease-out"</code>, <code>"linear"</code>, * <code>"ease-in-out"</code>, <code>"ease"</code>. * @param x {Integer} The percent value of the function. * @return {Integer} The calculated value */ calculateTiming : function(func, x){ if(func == "ease-in"){ var a = [3.1223e-7, 0.0757, 1.2646, -0.167, -0.4387, 0.2654]; } else if(func == "ease-out"){ var a = [-7.0198e-8, 1.652, -0.551, -0.0458, 0.1255, -0.1807]; } else if(func == "linear"){ return x; } else if(func == "ease-in-out"){ var a = [2.482e-7, -0.2289, 3.3466, -1.0857, -1.7354, 0.7034]; } else { // default is 'ease' var a = [-0.0021, 0.2472, 9.8054, -21.6869, 17.7611, -5.1226]; };;; // A 6th grade polynomial has been used as approximation of the original // bezier curves described in the transition spec // http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag // (the same is used for animations as well) var y = 0; for(var i = 0;i < a.length;i++){ y += a[i] * Math.pow(x, i); }; return y; }, /** * Request for an animation frame. If the native <code>requestAnimationFrame</code> * method is supported, it will be used. Otherwise, we use timeouts with a * 30ms delay. * @param callback {Function} The callback function which will get the current * time as argument. * @param context {var} The context of the callback. * @return {Number} The id of the request. */ request : function(callback, context){ var req = qx.core.Environment.get("css.animation.requestframe"); var clb = function(){ var time = +(new Date()); callback.call(context, time); }; if(req){ return window[req](clb); } else { // make sure to use an indirection because setTimeout passes a // number as first argument as well return window.setTimeout(function(){ clb(); }, qx.bom.AnimationFrame.TIMEOUT); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Abstract class to compute the position of an object on one axis. */ qx.Bootstrap.define("qx.util.placement.AbstractAxis", { extend : Object, statics : { /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. * @abstract */ computeStart : function(size, target, offsets, areaSize, position){ throw new Error("abstract method call!"); }, /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : function(size, target, offsets, position){ switch(position){case "edge-start": return target.start - offsets.end - size;case "edge-end": return target.end + offsets.start;case "align-start": return target.start + offsets.start;case "align-center": return target.start + parseInt((target.end - target.start - size) / 2, 10) + offsets.start;case "align-end": return target.end - offsets.end - size;}; }, /** * Whether the object specified by <code>start</code> and <code>size</code> * is completely inside of the axis' range.. * * @param start {Integer} Computed start position of the object * @param size {Integer} Size of the object * @param areaSize {Integer} The size of the axis * @return {Boolean} Whether the object is inside of the axis' range */ _isInRange : function(start, size, areaSize){ return start >= 0 && start + size <= areaSize; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Places the object directly at the specified position. It is not moved if * parts of the object are outside of the axis' range. */ qx.Bootstrap.define("qx.util.placement.DirectAxis", { statics : { /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : qx.util.placement.AbstractAxis._moveToEdgeAndAlign, /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. */ computeStart : function(size, target, offsets, areaSize, position){ return this._moveToEdgeAndAlign(size, target, offsets, position); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Places the object to the target. If parts of the object are outside of the * range this class places the object at the best "edge", "alignment" * combination so that the overlap between object and range is maximized. */ qx.Bootstrap.define("qx.util.placement.KeepAlignAxis", { statics : { /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : qx.util.placement.AbstractAxis._moveToEdgeAndAlign, /** * Whether the object specified by <code>start</code> and <code>size</code> * is completely inside of the axis' range.. * * @param start {Integer} Computed start position of the object * @param size {Integer} Size of the object * @param areaSize {Integer} The size of the axis * @return {Boolean} Whether the object is inside of the axis' range */ _isInRange : qx.util.placement.AbstractAxis._isInRange, /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. */ computeStart : function(size, target, offsets, areaSize, position){ var start = this._moveToEdgeAndAlign(size, target, offsets, position); var range1End,range2Start; if(this._isInRange(start, size, areaSize)){ return start; }; if(position == "edge-start" || position == "edge-end"){ range1End = target.start - offsets.end; range2Start = target.end + offsets.start; } else { range1End = target.end - offsets.end; range2Start = target.start + offsets.start; }; if(range1End > areaSize - range2Start){ start = range1End - size; } else { start = range2Start; }; return start; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Places the object according to the target. If parts of the object are outside * of the axis' range the object's start is adjusted so that the overlap between * the object and the axis is maximized. */ qx.Bootstrap.define("qx.util.placement.BestFitAxis", { statics : { /** * Whether the object specified by <code>start</code> and <code>size</code> * is completely inside of the axis' range.. * * @param start {Integer} Computed start position of the object * @param size {Integer} Size of the object * @param areaSize {Integer} The size of the axis * @return {Boolean} Whether the object is inside of the axis' range */ _isInRange : qx.util.placement.AbstractAxis._isInRange, /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : qx.util.placement.AbstractAxis._moveToEdgeAndAlign, /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. */ computeStart : function(size, target, offsets, areaSize, position){ var start = this._moveToEdgeAndAlign(size, target, offsets, position); if(this._isInRange(start, size, areaSize)){ return start; }; if(start < 0){ start = Math.min(0, areaSize - size); }; if(start + size > areaSize){ start = Math.max(0, areaSize - size); }; return start; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.util.placement.KeepAlignAxis#computeStart) #require(qx.util.placement.BestFitAxis#computeStart) #require(qx.util.placement.DirectAxis#computeStart) ************************************************************************ */ /** * The Placement module provides a convenient way to align two elements relative * to each other using various pre-defined algorithms. */ qxWeb.define("qx.module.Placement", { statics : { /** * Moves the first element in the collection, aligning it with the given * target. * * @attach{qxWeb} * @param target {Element} Placement target * @param position {String} Alignment of the object with the target, any of * <code>"top-left"</code>, <code>"top-center"</code>, <code>"top-right"</code>, * <code>"bottom-left"</code>, <code>"bottom-center"</code>, <code>"bottom-right"</code>, * <code>"left-top"</code>, <code>"left-middle"</code>, <code>"left-bottom"</code>, * <code>"right-top"</code>, <code>"right-middle"</code>, <code>"right-bottom"</code> * @param offsets {Map?null} Map with the desired offsets between the two elements. * Must contain the keys <code>left</code>, <code>top</code>, * <code>right</code> and <code>bottom</code> * @param modeX {String?"direct"} Horizontal placement mode. Valid values are: * <ul> * <li><code>direct</code>: place the element directly at the given * location.</li> * <li><code>keep-align</code>: if the element is partially outside of the * visible area, it is moved to the best fitting 'edge' and 'alignment' of * the target. * It is guaranteed the the new position attaches the object to one of the * target edges and that it is aligned with a target edge.</li> * <li><code>best-fit</code>: If the element is partially outside of the visible * area, it is moved into the view port, ignoring any offset and position * values.</li> * </ul> * @param modeY {String?"direct"} Vertical placement mode. Accepts the same values as * the 'modeX' argument. * @return {qxWeb} The collection for chaining */ placeTo : function(target, position, offsets, modeX, modeY){ if(!this[0]){ return null; }; var axes = { x : qx.module.Placement._getAxis(modeX), y : qx.module.Placement._getAxis(modeY) }; var size = { width : this.getWidth(), height : this.getHeight() }; var parent = this.getParents(); var area = { width : parent.getWidth(), height : parent.getHeight() }; var target = qxWeb(target).getOffset(); var offsets = offsets || { top : 0, right : 0, bottom : 0, left : 0 }; var splitted = position.split("-"); var edge = splitted[0]; var align = splitted[1]; var position = { x : qx.module.Placement._getPositionX(edge, align), y : qx.module.Placement._getPositionY(edge, align) }; var newLocation = qx.module.Placement._computePlacement(axes, size, area, target, offsets, position); this.setStyles({ position : "absolute", left : newLocation.left + "px", top : newLocation.top + "px" }); return this; }, /** * Returns the appropriate axis implementation for the given placement * mode * * @param mode {String} Placement mode * @return {Object} Placement axis class */ _getAxis : function(mode){ switch(mode){case "keep-align": return qx.util.placement.KeepAlignAxis;case "best-fit": return qx.util.placement.BestFitAxis;case "direct":default: return qx.util.placement.DirectAxis;}; }, /** * Returns the computed coordinates for the element to be placed * * @param axes {Map} Map with the keys <code>x</code> and <code>y</code>. Values * are the axis implementations * @param size {Map} Map with the keys <code>width</code> and <code>height</code> * containing the size of the placement target * @param area {Map} Map with the keys <code>width</code> and <code>height</code> * containing the size of the two elements' common parent (available space for * placement) * @param target {qxWeb} Collection containing the placement target * @param offsets {Map} Map of offsets (top, right, bottom, left) * @param position {Map} Map with the keys <code>x</code> and <code>y</code>, * containing the type of positioning for each axis * @return {Map} Map with the keys <code>left</code> and <code>top</code> * containing the computed coordinates to which the element should be moved */ _computePlacement : function(axes, size, area, target, offsets, position){ var left = axes.x.computeStart(size.width, { start : target.left, end : target.right }, { start : offsets.left, end : offsets.right }, area.width, position.x); var top = axes.y.computeStart(size.height, { start : target.top, end : target.bottom }, { start : offsets.top, end : offsets.bottom }, area.height, position.y); return { left : left, top : top }; }, /** * Returns the X axis positioning type for the given edge and alignment * values * * @param edge {String} edge value * @param align {String} align value * @return {String} X positioning type */ _getPositionX : function(edge, align){ if(edge == "left"){ return "edge-start"; } else if(edge == "right"){ return "edge-end"; } else if(align == "left"){ return "align-start"; } else if(align == "right"){ return "align-end"; };;; }, /** * Returns the Y axis positioning type for the given edge and alignment * values * * @param edge {String} edge value * @param align {String} align value * @return {String} Y positioning type */ _getPositionY : function(edge, align){ if(edge == "top"){ return "edge-start"; } else if(edge == "bottom"){ return "edge-end"; } else if(align == "top"){ return "align-start"; } else if(align == "bottom"){ return "align-end"; };;; } }, defer : function(statics){ qxWeb.$attach({ "placeTo" : statics.placeTo }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Creates a touch event handler that fires high-level events such as "swipe" * based on low-level event sequences on the given element */ qx.Bootstrap.define("qx.module.event.TouchHandler", { statics : { /** * List of events that require a touch handler * @type {Array} */ TYPES : ["tap", "swipe"], /** * Creates a touch handler for the given element when a touch event listener * is attached to it * * @param element {Element} DOM element */ register : function(element){ if(!element.__touchHandler){ if(!element.__emitter){ element.__emitter = new qx.event.Emitter(); }; element.__touchHandler = new qx.event.handler.TouchCore(element, element.__emitter); }; }, /** * Removes the touch event handler from the element if there are no more * touch event listeners attached to it * @param element {Element} DOM element */ unregister : function(element){ if(element.__touchHandler){ if(!element.__emitter){ element.__touchHandler = null; } else { var hasTouchListener = false; var listeners = element.__emitter.getListeners(); qx.module.event.TouchHandler.TYPES.forEach(function(type){ if(type in listeners && listeners[type].length > 0){ hasTouchListener = true; }; }); if(!hasTouchListener){ element.__touchHandler = null; }; }; }; } }, defer : function(statics){ qxWeb.$registerEventHook(statics.TYPES, statics.register, statics.unregister); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) * Tino Butz (tbtz) * Christian Hagendorn (chris_schmidt) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #ignore(qx.event.type.Tap) #ignore(qx.event.type.Swipe) #ignore(qx.event.type) #ignore(qx.event) ************************************************************************ */ /** * Listens for native touch events and fires composite events like "tap" and * "swipe" */ qx.Bootstrap.define("qx.event.handler.TouchCore", { extend : Object, statics : { /** {Integer} The maximum distance of a tap. Only if the x or y distance of * the performed tap is less or equal the value of this constant, a tap * event is fired. */ TAP_MAX_DISTANCE : qx.core.Environment.get("os.name") != "android" ? 10 : 40, /** {Map} The direction of a swipe relative to the axis */ SWIPE_DIRECTION : { x : ["left", "right"], y : ["up", "down"] }, /** {Integer} The minimum distance of a swipe. Only if the x or y distance * of the performed swipe is greater as or equal the value of this * constant, a swipe event is fired. */ SWIPE_MIN_DISTANCE : qx.core.Environment.get("os.name") != "android" ? 11 : 41, /** {Integer} The minimum velocity of a swipe. Only if the velocity of the * performed swipe is greater as or equal the value of this constant, a * swipe event is fired. */ SWIPE_MIN_VELOCITY : 0 }, /** * Create a new instance * * @param target {Element} element on which to listen for native touch events * @param emitter {qx.event.Emitter} Event emitter object */ construct : function(target, emitter){ this.__target = target; this.__emitter = emitter; this._initTouchObserver(); }, members : { __target : null, __emitter : null, __onTouchEventWrapper : null, __originalTarget : null, __startPageX : null, __startPageY : null, __startTime : null, __isSingleTouchGesture : null, __isTapGesture : null, __onMove : null, __beginScalingDistance : null, __beginRotation : null, /* --------------------------------------------------------------------------- OBSERVER INIT --------------------------------------------------------------------------- */ /** * Initializes the native touch event listeners. */ _initTouchObserver : function(){ this.__onTouchEventWrapper = qx.lang.Function.listener(this._onTouchEvent, this); var Event = qx.bom.Event; Event.addNativeListener(this.__target, "touchstart", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "touchmove", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "touchend", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "touchcancel", this.__onTouchEventWrapper); if(qx.core.Environment.get("event.mspointer")){ Event.addNativeListener(this.__target, "MSPointerDown", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "MSPointerMove", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "MSPointerUp", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "MSPointerCancel", this.__onTouchEventWrapper); }; }, /* --------------------------------------------------------------------------- OBSERVER STOP --------------------------------------------------------------------------- */ /** * Disconnects the native touch event listeners. */ _stopTouchObserver : function(){ var Event = qx.bom.Event; Event.removeNativeListener(this.__target, "touchstart", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "touchmove", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "touchend", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "touchcancel", this.__onTouchEventWrapper); if(qx.core.Environment.get("event.mspointer")){ Event.removeNativeListener(this.__target, "MSPointerDown", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "MSPointerMove", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "MSPointerUp", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "MSPointerCancel", this.__onTouchEventWrapper); }; }, /* --------------------------------------------------------------------------- NATIVE EVENT OBSERVERS --------------------------------------------------------------------------- */ /** * Handler for native touch events. * * @param domEvent {Event} The touch event from the browser. */ _onTouchEvent : function(domEvent){ this._commonTouchEventHandler(domEvent); }, /** * Calculates the scaling distance between two touches. * @param touch0 {Event} The touch event from the browser. * @param touch1 {Event} The touch event from the browser. * @return {Number} the calculated distance. */ _getScalingDistance : function(touch0, touch1){ return (Math.sqrt(Math.pow(touch0.pageX - touch1.pageX, 2) + Math.pow(touch0.pageY - touch1.pageY, 2))); }, /** * Calculates the rotation between two touches. * @param touch0 {Event} The touch event from the browser. * @param touch1 {Event} The touch event from the browser. * @return {Number} the calculated rotation. */ _getRotationAngle : function(touch0, touch1){ var x = touch0.pageX - touch1.pageX; var y = touch0.pageY - touch1.pageY; return (Math.atan2(y, x) * 180 / Math.PI); }, /** * Called by an event handler. * * @param domEvent {Event} DOM event * @param type {String ? null} type of the event */ _commonTouchEventHandler : function(domEvent, type){ var type = type || domEvent.type; if(qx.core.Environment.get("event.mspointer")){ domEvent.changedTouches = [domEvent]; domEvent.targetTouches = [domEvent]; domEvent.touches = [domEvent]; if(type == "MSPointerDown"){ type = "touchstart"; } else if(type == "MSPointerUp"){ type = "touchend"; } else if(type == "MSPointerMove"){ if(this.__onMove == true){ type = "touchmove"; }; } else if(type == "MSPointerCancel"){ type = "touchcancel"; };;; }; if(type == "touchstart"){ this.__originalTarget = this._getTarget(domEvent); this.__isTapGesture = true; if(domEvent.touches && domEvent.touches.length > 1){ this.__beginScalingDistance = this._getScalingDistance(domEvent.touches[0], domEvent.touches[1]); this.__beginRotation = this._getRotationAngle(domEvent.touches[0], domEvent.touches[1]); }; }; if(type == "touchmove"){ // Polyfill for scale if(typeof domEvent.scale == "undefined" && domEvent.changedTouches.length > 1){ var currentScalingDistance = this._getScalingDistance(domEvent.changedTouches[0], domEvent.changedTouches[1]); domEvent.scale = currentScalingDistance / this.__beginScalingDistance; }; // Polyfill for rotation if(typeof domEvent.rotation == "undefined" && domEvent.changedTouches.length > 1){ var currentRotation = this._getRotationAngle(domEvent.changedTouches[0], domEvent.changedTouches[1]); domEvent.rotation = currentRotation - this.__beginRotation; }; if(this.__isTapGesture){ this.__isTapGesture = this._isBelowTapMaxDistance(domEvent.changedTouches[0]); }; }; this._fireEvent(domEvent, type); this.__checkAndFireGesture(domEvent, type); }, /** * Checks if the distance between the x/y coordinates of "touchstart" and "touchmove" event * exceeds TAP_MAX_DISTANCE and returns the result. * * @param touch {Event} The "touchmove" event from the browser. * @return {Boolean} true if distance is below TAP_MAX_DISTANCE. */ _isBelowTapMaxDistance : function(touch){ var deltaCoordinates = { x : touch.screenX - this.__startPageX, y : touch.screenY - this.__startPageY }; var clazz = qx.event.handler.TouchCore; return (Math.abs(deltaCoordinates.x) <= clazz.TAP_MAX_DISTANCE && Math.abs(deltaCoordinates.y) <= clazz.TAP_MAX_DISTANCE); }, /* --------------------------------------------------------------------------- HELPERS --------------------------------------------------------------------------- */ /** * Return the target of the event. * * @param domEvent {Event} DOM event * @return {Element} Event target */ _getTarget : function(domEvent){ var target = qx.bom.Event.getTarget(domEvent); // Text node. Fix Safari Bug, see http://www.quirksmode.org/js/events_properties.html if(qx.core.Environment.get("engine.name") == "webkit"){ if(target && target.nodeType == 3){ target = target.parentNode; }; } else if(qx.core.Environment.get("event.mspointer")){ // Fix for IE10 and pointer-events:none var targetForIE = this.__evaluateTarget(domEvent); if(targetForIE){ target = targetForIE; }; }; return target; }, /** * This method fixes "pointer-events:none" for Internet Explorer 10. * Checks which elements are placed to position x/y and traverses the array * till one element has no "pointer-events:none" inside its style attribute. * @param domEvent {Event} DOM event * @return {Element | null} Event target */ __evaluateTarget : function(domEvent){ if(domEvent && domEvent.touches){ var clientX = domEvent.touches[0].clientX; var clientY = domEvent.touches[0].clientY; }; // Retrieve an array with elements on point X/Y. var hitTargets = document.msElementsFromPoint(clientX, clientY); if(hitTargets){ // Traverse this array for the elements which has no pointer-events:none inside. for(var i = 0;i < hitTargets.length;i++){ var currentTarget = hitTargets[i]; var pointerEvents = qx.bom.element.Style.get(currentTarget, "pointer-events", 3); if(pointerEvents != "none"){ return currentTarget; }; }; }; return null; }, /** * Fire a touch event with the given parameters * * @param domEvent {Event} DOM event * @param type {String ? null} type of the event * @param target {Element ? null} event target */ _fireEvent : function(domEvent, type, target){ if(!target){ target = this._getTarget(domEvent); }; var type = type || domEvent.type; if(target && target.nodeType && this.__emitter){ this.__emitter.emit(type, domEvent); }; }, /** * Checks if a gesture was made and fires the gesture event. * * @param domEvent {Event} DOM event * @param type {String ? null} type of the event * @param target {Element ? null} event target */ __checkAndFireGesture : function(domEvent, type, target){ if(!target){ target = this._getTarget(domEvent); }; var type = type || domEvent.type; if(type == "touchstart"){ this.__gestureStart(domEvent, target); } else if(type == "touchmove"){ this.__gestureChange(domEvent, target); } else if(type == "touchend"){ this.__gestureEnd(domEvent, target); };; }, /** * Helper method for gesture start. * * @param domEvent {Event} DOM event * @param target {Element} event target */ __gestureStart : function(domEvent, target){ var touch = domEvent.changedTouches[0]; this.__onMove = true; this.__startPageX = touch.screenX; this.__startPageY = touch.screenY; this.__startTime = new Date().getTime(); this.__isSingleTouchGesture = domEvent.changedTouches.length === 1; }, /** * Helper method for gesture change. * * @param domEvent {Event} DOM event * @param target {Element} event target */ __gestureChange : function(domEvent, target){ // Abort a single touch gesture when another touch occurs. if(this.__isSingleTouchGesture && domEvent.changedTouches.length > 1){ this.__isSingleTouchGesture = false; }; }, /** * Helper method for gesture end. * * @param domEvent {Event} DOM event * @param target {Element} event target */ __gestureEnd : function(domEvent, target){ this.__onMove = false; if(this.__isSingleTouchGesture){ var touch = domEvent.changedTouches[0]; var deltaCoordinates = { x : touch.screenX - this.__startPageX, y : touch.screenY - this.__startPageY }; var eventType; if(this.__originalTarget == target && this.__isTapGesture){ if(qx.event && qx.event.type && qx.event.type.Tap){ eventType = qx.event.type.Tap; }; this._fireEvent(domEvent, "tap", target, eventType); } else { var swipe = this.__getSwipeGesture(domEvent, target, deltaCoordinates); if(swipe){ if(qx.event && qx.event.type && qx.event.type.Swipe){ eventType = qx.event.type.Swipe; }; domEvent.swipe = swipe; this._fireEvent(domEvent, "swipe", target, eventType); }; }; }; }, /** * Returns the swipe gesture when the user performed a swipe. * * @param domEvent {Event} DOM event * @param target {Element} event target * @param deltaCoordinates {Map} delta x/y coordinates since the gesture started. * @return {Map} returns the swipe data when the user performed a swipe, null if the gesture was no swipe. */ __getSwipeGesture : function(domEvent, target, deltaCoordinates){ var clazz = qx.event.handler.TouchCore; var duration = new Date().getTime() - this.__startTime; var axis = (Math.abs(deltaCoordinates.x) >= Math.abs(deltaCoordinates.y)) ? "x" : "y"; var distance = deltaCoordinates[axis]; var direction = clazz.SWIPE_DIRECTION[axis][distance < 0 ? 0 : 1]; var velocity = (duration !== 0) ? distance / duration : 0; var swipe = null; if(Math.abs(velocity) >= clazz.SWIPE_MIN_VELOCITY && Math.abs(distance) >= clazz.SWIPE_MIN_DISTANCE){ swipe = { startTime : this.__startTime, duration : duration, axis : axis, direction : direction, distance : distance, velocity : velocity }; }; return swipe; }, /** * Dispose this object */ dispose : function(){ this._stopTouchObserver(); this.__originalTarget = this.__target = this.__emitter = this.__beginScalingDistance = this.__beginRotation = null; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Normalization for orientationchange events * Example: * <pre class="javascript"> * q(window).on("orientationchange", function(ev) { * ev.getOrientation(); * ev.isLandscape(); * }); * </pre> */ qx.Bootstrap.define("qx.module.event.Orientation", { statics : { /** * List of event types to be normalized */ TYPES : ["orientationchange"], /** * List of qx.module.event.Orientation methods to be attached to native * event objects * @internal */ BIND_METHODS : ["getOrientation", "isLandscape", "isPortrait"], /** * Returns the current orientation of the viewport in degrees. * * All possible values and their meaning: * * * <code>0</code>: "Portrait" * * <code>-90</code>: "Landscape (right, screen turned clockwise)" * * <code>90</code>: "Landscape (left, screen turned counterclockwise)" * * <code>180</code>: "Portrait (upside-down portrait)" * * @return {Number} The current orientation in degrees */ getOrientation : function(){ return this._orientation; }, /** * Whether the viewport orientation is currently in landscape mode. * * @return {Boolean} <code>true</code> when the viewport orientation * is currently in landscape mode. */ isLandscape : function(){ return this._mode == "landscape"; }, /** * Whether the viewport orientation is currently in portrait mode. * * @return {Boolean} <code>true</code> when the viewport orientation * is currently in portrait mode. */ isPortrait : function(){ return this._mode == "portrait"; }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @param type {String} Event type * @return {Event} Normalized event object * @internal */ normalize : function(event, element, type){ if(!event){ return event; }; event._type = type; var bindMethods = qx.module.event.Orientation.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Orientation[bindMethods[i]].bind(event); }; }; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(statics.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Attribute) #require(qx.module.Css) #require(qx.module.Environment) #require(qx.module.Event) #require(qx.module.Manipulating) #require(qx.module.Polyfill) #require(qx.module.Traversing) ************************************************************************ */ /** * Placeholder class which simply defines and includes the core of qxWeb. * The core modules are: * * * {@link qx.module.Attribute} * * {@link qx.module.Css} * * {@link qx.module.Environment} * * {@link qx.module.Event} * * {@link qx.module.Manipulating} * * {@link qx.module.Polyfill} * * {@link qx.module.Traversing} */ qx.Bootstrap.define("qx.module.Core", { }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) #require(qx.module.Environment) ************************************************************************ */ /** * Normalization for native keyboard events */ qx.Bootstrap.define("qx.module.event.Keyboard", { statics : { /** * List of event types to be normalized */ TYPES : ["keydown", "keypress", "keyup"], /** * List qx.module.event.Keyboard methods to be attached to native mouse event * objects * @internal */ BIND_METHODS : ["getKeyIdentifier"], /** * Identifier of the pressed key. This property is modeled after the <em>KeyboardEvent.keyIdentifier</em> property * of the W3C DOM 3 event specification * (http://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-KeyboardEvent-keyIdentifier). * * Printable keys are represented by an unicode string, non-printable keys * have one of the following values: * * <table> * <tr><th>Backspace</th><td>The Backspace (Back) key.</td></tr> * <tr><th>Tab</th><td>The Horizontal Tabulation (Tab) key.</td></tr> * <tr><th>Space</th><td>The Space (Spacebar) key.</td></tr> * <tr><th>Enter</th><td>The Enter key. Note: This key identifier is also used for the Return (Macintosh numpad) key.</td></tr> * <tr><th>Shift</th><td>The Shift key.</td></tr> * <tr><th>Control</th><td>The Control (Ctrl) key.</td></tr> * <tr><th>Alt</th><td>The Alt (Menu) key.</td></tr> * <tr><th>CapsLock</th><td>The CapsLock key</td></tr> * <tr><th>Meta</th><td>The Meta key. (Apple Meta and Windows key)</td></tr> * <tr><th>Escape</th><td>The Escape (Esc) key.</td></tr> * <tr><th>Left</th><td>The Left Arrow key.</td></tr> * <tr><th>Up</th><td>The Up Arrow key.</td></tr> * <tr><th>Right</th><td>The Right Arrow key.</td></tr> * <tr><th>Down</th><td>The Down Arrow key.</td></tr> * <tr><th>PageUp</th><td>The Page Up key.</td></tr> * <tr><th>PageDown</th><td>The Page Down (Next) key.</td></tr> * <tr><th>End</th><td>The End key.</td></tr> * <tr><th>Home</th><td>The Home key.</td></tr> * <tr><th>Insert</th><td>The Insert (Ins) key. (Does not fire in Opera/Win)</td></tr> * <tr><th>Delete</th><td>The Delete (Del) Key.</td></tr> * <tr><th>F1</th><td>The F1 key.</td></tr> * <tr><th>F2</th><td>The F2 key.</td></tr> * <tr><th>F3</th><td>The F3 key.</td></tr> * <tr><th>F4</th><td>The F4 key.</td></tr> * <tr><th>F5</th><td>The F5 key.</td></tr> * <tr><th>F6</th><td>The F6 key.</td></tr> * <tr><th>F7</th><td>The F7 key.</td></tr> * <tr><th>F8</th><td>The F8 key.</td></tr> * <tr><th>F9</th><td>The F9 key.</td></tr> * <tr><th>F10</th><td>The F10 key.</td></tr> * <tr><th>F11</th><td>The F11 key.</td></tr> * <tr><th>F12</th><td>The F12 key.</td></tr> * <tr><th>NumLock</th><td>The Num Lock key.</td></tr> * <tr><th>PrintScreen</th><td>The Print Screen (PrintScrn, SnapShot) key.</td></tr> * <tr><th>Scroll</th><td>The scroll lock key</td></tr> * <tr><th>Pause</th><td>The pause/break key</td></tr> * <tr><th>Win</th><td>The Windows Logo key</td></tr> * <tr><th>Apps</th><td>The Application key (Windows Context Menu)</td></tr> * </table> * * @return {String} The key identifier */ getKeyIdentifier : function(){ if(this.type == "keypress" && (qxWeb.env.get("engine.name") != "gecko" || this.charCode !== 0)){ return qx.event.util.Keyboard.charCodeToIdentifier(this.charCode || this.keyCode); }; return qx.event.util.Keyboard.keyCodeToIdentifier(this.keyCode); }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @return {Event} Normalized event object * @internal */ normalize : function(event, element){ if(!event){ return event; }; var bindMethods = qx.module.event.Keyboard.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Keyboard[bindMethods[i]].bind(event); }; }; return event; }, /** * IE9 will not fire an "input" event on text input elements if the user changes * the field's value by pressing the Backspace key. We fix this by listening * for the "keyup" event and emitting the missing event if necessary * * @param element {Element} Target element */ registerInputFix : function(element){ if(element.type === "text" || element.type === "password" || element.type === "textarea"){ if(!element.__inputFix){ element.__inputFix = qxWeb(element).on("keyup", qx.module.event.Keyboard._inputFix); }; }; }, /** * Removes the IE9 input event fix * @param element {Element} target element */ unregisterInputFix : function(element){ if(element.__inputFix && !qxWeb(element).hasListener("input")){ qxWeb(element).off("keyup", qx.module.event.Keyboard._inputFix); element.__inputFix = null; }; }, /** * IE9 fix: Emits an "input" event if a text input element's value was changed * using the Backspace key * @param ev {Event} Keyup event */ _inputFix : function(ev){ if(ev.getKeyIdentifier() !== "Backspace"){ return; }; var target = ev.getTarget(); var newValue = qxWeb(target).getValue(); if(!target.__oldInputValue || target.__oldInputValue !== newValue){ target.__oldInputValue = newValue; ev.type = ev._type = "input"; target.__emitter.emit("input", ev); }; } }, defer : function(statics){ qxWeb.$registerEventNormalization(qx.module.event.Keyboard.TYPES, statics.normalize); if(qxWeb.env.get("engine.name") === "mshtml" && qxWeb.env.get("browser.documentmode") === 9){ qxWeb.$registerEventHook("input", statics.registerInputFix, statics.unregisterInputFix); }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Utilities for working with character codes and key identifiers */ qx.Bootstrap.define("qx.event.util.Keyboard", { statics : { /* --------------------------------------------------------------------------- KEY MAPS --------------------------------------------------------------------------- */ /** * {Map} maps the charcodes of special printable keys to key identifiers * * @lint ignoreReferenceField(specialCharCodeMap) */ specialCharCodeMap : { '8' : "Backspace", // The Backspace (Back) key. '9' : "Tab", // The Horizontal Tabulation (Tab) key. // Note: This key identifier is also used for the // Return (Macintosh numpad) key. '13' : "Enter", // The Enter key. '27' : "Escape", // The Escape (Esc) key. '32' : "Space" }, /** * {Map} maps the keycodes of the numpad keys to the right charcodes * * @lint ignoreReferenceField(numpadToCharCode) */ numpadToCharCode : { '96' : "0".charCodeAt(0), '97' : "1".charCodeAt(0), '98' : "2".charCodeAt(0), '99' : "3".charCodeAt(0), '100' : "4".charCodeAt(0), '101' : "5".charCodeAt(0), '102' : "6".charCodeAt(0), '103' : "7".charCodeAt(0), '104' : "8".charCodeAt(0), '105' : "9".charCodeAt(0), '106' : "*".charCodeAt(0), '107' : "+".charCodeAt(0), '109' : "-".charCodeAt(0), '110' : ",".charCodeAt(0), '111' : "/".charCodeAt(0) }, /** * {Map} maps the keycodes of non printable keys to key identifiers * * @lint ignoreReferenceField(keyCodeToIdentifierMap) */ keyCodeToIdentifierMap : { '16' : "Shift", // The Shift key. '17' : "Control", // The Control (Ctrl) key. '18' : "Alt", // The Alt (Menu) key. '20' : "CapsLock", // The CapsLock key '224' : "Meta", // The Meta key. (Apple Meta and Windows key) '37' : "Left", // The Left Arrow key. '38' : "Up", // The Up Arrow key. '39' : "Right", // The Right Arrow key. '40' : "Down", // The Down Arrow key. '33' : "PageUp", // The Page Up key. '34' : "PageDown", // The Page Down (Next) key. '35' : "End", // The End key. '36' : "Home", // The Home key. '45' : "Insert", // The Insert (Ins) key. (Does not fire in Opera/Win) '46' : "Delete", // The Delete (Del) Key. '112' : "F1", // The F1 key. '113' : "F2", // The F2 key. '114' : "F3", // The F3 key. '115' : "F4", // The F4 key. '116' : "F5", // The F5 key. '117' : "F6", // The F6 key. '118' : "F7", // The F7 key. '119' : "F8", // The F8 key. '120' : "F9", // The F9 key. '121' : "F10", // The F10 key. '122' : "F11", // The F11 key. '123' : "F12", // The F12 key. '144' : "NumLock", // The Num Lock key. '44' : "PrintScreen", // The Print Screen (PrintScrn, SnapShot) key. '145' : "Scroll", // The scroll lock key '19' : "Pause", // The pause/break key // The left Windows Logo key or left cmd key '91' : qx.core.Environment.get("os.name") == "osx" ? "cmd" : "Win", '92' : "Win", // The right Windows Logo key or left cmd key // The Application key (Windows Context Menu) or right cmd key '93' : qx.core.Environment.get("os.name") == "osx" ? "cmd" : "Apps" }, /** char code for capital A */ charCodeA : "A".charCodeAt(0), /** char code for capital Z */ charCodeZ : "Z".charCodeAt(0), /** char code for 0 */ charCode0 : "0".charCodeAt(0), /** char code for 9 */ charCode9 : "9".charCodeAt(0), /** * converts a keyboard code to the corresponding identifier * * @param keyCode {Integer} key code * @return {String} key identifier */ keyCodeToIdentifier : function(keyCode){ if(this.isIdentifiableKeyCode(keyCode)){ var numPadKeyCode = this.numpadToCharCode[keyCode]; if(numPadKeyCode){ return String.fromCharCode(numPadKeyCode); }; return (this.keyCodeToIdentifierMap[keyCode] || this.specialCharCodeMap[keyCode] || String.fromCharCode(keyCode)); } else { return "Unidentified"; }; }, /** * converts a character code to the corresponding identifier * * @param charCode {String} character code * @return {String} key identifier */ charCodeToIdentifier : function(charCode){ return this.specialCharCodeMap[charCode] || String.fromCharCode(charCode).toUpperCase(); }, /** * Check whether the keycode can be reliably detected in keyup/keydown events * * @param keyCode {String} key code to check. * @return {Boolean} Whether the keycode can be reliably detected in keyup/keydown events. */ isIdentifiableKeyCode : function(keyCode){ // A-Z (TODO: is this lower or uppercase?) if(keyCode >= this.charCodeA && keyCode <= this.charCodeZ){ return true; }; // 0-9 if(keyCode >= this.charCode0 && keyCode <= this.charCode9){ return true; }; // Enter, Space, Tab, Backspace if(this.specialCharCodeMap[keyCode]){ return true; }; // Numpad if(this.numpadToCharCode[keyCode]){ return true; }; // non printable keys if(this.isNonPrintableKeyCode(keyCode)){ return true; }; return false; }, /** * Checks whether the keyCode represents a non printable key * * @param keyCode {String} key code to check. * @return {Boolean} Whether the keyCode represents a non printable key. */ isNonPrintableKeyCode : function(keyCode){ return this.keyCodeToIdentifierMap[keyCode] ? true : false; }, /** * Checks whether a given string is a valid keyIdentifier * * @param keyIdentifier {String} The key identifier. * @return {Boolean} whether the given string is a valid keyIdentifier */ isValidKeyIdentifier : function(keyIdentifier){ if(this.identifierToKeyCodeMap[keyIdentifier]){ return true; }; if(keyIdentifier.length != 1){ return false; }; if(keyIdentifier >= "0" && keyIdentifier <= "9"){ return true; }; if(keyIdentifier >= "A" && keyIdentifier <= "Z"){ return true; }; switch(keyIdentifier){case "+":case "-":case "*":case "/": return true;default: return false;}; }, /** * Checks whether a given string is a printable keyIdentifier. * * @param keyIdentifier {String} The key identifier. * @return {Boolean} whether the given string is a printable keyIdentifier. */ isPrintableKeyIdentifier : function(keyIdentifier){ if(keyIdentifier === "Space"){ return true; } else { return this.identifierToKeyCodeMap[keyIdentifier] ? false : true; }; } }, defer : function(statics, members){ // construct inverse of keyCodeToIdentifierMap if(!statics.identifierToKeyCodeMap){ statics.identifierToKeyCodeMap = { }; for(var key in statics.keyCodeToIdentifierMap){ statics.identifierToKeyCodeMap[statics.keyCodeToIdentifierMap[key]] = parseInt(key, 10); }; for(var key in statics.specialCharCodeMap){ statics.identifierToKeyCodeMap[statics.specialCharCodeMap[key]] = parseInt(key, 10); }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * A wrapper for Cookie handling. */ qx.Bootstrap.define("qx.bom.Cookie", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /* --------------------------------------------------------------------------- USER APPLICATION METHODS --------------------------------------------------------------------------- */ /** * Returns the string value of a cookie. * * @param key {String} The key for the saved string value. * @return {null | String} Returns the saved string value, if the cookie * contains a value for the key, <code>null</code> otherwise. */ get : function(key){ var start = document.cookie.indexOf(key + "="); var len = start + key.length + 1; if((!start) && (key != document.cookie.substring(0, key.length))){ return null; }; if(start == -1){ return null; }; var end = document.cookie.indexOf(";", len); if(end == -1){ end = document.cookie.length; }; return unescape(document.cookie.substring(len, end)); }, /** * Sets the string value of a cookie. * * @param key {String} The key for the string value. * @param value {String} The string value. * @param expires {Number?null} The expires in days starting from now, * or <code>null</code> if the cookie should deleted after browser close. * @param path {String?null} Path value. * @param domain {String?null} Domain value. * @param secure {Boolean?null} Secure flag. */ set : function(key, value, expires, path, domain, secure){ // Generate cookie var cookie = [key, "=", escape(value)]; if(expires){ var today = new Date(); today.setTime(today.getTime()); cookie.push(";expires=", new Date(today.getTime() + (expires * 1000 * 60 * 60 * 24)).toGMTString()); }; if(path){ cookie.push(";path=", path); }; if(domain){ cookie.push(";domain=", domain); }; if(secure){ cookie.push(";secure"); }; // Store cookie document.cookie = cookie.join(""); }, /** * Deletes the string value of a cookie. * * @param key {String} The key for the string value. * @param path {String?null} Path value. * @param domain {String?null} Domain value. */ del : function(key, path, domain){ if(!qx.bom.Cookie.get(key)){ return; }; // Generate cookie var cookie = [key, "="]; if(path){ cookie.push(";path=", path); }; if(domain){ cookie.push(";domain=", domain); }; cookie.push(";expires=Thu, 01-Jan-1970 00:00:01 GMT"); // Store cookie document.cookie = cookie.join(""); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /** * Cookie handling module */ qx.Bootstrap.define("qx.module.Cookie", { statics : { /** * Returns the string value of a cookie. * * @attachStatic {qxWeb, cookie.get} * @param key {String} The key for the saved string value. * @return {String|null} Returns the saved string value if the cookie * contains a value for the key, otherwise <code>null</code> * @signature function(key) */ get : qx.bom.Cookie.get, /** * Sets the string value of a cookie. * * @attachStatic {qxWeb, cookie.set} * @param key {String} The key for the string value. * @param value {String} The string value. * @param expires {Number?null} Expires directive value in days starting from now, * or <code>null</code> if the cookie should be deleted when the browser * is closed. * @param path {String?null} Path value. * @param domain {String?null} Domain value. * @param secure {Boolean?null} Secure flag. * @signature function(key, value, expires, path, domain, secure) */ set : qx.bom.Cookie.set, /** * Deletes the string value of a cookie. * * @attachStatic {qxWeb, cookie.del} * @param key {String} The key for the string value. * @param path {String?null} Path value. * @param domain {String?null} Domain value. * @signature function(key, path, domain) */ del : qx.bom.Cookie.del }, defer : function(statics){ qxWeb.$attachStatic({ "cookie" : { get : statics.get, set : statics.set, del : statics.del } }); } }); var exp = envinfo["qx.export"]; if (exp) { for (var name in exp) { var c = exp[name].split("."); var root = window; for (var i=0; i < c.length; i++) { root = root[c[i]]; }; window[name] = root; } } window["qx"] = undefined; try { delete window.qx; } catch(e) {} })();
app/components/Contact.js
darrylivan/marcojscalise.com
/** * Created by darryl on 1/24/17. */ import React from 'react'; const Contact = () => <div> <section id="page-title"> <div className="container clearfix"> <h1>Contact Me</h1> <span>Call or email for an appointment.</span> <ol className="breadcrumb"> <li><a href="/">Home</a></li> <li className="active">Contact</li> </ol> </div> </section> <div style={ { height: '20px' }}></div> <div className="container clearfix"> <div className="row clear-bottommargin"> <div className="col-md-4 col-sm-6 bottommargin clearfix"> <div className="feature-box fbox-center fbox-bg fbox-plain"> <div className="fbox-icon"> <a href="#"><i className="icon-map-marker2"></i></a> </div> <h3>Our Headquarters<span className="subtitle"> 1351 N. Cleveland St.<br/> Loveland, CO 80537</span></h3> </div> </div> <div className="col-md-4 col-sm-6 bottommargin clearfix"> <div className="feature-box fbox-center fbox-bg fbox-plain"> <div className="fbox-icon"> <a href="#"><i className="icon-phone3"></i></a> </div> <h3>Make an appointment<span className="subtitle"> <a href="tel:970.613.1270">970.613.1270</a><br/>&nbsp;</span></h3> </div> </div> <div className="col-md-4 col-sm-6 bottommargin clearfix"> <div className="feature-box fbox-center fbox-bg fbox-plain"> <div className="fbox-icon"> <a href="#"><i className="icon-email"></i></a> </div> <h3>Send us a note<span className="subtitle"> marco@marcojscalise.com<br/>&nbsp;</span></h3> </div> </div> </div> <div className="divider"><i className="icon-circle"></i></div> </div> </div>; export default Contact;
src/index.js
fcsonline/react-transmission
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'mobx-react'; import { AppContainer } from 'react-hot-loader'; import { IntlProvider, addLocaleData } from 'react-intl'; import * as stores from 'stores'; import notify from 'reactions/notify'; import App from 'components/App'; import en from 'react-intl/locale-data/en'; import es from 'react-intl/locale-data/es'; import enTranslations from 'translations/en.json'; import esTranslations from 'translations/es.json'; addLocaleData([...en, ...es]); const messages = { 'en-US': enTranslations, en: enTranslations, es: esTranslations, }; // Start reactions notify(stores); const rootEl = document.getElementById('root'); function renderApp(app) { return ReactDOM.render( <AppContainer> <Provider {...stores}> <IntlProvider locale={navigator.language} messages={messages[navigator.language]}> {app} </IntlProvider> </Provider> </AppContainer>, rootEl ); } renderApp(<App />); if (module.hot) { module.hot.accept('components/App', () => { const NextApp = require('components/App').default; renderApp(<NextApp />); }); }
src/components/Links/messages.js
transitlinks/web-app
import React from 'react'; import { defineMessages } from 'react-intl'; export default defineMessages({ 'profile-link': { id: 'account.profileLink', defaultMessage: 'Profile', description: 'Profile' }, 'links-link': { id: 'account.linksLink', defaultMessage: 'Links', description: 'Links' }, 'logout': { id: 'account.logout', defaultMessage: 'Log out', description: 'Log out' } });
src/components/Icons/IconTrash.js
chrisxclash/play-midnight
import React from 'react'; import SvgIcon from './SvgIcon'; const IconTrash = props => ( <SvgIcon viewBox="0 0 26 26" {...props}> <path d="M 11 -0.03125 C 10.164063 -0.03125 9.34375 0.132813 8.75 0.71875 C 8.15625 1.304688 7.96875 2.136719 7.96875 3 L 4 3 C 3.449219 3 3 3.449219 3 4 L 2 4 L 2 6 L 24 6 L 24 4 L 23 4 C 23 3.449219 22.550781 3 22 3 L 18.03125 3 C 18.03125 2.136719 17.84375 1.304688 17.25 0.71875 C 16.65625 0.132813 15.835938 -0.03125 15 -0.03125 Z M 11 2.03125 L 15 2.03125 C 15.546875 2.03125 15.71875 2.160156 15.78125 2.21875 C 15.84375 2.277344 15.96875 2.441406 15.96875 3 L 10.03125 3 C 10.03125 2.441406 10.15625 2.277344 10.21875 2.21875 C 10.28125 2.160156 10.453125 2.03125 11 2.03125 Z M 4 7 L 4 23 C 4 24.652344 5.347656 26 7 26 L 19 26 C 20.652344 26 22 24.652344 22 23 L 22 7 Z M 8 10 L 10 10 L 10 22 L 8 22 Z M 12 10 L 14 10 L 14 22 L 12 22 Z M 16 10 L 18 10 L 18 22 L 16 22 Z "/> </SvgIcon> ); export default IconTrash;
client/src/components/Connections/components/Search.js
verejnedigital/verejne.digital
// @flow import React from 'react' import {withRouter} from 'react-router-dom' import {withHandlers, withState} from 'recompose' import {compose} from 'redux' import {Form, FormGroup, Label, Button} from 'reactstrap' import type {ContextRouter} from 'react-router' import EntitySearchWrapper, {type EntitySearchProps} from '../dataWrappers/EntitySearchWrapper' import AutoComplete from '../../shared/AutoComplete/AutoComplete' import './Search.css' type EmptyHandler = () => void type EventHandler = (e: Event) => void type selectHandler = (value: string) => void type Props = { searchValue1: string, searchValue2: string, setSearchValue1: EventHandler, setSearchValue2: EventHandler, handleSelect1: selectHandler, handleSelect2: selectHandler, searchOnEnter: EventHandler, searchConnection: EmptyHandler, } & EntitySearchProps & ContextRouter const _searchConnection = (props: Props) => { if (props.searchValue1.trim() !== '') { if (props.searchValue2.trim() !== '') { props.history.push( `/prepojenia?eid1=${props.searchValue1.trim()}&eid2=${props.searchValue2.trim()}` ) } else { props.history.push(`/prepojenia?eid1=${props.searchValue1.trim()}`) } } } const Search = ({ searchValue1, searchValue2, setSearchValue1, setSearchValue2, handleSelect1, handleSelect2, searchOnEnter, searchConnection, }: Props) => ( <div className="connections-search-wrapper"> <h2>Vyhľadaj</h2> <p>Zaujímavé spojenia jednotlivca alebo najkratšie spojenie medzi dvojicou:</p> <Form> <FormGroup> <Label for="searchValue1">Prvá firma/osoba*</Label> <AutoComplete value={searchValue1} onChangeHandler={setSearchValue1} onSelectHandler={handleSelect1} menuClassName="connections-autocomplete-suggestions" inputProps={{ className: 'form-control connections-autocomplete-input', onKeyPress: searchOnEnter, placeholder: 'Zadaj prvú firmu / človeka', }} wrapperProps={{ className: 'connections-autocomplete-wrapper', }} /> </FormGroup> <FormGroup> <Label htmlFor="searchValue2">Druhá firma/osoba</Label> <AutoComplete value={searchValue2} onChangeHandler={setSearchValue2} onSelectHandler={handleSelect2} menuClassName="connections-autocomplete-suggestions" inputProps={{ className: 'form-control connections-autocomplete-input', onKeyPress: searchOnEnter, placeholder: 'Zadaj druhú firmu / človeka', }} wrapperProps={{ className: 'connections-autocomplete-wrapper', }} /> </FormGroup> <Button color="primary" onClick={searchConnection}> Vyhľadať </Button> </Form> </div> ) export default compose( withRouter, EntitySearchWrapper, withState('searchValue1', 'setSearchValue1', ({entitySearch1}) => entitySearch1), withState('searchValue2', 'setSearchValue2', ({entitySearch2}) => entitySearch2), withHandlers({ setSearchValue1: ({setSearchValue1}) => (e) => setSearchValue1(e.target.value), setSearchValue2: ({setSearchValue2}) => (e) => setSearchValue2(e.target.value), handleSelect1: ({setSearchValue1}) => (value) => setSearchValue1(value), handleSelect2: ({setSearchValue2}) => (value) => setSearchValue2(value), searchOnEnter: (props: Props) => (e) => { if (e.key === 'Enter') { _searchConnection(props) } }, searchConnection: (props: Props) => () => _searchConnection(props), }) )(Search)
node_modules/react-dom/dist/react-dom-server.js
yongliu2001/ReduxExample
/** * ReactDOMServer v0.14.7 * * 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. * */ // Based off https://github.com/ForbesLindesay/umd/blob/master/template.js ;(function(f) { // CommonJS if (typeof exports === "object" && typeof module !== "undefined") { module.exports = f(require('react')); // RequireJS } else if (typeof define === "function" && define.amd) { define(['react'], f); // <script> } else { var g; if (typeof window !== "undefined") { g = window; } else if (typeof global !== "undefined") { g = global; } else if (typeof self !== "undefined") { g = self; } else { // works providing we're not in "use strict"; // needed for Java 8 Nashorn // see https://github.com/facebook/react/issues/3037 g = this; } g.ReactDOMServer = f(g.React); } })(function(React) { return React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; });
ajax/libs/yui/3.16.0/datatable-body/datatable-body-debug.js
him2him2/cdnjs
/* YUI 3.16.0 (build 76f0e08) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('datatable-body', function (Y, NAME) { /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. @module datatable @submodule datatable-body @since 3.5.0 **/ var Lang = Y.Lang, isArray = Lang.isArray, isNumber = Lang.isNumber, isString = Lang.isString, fromTemplate = Lang.sub, htmlEscape = Y.Escape.html, toArray = Y.Array, bind = Y.bind, YObject = Y.Object, valueRegExp = /\{value\}/g, EV_CONTENT_UPDATE = 'contentUpdate', shiftMap = { above: [-1, 0], below: [1, 0], next: [0, 1], prev: [0, -1], previous: [0, -1] }; /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. Translates the provided `modelList` into a rendered `<tbody>` based on the data in the constituent Models, altered or amended by any special column configurations. The `columns` configuration, passed to the constructor, determines which columns will be rendered. The rendering process involves constructing an HTML template for a complete row of data, built by concatenating a customized copy of the instance's `CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is then populated with values from each Model in the `modelList`, aggregating a complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. A column `formatter` can be: * a function, as described below. * a string which can be: * the name of a pre-defined formatter function which can be located in the `Y.DataTable.BodyView.Formatters` hash using the value of the `formatter` property as the index. * A template that can use the `{value}` placeholder to include the value for the current cell or the name of any field in the underlaying model also enclosed in curly braces. Any number and type of these placeholders can be used. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @class BodyView @namespace DataTable @extends View @since 3.5.0 **/ Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], { // -- Instance properties ------------------------------------------------- /** HTML template used to create table cells. @property CELL_TEMPLATE @type {String} @default '<td {headers} class="{className}">{content}</td>' @since 3.5.0 **/ CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>', /** CSS class applied to even rows. This is assigned at instantiation. For DataTable, this will be `yui3-datatable-even`. @property CLASS_EVEN @type {String} @default 'yui3-table-even' @since 3.5.0 **/ //CLASS_EVEN: null /** CSS class applied to odd rows. This is assigned at instantiation. When used by DataTable instances, this will be `yui3-datatable-odd`. @property CLASS_ODD @type {String} @default 'yui3-table-odd' @since 3.5.0 **/ //CLASS_ODD: null /** HTML template used to create table rows. @property ROW_TEMPLATE @type {String} @default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>' @since 3.5.0 **/ ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>', /** The object that serves as the source of truth for column and row data. This property is assigned at instantiation from the `host` property of the configuration object passed to the constructor. @property host @type {Object} @default (initially unset) @since 3.5.0 **/ //TODO: should this be protected? //host: null, /** HTML templates used to create the `<tbody>` containing the table rows. @property TBODY_TEMPLATE @type {String} @default '<tbody class="{className}">{content}</tbody>' @since 3.6.0 **/ TBODY_TEMPLATE: '<tbody class="{className}"></tbody>', // -- Public methods ------------------------------------------------------ /** Returns the `<td>` Node from the given row and column index. Alternately, the `seed` can be a Node. If so, the nearest ancestor cell is returned. If the `seed` is a cell, it is returned. If there is no cell at the given coordinates, `null` is returned. Optionally, include an offset array or string to return a cell near the cell identified by the `seed`. The offset can be an array containing the number of rows to shift followed by the number of columns to shift, or one of "above", "below", "next", or "previous". <pre><code>// Previous cell in the previous row var cell = table.getCell(e.target, [-1, -1]); // Next cell var cell = table.getCell(e.target, 'next'); var cell = table.getCell(e.target, [0, 1];</pre></code> @method getCell @param {Number[]|Node} seed Array of row and column indexes, or a Node that is either the cell itself or a descendant of one. @param {Number[]|String} [shift] Offset by which to identify the returned cell Node @return {Node} @since 3.5.0 **/ getCell: function (seed, shift) { var tbody = this.tbodyNode, row, cell, index, rowIndexOffset; if (seed && tbody) { if (isArray(seed)) { row = tbody.get('children').item(seed[0]); cell = row && row.get('children').item(seed[1]); } else if (seed._node) { cell = seed.ancestor('.' + this.getClassName('cell'), true); } if (cell && shift) { rowIndexOffset = tbody.get('firstChild.rowIndex'); if (isString(shift)) { if (!shiftMap[shift]) { Y.error('Unrecognized shift: ' + shift, null, 'datatable-body'); } shift = shiftMap[shift]; } if (isArray(shift)) { index = cell.get('parentNode.rowIndex') + shift[0] - rowIndexOffset; row = tbody.get('children').item(index); index = cell.get('cellIndex') + shift[1]; cell = row && row.get('children').item(index); } } } return cell || null; }, /** Returns the generated CSS classname based on the input. If the `host` attribute is configured, it will attempt to relay to its `getClassName` or use its static `NAME` property as a string base. If `host` is absent or has neither method nor `NAME`, a CSS classname will be generated using this class's `NAME`. @method getClassName @param {String} token* Any number of token strings to assemble the classname from. @return {String} @protected @since 3.5.0 **/ getClassName: function () { var host = this.host, args; if (host && host.getClassName) { return host.getClassName.apply(host, arguments); } else { args = toArray(arguments); args.unshift(this.constructor.NAME); return Y.ClassNameManager.getClassName .apply(Y.ClassNameManager, args); } }, /** Returns the Model associated to the row Node or id provided. Passing the Node or id for a descendant of the row also works. If no Model can be found, `null` is returned. @method getRecord @param {String|Node} seed Row Node or `id`, or one for a descendant of a row @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var modelList = this.get('modelList'), tbody = this.tbodyNode, row = null, record; if (tbody) { if (isString(seed)) { seed = tbody.one('#' + seed); } if (seed && seed._node) { row = seed.ancestor(function (node) { return node.get('parentNode').compareTo(tbody); }, true); record = row && modelList.getByClientId(row.getData('yui3-record')); } } return record || null; }, /** Returns the `<tr>` Node from the given row index, Model, or Model's `clientId`. If the rows haven't been rendered yet, or if the row can't be found by the input, `null` is returned. @method getRow @param {Number|String|Model} id Row index, Model instance, or clientId @return {Node} @since 3.5.0 **/ getRow: function (id) { var tbody = this.tbodyNode, row = null; if (tbody) { if (id) { id = this._idMap[id.get ? id.get('clientId') : id] || id; } row = isNumber(id) ? tbody.get('children').item(id) : tbody.one('#' + id); } return row; }, /** Creates the table's `<tbody>` content by assembling markup generated by populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content from the `columns` and `modelList` attributes. The rendering process happens in three stages: 1. A row template is assembled from the `columns` attribute (see `_createRowTemplate`) 2. An HTML string is built up by concatenating the application of the data in each Model in the `modelList` to the row template. For cells with `formatter`s, the function is called to generate cell content. Cells with `nodeFormatter`s are ignored. For all other cells, the data value from the Model attribute for the given column key is used. The accumulated row markup is then inserted into the container. 3. If any column is configured with a `nodeFormatter`, the `modelList` is iterated again to apply the `nodeFormatter`s. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @method render @chainable @since 3.5.0 **/ render: function () { var table = this.get('container'), data = this.get('modelList'), displayCols = this.get('columns'), tbody = this.tbodyNode || (this.tbodyNode = this._createTBodyNode()); // Needed for mutation this._createRowTemplate(displayCols); if (data) { tbody.setHTML(this._createDataHTML(displayCols)); this._applyNodeFormatters(tbody, displayCols); } if (tbody.get('parentNode') !== table) { table.appendChild(tbody); } this.bindUI(); return this; }, /** Refreshes the provided row against the provided model and the Array of columns to be updated. @method refreshRow @param {Node} row @param {Model} model Y.Model representation of the row @param {String[]} colKeys Array of column keys @chainable */ refreshRow: function (row, model, colKeys) { var col, cell, len = colKeys.length, i; for (i = 0; i < len; i++) { col = this.getColumn(colKeys[i]); if (col !== null) { cell = row.one('.' + this.getClassName('col', col._id || col.key)); this.refreshCell(cell, model); } } return this; }, /** Refreshes the given cell with the provided model data and the provided column configuration. Uses the provided column formatter if aviable. @method refreshCell @param {Node} cell Y.Node pointer to the cell element to be updated @param {Model} [model] Y.Model representation of the row @param {Object} [col] Column configuration object for the cell @chainable */ refreshCell: function (cell, model, col) { var content, formatterFn, formatterData, data = model.toJSON(); cell = this.getCell(cell); /* jshint -W030 */ model || (model = this.getRecord(cell)); col || (col = this.getColumn(cell)); /* jshint +W030 */ if (col.nodeFormatter) { formatterData = { cell: cell.one('.' + this.getClassName('liner')) || cell, column: col, data: data, record: model, rowIndex: this._getRowIndex(cell.ancestor('tr')), td: cell, value: data[col.key] }; keep = col.nodeFormatter.call(host,formatterData); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. cell.destroy(true); } } else if (col.formatter) { if (!col._formatterFn) { col = this._setColumnsFormatterFn([col])[0]; } formatterFn = col._formatterFn || null; if (formatterFn) { formatterData = { value : data[col.key], data : data, column : col, record : model, className: '', rowClass : '', rowIndex : this._getRowIndex(cell.ancestor('tr')) }; // Formatters can either return a value ... content = formatterFn.call(this.get('host'), formatterData); // ... or update the value property of the data obj passed if (content === undefined) { content = formatterData.value; } } if (content === undefined || content === null || content === '') { content = col.emptyCellValue || ''; } } else { content = data[col.key] || col.emptyCellValue || ''; } cell.setHTML(col.allowHTML ? content : Y.Escape.html(content)); return this; }, /** Returns column data from this.get('columns'). If a Y.Node is provided as the key, will try to determine the key from the classname @method getColumn @param {String|Node} name @return {Object} Returns column configuration */ getColumn: function (name) { if (name && name._node) { // get column name from node name = name.get('className').match( new RegExp( this.getClassName('col') +'-([^ ]*)' ) )[1]; } if (this.host) { return this.host._columnMap[name] || null; } var displayCols = this.get('columns'), col = null; Y.Array.some(displayCols, function (_col) { if ((_col._id || _col.key) === name) { col = _col; return true; } }); return col; }, // -- Protected and private methods --------------------------------------- /** Handles changes in the source's columns attribute. Redraws the table data. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ // TODO: Preserve existing DOM // This will involve parsing and comparing the old and new column configs // and reacting to four types of changes: // 1. formatter, nodeFormatter, emptyCellValue changes // 2. column deletions // 3. column additions // 4. column moves (preserve cells) _afterColumnsChange: function () { this.render(); }, /** Handles modelList changes, including additions, deletions, and updates. Modifies the existing table DOM accordingly. @method _afterDataChange @param {EventFacade} e The `change` event from the ModelList @protected @since 3.5.0 **/ _afterDataChange: function (e) { var type = (e.type.match(/:(add|change|remove)$/) || [])[1], index = e.index, displayCols = this.get('columns'), col, changed = e.changed && Y.Object.keys(e.changed), key, row, i, len; for (i = 0, len = displayCols.length; i < len; i++ ) { col = displayCols[i]; // since nodeFormatters typcially make changes outside of it's // cell, we need to see if there are any columns that have a // nodeFormatter and if so, we need to do a full render() of the // tbody if (col.hasOwnProperty('nodeFormatter')) { this.render(); this.fire(EV_CONTENT_UPDATE); return; } } // TODO: if multiple rows are being added/remove/swapped, can we avoid the restriping? switch (type) { case 'change': for (i = 0, len = displayCols.length; i < len; i++) { col = displayCols[i]; key = col.key; if (col.formatter && !e.changed[key]) { changed.push(key); } } this.refreshRow(this.getRow(e.target), e.target, changed); break; case 'add': // we need to make sure we don't have an index larger than the data we have index = Math.min(index, this.get('modelList').size() - 1); // updates the columns with formatter functions this._setColumnsFormatterFn(displayCols); row = Y.Node.create(this._createRowHTML(e.model, index, displayCols)); this.tbodyNode.insert(row, index); this._restripe(index); break; case 'remove': this.getRow(index).remove(true); // we removed a row, so we need to back up our index to stripe this._restripe(index - 1); break; default: this.render(); } // Event fired to tell users when we are done updating after the data // was changed this.fire(EV_CONTENT_UPDATE); }, /** Toggles the odd/even classname of the row after the given index. This method is used to update rows after a row is inserted into or removed from the table. Note this event is delayed so the table is only restriped once when multiple rows are updated at one time. @protected @method _restripe @param {Number} [index] Index of row to start restriping after @since 3.11.0 */ _restripe: function (index) { var task = this._restripeTask, self; // index|0 to force int, avoid NaN. Math.max() to avoid neg indexes. index = Math.max((index|0), 0); if (!task) { self = this; this._restripeTask = { timer: setTimeout(function () { // Check for self existence before continuing if (!self || self.get('destroy') || !self.tbodyNode || !self.tbodyNode.inDoc()) { self._restripeTask = null; return; } var odd = [self.CLASS_ODD, self.CLASS_EVEN], even = [self.CLASS_EVEN, self.CLASS_ODD], index = self._restripeTask.index; self.tbodyNode.get('childNodes') .slice(index) .each(function (row, i) { // TODO: each vs batch row.replaceClass.apply(row, (index + i) % 2 ? even : odd); }); self._restripeTask = null; }, 0), index: index }; } else { task.index = Math.min(task.index, index); } }, /** Handles replacement of the modelList. Rerenders the `<tbody>` contents. @method _afterModelListChange @param {EventFacade} e The `modelListChange` event @protected @since 3.6.0 **/ _afterModelListChange: function () { var handles = this._eventHandles; if (handles.dataChange) { handles.dataChange.detach(); delete handles.dataChange; this.bindUI(); } if (this.tbodyNode) { this.render(); } }, /** Iterates the `modelList`, and calls any `nodeFormatter`s found in the `columns` param on the appropriate cell Nodes in the `tbody`. @method _applyNodeFormatters @param {Node} tbody The `<tbody>` Node whose columns to update @param {Object[]} displayCols The column configurations @protected @since 3.5.0 **/ _applyNodeFormatters: function (tbody, displayCols) { var host = this.host || this, data = this.get('modelList'), formatters = [], linerQuery = '.' + this.getClassName('liner'), rows, i, len; // Only iterate the ModelList again if there are nodeFormatters for (i = 0, len = displayCols.length; i < len; ++i) { if (displayCols[i].nodeFormatter) { formatters.push(i); } } if (data && formatters.length) { rows = tbody.get('childNodes'); data.each(function (record, index) { var formatterData = { data : record.toJSON(), record : record, rowIndex : index }, row = rows.item(index), i, len, col, key, cells, cell, keep; if (row) { cells = row.get('childNodes'); for (i = 0, len = formatters.length; i < len; ++i) { cell = cells.item(formatters[i]); if (cell) { col = formatterData.column = displayCols[formatters[i]]; key = col.key || col.id; formatterData.value = record.get(key); formatterData.td = cell; formatterData.cell = cell.one(linerQuery) || cell; keep = col.nodeFormatter.call(host,formatterData); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. cell.destroy(true); } } } } }); } }, /** Binds event subscriptions from the UI and the host (if assigned). @method bindUI @protected @since 3.5.0 **/ bindUI: function () { var handles = this._eventHandles, modelList = this.get('modelList'), changeEvent = modelList.model.NAME + ':change'; if (!handles.columnsChange) { handles.columnsChange = this.after('columnsChange', bind('_afterColumnsChange', this)); } if (modelList && !handles.dataChange) { handles.dataChange = modelList.after( ['add', 'remove', 'reset', changeEvent], bind('_afterDataChange', this)); } }, /** Iterates the `modelList` and applies each Model to the `_rowTemplate`, allowing any column `formatter` or `emptyCellValue` to override cell content for the appropriate column. The aggregated HTML string is returned. @method _createDataHTML @param {Object[]} displayCols The column configurations to customize the generated cell content or class names @return {String} The markup for all Models in the `modelList`, each applied to the `_rowTemplate` @protected @since 3.5.0 **/ _createDataHTML: function (displayCols) { var data = this.get('modelList'), html = ''; if (data) { data.each(function (model, index) { html += this._createRowHTML(model, index, displayCols); }, this); } return html; }, /** Applies the data of a given Model, modified by any column formatters and supplemented by other template values to the instance's `_rowTemplate` (see `_createRowTemplate`). The generated string is then returned. The data from Model's attributes is fetched by `toJSON` and this data object is appended with other properties to supply values to {placeholders} in the template. For a template generated from a Model with 'foo' and 'bar' attributes, the data object would end up with the following properties before being used to populate the `_rowTemplate`: * `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute. * `foo` - The value to populate the 'foo' column cell content. This value will be the value stored in the Model's `foo` attribute, or the result of the column's `formatter` if assigned. If the value is '', `null`, or `undefined`, and the column's `emptyCellValue` is assigned, that value will be used. * `bar` - Same for the 'bar' column cell content. * `foo-className` - String of CSS classes to apply to the `<td>`. * `bar-className` - Same. * `rowClass` - String of CSS classes to apply to the `<tr>`. This will be the odd/even class per the specified index plus any additional classes assigned by column formatters (via `o.rowClass`). Because this object is available to formatters, any additional properties can be added to fill in custom {placeholders} in the `_rowTemplate`. @method _createRowHTML @param {Model} model The Model instance to apply to the row template @param {Number} index The index the row will be appearing @param {Object[]} displayCols The column configurations @return {String} The markup for the provided Model, less any `nodeFormatter`s @protected @since 3.5.0 **/ _createRowHTML: function (model, index, displayCols) { var data = model.toJSON(), clientId = model.get('clientId'), values = { rowId : this._getRowId(clientId), clientId: clientId, rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN }, host = this.host || this, i, len, col, token, value, formatterData; for (i = 0, len = displayCols.length; i < len; ++i) { col = displayCols[i]; value = data[col.key]; token = col._id || col.key; values[token + '-className'] = ''; if (col._formatterFn) { formatterData = { value : value, data : data, column : col, record : model, className: '', rowClass : '', rowIndex : index }; // Formatters can either return a value value = col._formatterFn.call(host, formatterData); // or update the value property of the data obj passed if (value === undefined) { value = formatterData.value; } values[token + '-className'] = formatterData.className; values.rowClass += ' ' + formatterData.rowClass; } // if the token missing OR is the value a legit value if (!values.hasOwnProperty(token) || data.hasOwnProperty(col.key)) { if (value === undefined || value === null || value === '') { value = col.emptyCellValue || ''; } values[token] = col.allowHTML ? value : htmlEscape(value); } } // replace consecutive whitespace with a single space values.rowClass = values.rowClass.replace(/\s+/g, ' '); return fromTemplate(this._rowTemplate, values); }, /** Locates the row within the tbodyNode and returns the found index, or Null if it is not found in the tbodyNode @param {Node} row @return {Number} Index of row in tbodyNode */ _getRowIndex: function (row) { var tbody = this.tbodyNode, index = 1; if (tbody && row) { //if row is not in the tbody, return if (row.ancestor('tbody') !== tbody) { return null; } // increment until we no longer have a previous node /*jshint boss: true*/ while (row = row.previous()) { // NOTE: assignment /*jshint boss: false*/ index++; } } return index; }, /** Creates a custom HTML template string for use in generating the markup for individual table rows with {placeholder}s to capture data from the Models in the `modelList` attribute or from column `formatter`s. Assigns the `_rowTemplate` property. @method _createRowTemplate @param {Object[]} displayCols Array of column configuration objects @protected @since 3.5.0 **/ _createRowTemplate: function (displayCols) { var html = '', cellTemplate = this.CELL_TEMPLATE, i, len, col, key, token, headers, tokenValues, formatter; this._setColumnsFormatterFn(displayCols); for (i = 0, len = displayCols.length; i < len; ++i) { col = displayCols[i]; key = col.key; token = col._id || key; formatter = col._formatterFn; // Only include headers if there are more than one headers = (col._headers || []).length > 1 ? 'headers="' + col._headers.join(' ') + '"' : ''; tokenValues = { content : '{' + token + '}', headers : headers, className: this.getClassName('col', token) + ' ' + (col.className || '') + ' ' + this.getClassName('cell') + ' {' + token + '-className}' }; if (!formatter && col.formatter) { tokenValues.content = col.formatter.replace(valueRegExp, tokenValues.content); } if (col.nodeFormatter) { // Defer all node decoration to the formatter tokenValues.content = ''; } html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues); } this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, { content: html }); }, /** Parses the columns array and defines the column's _formatterFn if there is a formatter available on the column @protected @method _setColumnsFormatterFn @param {Object[]} displayCols Array of column configuration objects @return {Object[]} Returns modified displayCols configuration Array */ _setColumnsFormatterFn: function (displayCols) { var Formatters = Y.DataTable.BodyView.Formatters, formatter, col, i, len; for (i = 0, len = displayCols.length; i < len; i++) { col = displayCols[i]; formatter = col.formatter; if (!col._formatterFn && formatter) { if (Lang.isFunction(formatter)) { col._formatterFn = formatter; } else if (formatter in Formatters) { col._formatterFn = Formatters[formatter].call(this.host || this, col); } } } return displayCols; }, /** Creates the `<tbody>` node that will store the data rows. @method _createTBodyNode @return {Node} @protected @since 3.6.0 **/ _createTBodyNode: function () { return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, { className: this.getClassName('data') })); }, /** Destroys the instance. @method destructor @protected @since 3.5.0 **/ destructor: function () { (new Y.EventHandle(YObject.values(this._eventHandles))).detach(); }, /** Holds the event subscriptions needing to be detached when the instance is `destroy()`ed. @property _eventHandles @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_eventHandles: null, /** Returns the row ID associated with a Model's clientId. @method _getRowId @param {String} clientId The Model clientId @return {String} @protected **/ _getRowId: function (clientId) { return this._idMap[clientId] || (this._idMap[clientId] = Y.guid()); }, /** Map of Model clientIds to row ids. @property _idMap @type {Object} @protected **/ //_idMap, /** Initializes the instance. Reads the following configuration properties in addition to the instance attributes: * `columns` - (REQUIRED) The initial column information * `host` - The object to serve as source of truth for column info and for generating class names @method initializer @param {Object} config Configuration data @protected @since 3.5.0 **/ initializer: function (config) { this.host = config.host; this._eventHandles = { modelListChange: this.after('modelListChange', bind('_afterModelListChange', this)) }; this._idMap = {}; this.CLASS_ODD = this.getClassName('odd'); this.CLASS_EVEN = this.getClassName('even'); } /** The HTML template used to create a full row of markup for a single Model in the `modelList` plus any customizations defined in the column configurations. @property _rowTemplate @type {String} @default (initially unset) @protected @since 3.5.0 **/ //_rowTemplate: null },{ /** Hash of formatting functions for cell contents. This property can be populated with a hash of formatting functions by the developer or a set of pre-defined functions can be loaded via the `datatable-formatters` module. See: [DataTable.BodyView.Formatters](./DataTable.BodyView.Formatters.html) @property Formatters @type Object @since 3.8.0 @static **/ Formatters: {} }); }, '3.16.0', {"requires": ["datatable-core", "view", "classnamemanager"]});
imports/ui/components/SearchResults/SearchResults.js
hwillson/meteor-solr-demo
/* eslint-disable react/prefer-es6-class */ import React from 'react'; import ResultCount from '../../../api/search/result_count'; import SearchResult from '../SearchResult/SearchResult'; const SearchResults = React.createClass({ propTypes: { searchResults: React.PropTypes.array.isRequired, searchParams: React.PropTypes.object.isRequired, searchMetadata: React.PropTypes.object.isRequired, }, resultsStartCount() { return ResultCount.calculateStartCount( this.props.searchParams.currentPage, this.props.searchParams.resultsPerPage ); }, renderSearchResults() { return this.props.searchResults.map((searchResult) => ( <SearchResult key={searchResult._id} result={searchResult} currentPage={this.props.searchParams.currentPage} searchMetadata={this.props.searchMetadata} /> )); }, render() { return ( <div className="search-results"> <ol start={this.resultsStartCount()}> {this.renderSearchResults()} </ol> </div> ); }, }); export default SearchResults;
src/components/Cell.js
a-type/redux-data-table
import React from 'react'; const Cell = ({ value, columnKey }) => ( <td>{'' + value}</td> ); export default Cell;
src/components/LoadingPanel.js
daheim/daheim-app-ui
import React from 'react' import CircularProgress from 'material-ui/CircularProgress' export default class LoadingPanel extends React.Component { static defaultProps = { loading: false } static propTypes = { loading: React.PropTypes.bool, children: React.PropTypes.node, style: React.PropTypes.object } render () { let {style, loading, ...props} = this.props let loadingDiv let loadingStyle = {} if (loading) { loadingDiv = ( <div style={{position: 'absolute', width: '100%', height: '100%', zIndex: 100, display: 'flex', alignItems: 'center'}}> <CircularProgress style={{margin: '0 auto'}} /> </div> ) loadingStyle.opacity = 0.2 } return ( <div style={Object.assign({position: 'relative', width: '100%'}, style)} {...props}> {loadingDiv} <div style={loadingStyle}> {this.props.children} </div> </div> ) } }
test/test_helper.js
rafaalb/BlogsReact
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
docs/src/pages/components/pickers/TimePickers.js
lgollut/material-ui
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import TextField from '@material-ui/core/TextField'; const useStyles = makeStyles((theme) => ({ container: { display: 'flex', flexWrap: 'wrap', }, textField: { marginLeft: theme.spacing(1), marginRight: theme.spacing(1), width: 200, }, })); export default function TimePickers() { const classes = useStyles(); return ( <form className={classes.container} noValidate> <TextField id="time" label="Alarm clock" type="time" defaultValue="07:30" className={classes.textField} InputLabelProps={{ shrink: true, }} inputProps={{ step: 300, // 5 min }} /> </form> ); }
app/javascript/mastodon/features/list_editor/components/account.js
foozmeat/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { makeGetAccount } from '../../../selectors'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import IconButton from '../../../components/icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import { removeFromListEditor, addToListEditor } from '../../../actions/lists'; const messages = defineMessages({ remove: { id: 'lists.account.remove', defaultMessage: 'Remove from list' }, add: { id: 'lists.account.add', defaultMessage: 'Add to list' }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = (state, { accountId, added }) => ({ account: getAccount(state, accountId), added: typeof added === 'undefined' ? state.getIn(['listEditor', 'accounts', 'items']).includes(accountId) : added, }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { accountId }) => ({ onRemove: () => dispatch(removeFromListEditor(accountId)), onAdd: () => dispatch(addToListEditor(accountId)), }); @connect(makeMapStateToProps, mapDispatchToProps) @injectIntl export default class Account extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, intl: PropTypes.object.isRequired, onRemove: PropTypes.func.isRequired, onAdd: PropTypes.func.isRequired, added: PropTypes.bool, }; static defaultProps = { added: false, }; render () { const { account, intl, onRemove, onAdd, added } = this.props; let button; if (added) { button = <IconButton icon='times' title={intl.formatMessage(messages.remove)} onClick={onRemove} />; } else { button = <IconButton icon='plus' title={intl.formatMessage(messages.add)} onClick={onAdd} />; } return ( <div className='account'> <div className='account__wrapper'> <div className='account__display-name'> <div className='account__avatar-wrapper'><Avatar account={account} size={36} /></div> <DisplayName account={account} /> </div> <div className='account__relationship'> {button} </div> </div> </div> ); } }
nativeExample/reactNativeDemo/index.android.js
zhanglizhao/react-native-knowledge
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ //导入模块 import React, { Component } from 'react'; //批量定义组件 import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import reactNativeDemo,{Input} from './app'; //定义组件 /*export default class reactNativeDemo extends Component { render() { //这是 JSX ,或 JavaScript 语法扩展,它直接在你的 JavaScript 代码中混合了类似 HTML 的语法 return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } }*/ /** * 定义组件的属性类型和默认属性 * 相对于web开发,需要提供视图的样式,那么StyleSheet.create就是干这件事的,只是用JS的自面量表达了css样式 * */ /*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);
app/javascript/mastodon/components/icon_button.js
h-izumi/mastodon
import React from 'react'; import Motion from 'react-motion/lib/Motion'; import spring from 'react-motion/lib/spring'; import PropTypes from 'prop-types'; class IconButton extends React.PureComponent { static propTypes = { className: PropTypes.string, title: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, onClick: PropTypes.func, size: PropTypes.number, active: PropTypes.bool, style: PropTypes.object, activeStyle: PropTypes.object, disabled: PropTypes.bool, inverted: PropTypes.bool, animate: PropTypes.bool, overlay: PropTypes.bool, }; static defaultProps = { size: 18, active: false, disabled: false, animate: false, overlay: false, }; handleClick = (e) => { e.preventDefault(); if (!this.props.disabled) { this.props.onClick(e); } } render () { const style = { fontSize: `${this.props.size}px`, width: `${this.props.size * 1.28571429}px`, height: `${this.props.size * 1.28571429}px`, lineHeight: `${this.props.size}px`, ...this.props.style, ...(this.props.active ? this.props.activeStyle : {}), }; const classes = ['icon-button']; if (this.props.active) { classes.push('active'); } if (this.props.disabled) { classes.push('disabled'); } if (this.props.inverted) { classes.push('inverted'); } if (this.props.overlay) { classes.push('overlayed'); } if (this.props.className) { classes.push(this.props.className); } return ( <Motion defaultStyle={{ rotate: this.props.active ? -360 : 0 }} style={{ rotate: this.props.animate ? spring(this.props.active ? -360 : 0, { stiffness: 120, damping: 7 }) : 0 }}> {({ rotate }) => <button aria-label={this.props.title} title={this.props.title} className={classes.join(' ')} onClick={this.handleClick} style={style} > <i style={{ transform: `rotate(${rotate}deg)` }} className={`fa fa-fw fa-${this.props.icon}`} aria-hidden='true' /> </button> } </Motion> ); } } export default IconButton;
packages/material-ui-icons/src/TimerOff.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let TimerOff = props => <SvgIcon {...props}> <path d="M19.04 4.55l-1.42 1.42C16.07 4.74 14.12 4 12 4c-1.83 0-3.53.55-4.95 1.48l1.46 1.46C9.53 6.35 10.73 6 12 6c3.87 0 7 3.13 7 7 0 1.27-.35 2.47-.94 3.49l1.45 1.45C20.45 16.53 21 14.83 21 13c0-2.12-.74-4.07-1.97-5.61l1.42-1.42-1.41-1.42zM15 1H9v2h6V1zm-4 8.44l2 2V8h-2v1.44zM3.02 4L1.75 5.27 4.5 8.03C3.55 9.45 3 11.16 3 13c0 4.97 4.02 9 9 9 1.84 0 3.55-.55 4.98-1.5l2.5 2.5 1.27-1.27-7.71-7.71L3.02 4zM12 20c-3.87 0-7-3.13-7-7 0-1.28.35-2.48.95-3.52l9.56 9.56c-1.03.61-2.23.96-3.51.96z" /> </SvgIcon>; TimerOff = pure(TimerOff); TimerOff.muiName = 'SvgIcon'; export default TimerOff;
modules/publication/jsx/uploadForm.js
kongtiaowang/Loris
import React from 'react'; import ProjectFormFields from './projectFields'; import swal from 'sweetalert2'; /** * Publication upload form component */ class PublicationUploadForm extends React.Component { /** * @constructor * @param {object} props - React Component properties */ constructor(props) { super(props); this.state = { Data: {}, formData: {}, numFiles: 0, uploadResult: null, loadError: undefined, formErrors: {}, isLoaded: false, loadedData: 0, uploadProgress: -1, }; this.setFormData = this.setFormData.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.addListItem = this.addListItem.bind(this); this.removeListItem = this.removeListItem.bind(this); this.setFileData = this.setFileData.bind(this); this.fetchData = this.fetchData.bind(this); } /** * Fetch data */ fetchData() { fetch(this.props.DataURL, { method: 'GET', }).then((response) => { if (!response.ok) { console.error(response.status); this.setState({ loadError: 'An error occurred when loading the form!', }); return; } response.json().then( (data) => this.setState({ Data: data, isLoaded: true, }) ); }).catch((error) => { // Network error console.error(error); this.setState({ loadError: 'An error occurred when loading the form!', }); }); } /** * Called by React when the component has been rendered on the page. */ componentDidMount() { this.fetchData(); } /** * Set file data * @param {string} formElement * @param {*} value */ setFileData(formElement, value) { let numFiles = this.state.numFiles; if (!this.state.formData[formElement]) { numFiles += 1; this.setState({numFiles: numFiles}); } this.setFormData(formElement, value); } /** * Set form data * @param {string} formElement * @param {*} value */ setFormData(formElement, value) { let formData = this.state.formData; formData[formElement] = value; this.setState({ formData: formData, }); } /** * Add list item * @param {string} formElement * @param {*} value * @param {string} pendingValKey */ addListItem(formElement, value, pendingValKey) { let formData = this.state.formData; let listItems = formData[formElement] || []; listItems.push(value); formData[formElement] = listItems; formData[pendingValKey] = null; this.setState({ formData: formData, }); } /** * Remove list item * @param {string} formElement * @param {*} value */ removeListItem(formElement, value) { let formData = this.state.formData; let listItems = formData[formElement]; let index = listItems.indexOf(value); if (index > -1) { listItems.splice(index, 1); formData[formElement] = listItems; this.setState({ formData: formData, }); } } /** * Handle submit * @param {object} e - Event object */ handleSubmit(e) { e.preventDefault(); if (Object.keys(this.state.formErrors).length > 0) { swal.fire( 'Please fix any remaining form errors before submission', '', 'error' ); return; } let formData = this.state.formData; let formObj = new FormData(); for (let key in formData) { if (formData.hasOwnProperty(key) && formData[key] !== '') { let formVal; if (Array.isArray(formData[key])) { formVal = JSON.stringify(formData[key]); } else { formVal = formData[key]; } formObj.append(key, formVal); } } fetch(this.props.action, { method: 'POST', body: formObj, }).then((response) => { if (!response.ok) { console.error(response.status); response.json().then((data) => { let message = (data && data.message) || ''; swal.fire('Something went wrong!', message, 'error'); }); return; } // reset form data this.setState({ formData: {}, numFiles: 0, }); swal.fire( { title: 'Submission Successful!', type: 'success', }).then(function() { window.location.replace(loris.BaseURL + '/publication/'); }); }).catch((error) => { // Network error console.error(error); swal.fire('Something went wrong!', '', 'error'); }); } /** * Renders the React component. * * @return {JSX} - React markup for the component */ render() { // Data loading error if (this.state.loadError !== undefined) { return ( <div className="alert alert-danger text-center"> <strong> {this.state.error} </strong> </div> ); } // Waiting for data to load if (!this.state.isLoaded) { return ( <button className="btn-info has-spinner"> Loading <span className="glyphicon glyphicon-refresh glyphicon-refresh-animate"> </span> </button> ); } let createElements; let formClass = 'col-md-12 col-lg-12'; if (!this.props.editMode) { createElements = ( <div key='propose_new_project'> <h3 className="col-md-offset-3 col-lg-offset-3"> Propose a new project </h3> <TextboxElement name="title" label="Title" onUserInput={this.setFormData} required={true} value={this.state.formData.title} /> </div> ); // if not in edit mode, shrink form for consistent display formClass = 'col-md-8 col-lg-7'; } return ( <div className="row"> <div className={formClass}> <FormElement name="publicationUpload" onSubmit={this.handleSubmit} ref="form" fileUpload={true} > {createElements} <ProjectFormFields formData={this.state.formData} formErrors={this.state.formErrors} numFiles={this.state.numFiles} setFormData={this.setFormData} setFileData={this.setFileData} addListItem={this.addListItem} removeListItem={this.removeListItem} toggleEmailNotify={this.toggleEmailNotify} uploadTypes={this.state.Data.uploadTypes} users={this.state.Data.users} allVOIs={this.state.Data.allVOIs} allKWs={this.state.Data.allKWs} allCollabs={this.state.Data.allCollabs} editMode={false} /> </FormElement> </div> </div> ); } } export default PublicationUploadForm;
ajax/libs/react/0.14.7/react-dom-server.min.js
Amomo/cdnjs
/** * ReactDOMServer v0.14.7 * * 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. * */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e(require("react"));else if("function"==typeof define&&define.amd)define(["react"],e);else{var f;f="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,f.ReactDOMServer=e(f.React)}}(function(e){return e.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED});
ajax/libs/core-js/0.5.4/library.js
melvinsembrano/cdnjs
/** * Core.js 0.5.4 * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2015 Denis Pushkarev */ !function(global, framework, undefined){ 'use strict'; /****************************************************************************** * Module : common * ******************************************************************************/ // Shortcuts for [[Class]] & property names 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' // Aliases global objects and prototypes , 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 , ArrayProto = Array[PROTOTYPE] , ObjectProto = Object[PROTOTYPE] , FunctionProto = Function[PROTOTYPE] , Infinity = 1 / 0 , DOT = '.' // Methods from https://github.com/DeveloperToolsWG/console-object/blob/master/api.md , CONSOLE_METHODS = 'assert,clear,count,debug,dir,dirxml,error,exception,' + 'group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,' + 'markTimeline,profile,profileEnd,table,time,timeEnd,timeline,' + 'timelineEnd,timeStamp,trace,warn'; // http://jsperf.com/core-js-isobject function isObject(it){ return it !== null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } // Native function? var isNative = ctx(/./.test, /\[native code\]\s*\}\s*$/, 1); // Object internal [[Class]] or toStringTag // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring 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); } // Function var call = FunctionProto.call , apply = FunctionProto.apply , REFERENCE_GET; // Partial apply function part(/* ...args */){ 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(/* ...args */){ 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); } } // Optional / simple context binding 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(/* ...args */){ return fn.apply(that, arguments); } } // Fast apply // http://jsperf.lnkit.com/fast-apply/5 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); } function construct(target, argumentsList /*, newTarget*/){ 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; } // Object: 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) // Dummy, fix for not array-like ES3 string in es5 module , 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); } // 19.1.2.1 Object.assign(target, source, ...) 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; } // Array // array('str1,str2,str3') => ['str1', 'str2', 'str3'] 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]; /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findIndex */ 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/*, that = undefined */){ 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; // 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(isEvery)return false; // every } } return isFindIndex ? -1 : isSome || isEvery ? isEvery : result; } } function createArrayContains(isContains){ return function(el /*, fromIndex = 0 */){ 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){ // strange IE quirks mode bug -> use typeof vs isFunction return typeof A == 'function' ? A : B; } // Math var MAX_SAFE_INTEGER = 0x1fffffffffffff // pow(2, 53) - 1 == 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); } // 20.1.2.4 Number.isNaN(number) function sameNaN(number){ return number != number; } // 7.1.4 ToInteger function toInteger(it){ return isNaN(it) ? 0 : trunc(it); } // 7.1.15 ToLength 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 < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? toString ? s.charAt(i) : a : toString ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; } } // Assertion & errors 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!"); } // Property descriptors & Symbol 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); } // 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){} }() , 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_SPECIES = getWellKnownSymbol('species'); function setSpecies(C){ if(framework || !isNative(C))defineProperty(C, SYMBOL_SPECIES, { configurable: true, get: returnThis }); } // Iterators var SYMBOL_ITERATOR = getWellKnownSymbol(ITERATOR) , SYMBOL_TAG = getWellKnownSymbol(TO_STRING_TAG) , SUPPORT_FF_ITER = FF_ITERATOR in ArrayProto , ITER = safeSymbol('iter') , KEY = 1 , VALUE = 2 , Iterators = {} , IteratorPrototype = {} , NATIVE_ITERATORS = SYMBOL_ITERATOR in ArrayProto // Safari define byggy iterators w/o `next` , BUGGY_ITERATORS = 'keys' in ArrayProto && !('next' in [].keys()); // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, returnThis); function setIterator(O, value){ hidden(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol SUPPORT_FF_ITER && 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){ // Define iterator setIterator(proto, iter); if(iter !== value){ var iterProto = getPrototypeOf(iter.call(new Constructor)); // Set @@toStringTag to native iterators setToStringTag(iterProto, NAME + ' Iterator', true); // FF fix has(proto, FF_ITERATOR) && setIterator(iterProto, returnThis); } } // Plug for library Iterators[NAME] = iter; // FF & v8 fix 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 forOf(iterable, entries, fn, that){ var iterator = getIterator(iterable) , f = ctx(fn, that, entries ? 2 : 1) , step; while(!(step = iterator.next()).done)if(stepCall(f, step.value, entries) === false)return; } // core var NODE = cof(process) == PROCESS , core = {} , path = framework ? global : core , old = global.core , exportGlobal // type bitmap , FORCED = 1 , GLOBAL = 2 , STATIC = 4 , PROTO = 8 , BIND = 16 , WRAP = 32 , SIMPLE = 64; 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){ // there is a similar native own = !(type & FORCED) && target && key in target && (!isFunction(target[key]) || isNative(target[key])); // export native or passed out = (own ? target : source)[key]; // prevent global pollution for namespaces if(!framework && isGlobal && !isFunction(target[key]))exp = source[key]; // bind timers to global for call from export context else if(type & BIND && own)exp = ctx(out, global); // wrap global constructors for prevent change them in library 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; // extend global if(framework && target && !own){ if(isGlobal || type & SIMPLE)target[key] = out; else delete target[key] && hidden(target, key, out); } // export if(exports[key] != out)hidden(exports, key, exp); } } // CommonJS export if(typeof module != 'undefined' && module.exports)module.exports = core; // RequireJS export else if(isFunction(define) && define.amd)define(function(){return core}); // Export to global object else exportGlobal = true; if(exportGlobal || framework){ core.noConflict = function(){ global.core = old; return core; } global.core = core; } /****************************************************************************** * Module : es5 * ******************************************************************************/ // ECMAScript 5 shim !function(IS_ENUMERABLE, Empty, _classof, $PROTO){ if(!DESC){ getOwnDescriptor = function(O, P){ if(has(O, P))return descriptor(!ObjectProto[IS_ENUMERABLE].call(O, P), O[P]); }; defineProperty = function(O, P, Attributes){ if('value' in Attributes)assertObject(O)[P] = Attributes.value; return O; }; defineProperties = function(O, Properties){ assertObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P, Attributes; while(length > i){ P = keys[i++]; Attributes = Properties[P]; if('value' in Attributes)O[P] = Attributes.value; } return O; }; } $define(STATIC + FORCED * !DESC, OBJECT, { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: getOwnDescriptor, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: defineProperty, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = [CONSTRUCTOR, HAS_OWN, 'isPrototypeOf', IS_ENUMERABLE, TO_LOCALE, TO_STRING, 'valueOf'] // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', PROTOTYPE) , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype function createDict(){ // Thrash, waste and sodomy: IE GC bug var iframe = document[CREATE_ELEMENT]('iframe') , i = keysLen1 , iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); iframe.src = 'javascript:'; // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script>'); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][keys1[i]]; return createDict(); } function createGetKeys(names, length, isNames){ return function(object){ var O = toObject(object) , i = 0 , result = [] , key; for(key in O)if(key != $PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~indexOf.call(result, key) || result.push(key); } return result; } } function isPrimitive(it){ return !isObject(it) } $define(STATIC, OBJECT, { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: getPrototypeOf = getPrototypeOf || function(O){ O = Object(assertDefined(O)); if(has(O, $PROTO))return O[$PROTO]; if(isFunction(O[CONSTRUCTOR]) && O instanceof O[CONSTRUCTOR]){ return O[CONSTRUCTOR][PROTOTYPE]; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: getNames = getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: create = create || function(O, /*?*/Properties){ var result if(O !== null){ Empty[PROTOTYPE] = assertObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf shim result[$PROTO] = O; } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: getKeys = getKeys || createGetKeys(keys1, keysLen1, false), // 19.1.2.17 / 15.2.3.8 Object.seal(O) seal: returnIt, // <- cap // 19.1.2.5 / 15.2.3.9 Object.freeze(O) freeze: returnIt, // <- cap // 19.1.2.15 / 15.2.3.10 Object.preventExtensions(O) preventExtensions: returnIt, // <- cap // 19.1.2.13 / 15.2.3.11 Object.isSealed(O) isSealed: isPrimitive, // <- cap // 19.1.2.12 / 15.2.3.12 Object.isFrozen(O) isFrozen: isFrozen = isFrozen || isPrimitive, // <- cap // 19.1.2.11 / 15.2.3.13 Object.isExtensible(O) isExtensible: isObject // <- cap }); // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $define(PROTO, FUNCTION, { bind: function(that /*, args... */){ var fn = assertFunction(this) , partArgs = slice.call(arguments, 1); function bound(/* args... */){ var args = partArgs.concat(slice.call(arguments)); return this instanceof bound ? construct(fn, args) : invoke(fn, args, that); } return bound; } }); // Fix for not array-like ES3 string function arrayMethodFix(fn){ return function(){ return fn.apply(ES5Object(this), arguments); } } if(!(0 in Object(DOT) && DOT[0] == DOT)){ ES5Object = function(it){ return cof(it) == STRING ? it.split('') : Object(it); } slice = arrayMethodFix(slice); } $define(PROTO + FORCED * (ES5Object != Object), ARRAY, { slice: slice, join: arrayMethodFix(ArrayProto.join) }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $define(STATIC, ARRAY, { isArray: function(arg){ return cof(arg) == ARRAY } }); function createArrayReduce(isRight){ return function(callbackfn, memo){ assertFunction(callbackfn); var O = toObject(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(2 > arguments.length)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; assert(isRight ? index >= 0 : length > index, REDUCE_ERROR); } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; } } $define(PROTO, ARRAY, { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: forEach = forEach || createArrayMethod(0), // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: createArrayMethod(1), // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: createArrayMethod(2), // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: createArrayMethod(3), // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: createArrayMethod(4), // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: indexOf = indexOf || createArrayContains(false), // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = toObject(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = min(index, toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 21.1.3.25 / 15.5.4.20 String.prototype.trim() $define(PROTO, STRING, {trim: createReplacer(/^\s*([\s\S]*\S)?\s*$/, '$1')}); // 20.3.3.1 / 15.9.4.4 Date.now() $define(STATIC, DATE, {now: function(){ return +new Date; }}); // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() $define(PROTO, DATE, {toISOString: function(){ if(!isFinite(this))throw RangeError('Invalid time value'); var d = this , y = d.getUTCFullYear() , m = d.getUTCMilliseconds() , s = y < 0 ? '-' : y > 9999 ? '+' : ''; return s + ('00000' + 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'; }}); if(_classof(function(){return arguments}()) == OBJECT)classof = function(it){ var cof = _classof(it); return cof == OBJECT && isFunction(it.callee) ? ARGUMENTS : cof; } }('propertyIsEnumerable', function(){}, classof, safeSymbol(PROTOTYPE)); /****************************************************************************** * Module : es6.symbol * ******************************************************************************/ // ECMAScript 6 symbols shim !function(TAG, SymbolRegistry, AllSymbols, setter){ // 19.4.1.1 Symbol([description]) 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 = { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = Symbol(key); }, // 19.4.2.4 Symbol.iterator iterator: SYMBOL_ITERATOR, // 19.4.2.5 Symbol.keyFor(sym) keyFor: part.call(keyOf, SymbolRegistry), // 19.4.2.10 Symbol.species species: SYMBOL_SPECIES, // 19.4.2.13 Symbol.toStringTag toStringTag: SYMBOL_TAG = getWellKnownSymbol(TO_STRING_TAG, true), // 19.4.2.14 Symbol.unscopables unscopables: SYMBOL_UNSCOPABLES, pure: safeSymbol, set: set, useSetter: function(){setter = true}, useSimple: function(){setter = false} }; // 19.4.2.2 Symbol.hasInstance // 19.4.2.3 Symbol.isConcatSpreadable // 19.4.2.6 Symbol.match // 19.4.2.8 Symbol.replace // 19.4.2.9 Symbol.search // 19.4.2.11 Symbol.split // 19.4.2.12 Symbol.toPrimitive 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, { // 19.1.2.7 Object.getOwnPropertyNames(O) 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; }, // 19.1.2.8 Object.getOwnPropertySymbols(O) 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; } }); }(safeSymbol('tag'), {}, {}, true); /****************************************************************************** * Module : es6.object * ******************************************************************************/ !function(tmp){ var objectStatic = { // 19.1.3.1 Object.assign(target, source) assign: assign, // 19.1.3.10 Object.is(value1, value2) is: function(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; } }; // 19.1.3.19 Object.setPrototypeOf(O, proto) // Works with __proto__ only. Old v8 can't works with null proto objects. '__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); if(framework){ // 19.1.3.6 Object.prototype.toString() tmp[SYMBOL_TAG] = DOT; if(cof(tmp) != DOT)hidden(ObjectProto, TO_STRING, function(){ return '[object ' + classof(this) + ']'; }); } // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, MATH, true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); }({}); /****************************************************************************** * Module : es6.object.statics-accept-primitives * ******************************************************************************/ !function(){ // Object static methods accept primitives 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'); }(); /****************************************************************************** * Module : es6.number * ******************************************************************************/ !function(isInteger){ $define(STATIC, NUMBER, { // 20.1.2.1 Number.EPSILON EPSILON: pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function(it){ return typeof it == 'number' && isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: sameNaN, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); // 20.1.2.3 Number.isInteger(number) }(Number.isInteger || function(it){ return !isObject(it) && isFinite(it) && floor(it) === it; }); /****************************************************************************** * Module : es6.math * ******************************************************************************/ // ECMAScript 6 shim !function(){ // 20.2.2.28 Math.sign(x) 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; }; // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } // 20.2.2.14 Math.expm1(x) function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1; } $define(STATIC, MATH, { // 20.2.2.3 Math.acosh(x) acosh: function(x){ return (x = +x) < 1 ? NaN : isFinite(x) ? log(x / E + sqrt(x + 1) * sqrt(x - 1) / E) + 1 : x; }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function(x){ return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function(x){ return sign(x = +x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32(x) clz32: function(x){ return (x >>>= 0) ? 32 - x[TO_STRING](2).length : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function(x){ return (exp(x = +x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: expm1, // 20.2.2.16 Math.fround(x) // TODO: fallback for IE9- fround: function(x){ return new Float32Array([x])[0]; }, // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) 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); }, // 20.2.2.18 Math.imul(x, y) imul: function(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); }, // 20.2.2.20 Math.log1p(x) log1p: function(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x); }, // 20.2.2.21 Math.log10(x) log10: function(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function(x){ return (abs(x = +x) < 1) ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2); }, // 20.2.2.33 Math.tanh(x) tanh: function(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); }, // 20.2.2.34 Math.trunc(x) trunc: trunc }); }(); /****************************************************************************** * Module : es6.string * ******************************************************************************/ !function(fromCharCode){ function assertNotRegExp(it){ if(cof(it) == REGEXP)throw TypeError(); } $define(STATIC, STRING, { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function(x){ var res = [] , len = arguments.length , i = 0 , code while(len > 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(''); }, // 21.1.2.4 String.raw(callSite, ...substitutions) 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, { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: createPointAt(false), // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) endsWith: function(searchString /*, endPosition = @length */){ 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; }, // 21.1.3.7 String.prototype.includes(searchString, position = 0) includes: function(searchString /*, position = 0 */){ assertNotRegExp(searchString); return !!~String(assertDefined(this)).indexOf(searchString, arguments[1]); }, // 21.1.3.13 String.prototype.repeat(count) 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; }, // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function(searchString /*, position = 0 */){ 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); /****************************************************************************** * Module : es6.array * ******************************************************************************/ !function(){ $define(STATIC, ARRAY, { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = Object(assertDefined(arrayLike)) , mapfn = arguments[1] , mapping = mapfn !== undefined , f = mapping ? ctx(mapfn, arguments[2], 2) : undefined , index = 0 , length, result, iter, step; if(isIterable(O))for(iter = getIterator(O), result = new (generic(this, Array)); !(step = iter.next()).done; index++){ result[index] = mapping ? f(step.value, index) : step.value; } else for(result = new (generic(this, Array))(length = toLength(O.length)); length > index; index++){ result[index] = mapping ? f(O[index], index) : O[index]; } result.length = index; return result; }, // 22.1.2.3 Array.of( ...items) of: function(/* ...args */){ var index = 0 , length = arguments.length , result = new (generic(this, Array))(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); $define(PROTO, ARRAY, { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) copyWithin: function(target /* = 0 */, start /* = 0, end = @length */){ 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; }, // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function(value /*, start = 0, end = @length */){ 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; }, // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) find: createArrayMethod(5), // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) findIndex: createArrayMethod(6) }); if(framework){ // 22.1.3.31 Array.prototype[@@unscopables] forEach.call(array('find,findIndex,fill,copyWithin,entries,keys,values'), function(it){ ArrayUnscopables[it] = true; }); SYMBOL_UNSCOPABLES in ArrayProto || hidden(ArrayProto, SYMBOL_UNSCOPABLES, ArrayUnscopables); } setSpecies(Array); }(); /****************************************************************************** * Module : es6.iterators * ******************************************************************************/ !function(at){ // 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]() defineStdIterators(Array, ARRAY, function(iterated, kind){ set(this, ITER, {o: toObject(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, 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); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators[ARGUMENTS] = Iterators[ARRAY]; // 21.1.3.27 String.prototype[@@iterator]() defineStdIterators(String, STRING, function(iterated){ set(this, ITER, {o: String(iterated), i: 0}); // 21.1.5.2.1 %StringIteratorPrototype%.next() }, 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)); /****************************************************************************** * Module : web.immediate * ******************************************************************************/ // setImmediate shim // Node.js 0.9+ & IE10+ has setImmediate, else: 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); } // Node.js 0.8- if(NODE){ defer = function(id){ nextTick(part.call(run, id)); } // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(addEventListener && isFunction(postMessage) && !global.importScripts){ defer = function(id){ postMessage(id, '*'); } addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // IE8- } 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); } } // Rest old browsers } else { defer = function(id){ setTimeout(run, 0, id); } } }('onreadystatechange'); $define(GLOBAL + BIND, { setImmediate: setImmediate, clearImmediate: clearImmediate }); /****************************************************************************** * Module : es6.promise * ******************************************************************************/ // ES6 promises shim // Based on https://github.com/getify/native-promise-only/ !function(Promise, test){ isFunction(Promise) && isFunction(Promise.resolve) && Promise.resolve(test = new Promise(function(){})) == test || function(asap, DEF){ function isThenable(o){ var then; if(isObject(o))then = o.then; return isFunction(then) ? then : false; } function notify(def){ var chain = def.chain; chain.length && asap(function(){ var msg = def.msg , ok = def.state == 1 , i = 0; while(chain.length > i)!function(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ ret = cb === true ? msg : cb(msg); 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(msg); } catch(err){ react.rej(err); } }(chain[i++]); chain.length = 0; }); } function resolve(msg){ var def = this , then, wrapper; if(def.done)return; def.done = true; def = def.def || def; // unwrap try { if(then = isThenable(msg)){ wrapper = {def: def, done: false}; // wrap then.call(msg, ctx(resolve, wrapper, 1), ctx(reject, wrapper, 1)); } else { def.msg = msg; def.state = 1; notify(def); } } catch(err){ reject.call(wrapper || {def: def, done: false}, err); // wrap } } function reject(msg){ var def = this; if(def.done)return; def.done = true; def = def.def || def; // unwrap def.msg = msg; def.state = 2; notify(def); } function getConstructor(C){ var S = assertObject(C)[SYMBOL_SPECIES]; return S != undefined ? S : C; } // 25.4.3.1 Promise(executor) Promise = function(executor){ assertFunction(executor); assertInstance(this, Promise, PROMISE); var def = {chain: [], state: 0, done: false, msg: undefined}; hidden(this, DEF, def); try { executor(ctx(resolve, def, 1), ctx(reject, def, 1)); } catch(err){ reject.call(def, err); } } assignHidden(Promise[PROTOTYPE], { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) 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); }), def = this[DEF]; def.chain.push(react); def.state && notify(def); return P; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); assignHidden(Promise, { // 25.4.4.1 Promise.all(iterable) 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); }); }, // 25.4.4.4 Promise.race(iterable) race: function(iterable){ var Promise = getConstructor(this); return new Promise(function(resolve, reject){ forOf(iterable, false, function(promise){ Promise.resolve(promise).then(resolve, reject); }); }); }, // 25.4.4.5 Promise.reject(r) reject: function(r){ return new (getConstructor(this))(function(resolve, reject){ reject(r); }); }, // 25.4.4.6 Promise.resolve(x) resolve: function(x){ return isObject(x) && DEF in x && getPrototypeOf(x) === this[PROTOTYPE] ? x : new (getConstructor(this))(function(resolve, reject){ resolve(x); }); } }); }(nextTick || setImmediate, safeSymbol('def')); setToStringTag(Promise, PROMISE); setSpecies(Promise); $define(GLOBAL + FORCED * !isNative(Promise), {Promise: Promise}); }(global[PROMISE]); /****************************************************************************** * Module : es6.collections * ******************************************************************************/ // ECMAScript 6 collections shim !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')))){ // create collection constructor 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 || defineProperty(C[PROTOTYPE], 'size', {get: function(){ return assertDefined(this[SIZE]); }}); } else { var Native = C , inst = new C , chain = inst[ADDER](isWeak ? {} : -0, 1) , buggyZero; // wrap to init collections from iterable if(!NATIVE_ITERATORS || !C.length){ 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; }); // fix converting -0 key to +0 if(buggyZero){ fixSVZ('delete'); fixSVZ('has'); isMap && fixSVZ('get'); } // + fix .add & .set for chaining if(buggyZero || chain !== inst)fixSVZ(ADDER, true); } setToStringTag(C, NAME); setSpecies(C); O[NAME] = C; $define(GLOBAL + WRAP + FORCED * !isNative(C), O); // 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 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; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!iter.o || !(iter.l = entry = entry ? entry.n : iter.o[FIRST])){ // or finish the iteration iter.o = undefined; return iterResult(1); } // return step by kind 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){ // return primitive with prefix if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it; // can't set id to frozen object if(isFrozen(it))return 'F'; if(!has(it, UID)){ // not necessary to add id if(!create)return 'E'; // add missing object id hidden(it, UID, ++uid); // return object id with prefix } return 'O' + it[UID]; } function getEntry(that, key){ // fast case var index = fastKey(key), entry; if(index != 'F')return that[O1][index]; // frozen object case 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; // change existing entry if(entry)entry.v = value; // create new entry else { that[LAST] = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that[LAST], // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that[FIRST])that[FIRST] = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index != 'F')that[O1][index] = entry; } return that; } var collectionMethods = { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() 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; }, // 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[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; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function(callbackfn /*, that = undefined */){ var f = ctx(callbackfn, arguments[1], 3) , entry; while(entry = entry ? entry.n : this[FIRST]){ 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(key){ return !!getEntry(this, key); } } // 23.1 Map Objects Map = getCollection(Map, MAP, { // 23.1.3.6 Map.prototype.get(key) get: function(key){ var entry = getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function(key, value){ return def(this, key === 0 ? 0 : key, value); } }, collectionMethods, true); // 23.2 Set Objects Set = getCollection(Set, SET, { // 23.2.3.1 Set.prototype.add(value) 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 = { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) '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]]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) 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]); } }; // 23.3 WeakMap Objects WeakMap = getCollection(WeakMap, WEAKMAP, { // 23.3.3.3 WeakMap.prototype.get(key) get: function(key){ if(isObject(key)){ if(isFrozen(key))return leakStore(this).get(key); if(has(key, WEAK))return key[WEAK][this[UID]]; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function(key, value){ return defWeak(this, key, value); } }, weakMethods, true, true); // IE11 WeakMap frozen keys fix 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){ // store frozen objects on leaky map if(isObject(a) && isFrozen(a)){ var result = leakStore(this)[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }; }); } // 23.4 WeakSet Objects WeakSet = getCollection(WeakSet, WEAKSET, { // 23.4.3.1 WeakSet.prototype.add(value) add: function(value){ return defWeak(this, value, true); } }, weakMethods, false, true); }(); /****************************************************************************** * Module : es6.reflect * ******************************************************************************/ !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/*, receiver*/){ 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/*, receiver*/){ 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 = { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) apply: ctx(call, apply, 3), // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) construct: construct, // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) defineProperty: wrap(defineProperty), // 26.1.4 Reflect.deleteProperty(target, propertyKey) deleteProperty: function(target, propertyKey){ var desc = getOwnDescriptor(assertObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; }, // 26.1.5 Reflect.enumerate(target) enumerate: function(target){ return new Enumerate(assertObject(target)); }, // 26.1.6 Reflect.get(target, propertyKey [, receiver]) get: reflectGet, // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) getOwnPropertyDescriptor: function(target, propertyKey){ return getOwnDescriptor(assertObject(target), propertyKey); }, // 26.1.8 Reflect.getPrototypeOf(target) getPrototypeOf: function(target){ return getPrototypeOf(assertObject(target)); }, // 26.1.9 Reflect.has(target, propertyKey) has: function(target, propertyKey){ return propertyKey in target; }, // 26.1.10 Reflect.isExtensible(target) isExtensible: function(target){ return !!isExtensible(assertObject(target)); }, // 26.1.11 Reflect.ownKeys(target) ownKeys: ownKeys, // 26.1.12 Reflect.preventExtensions(target) preventExtensions: wrap(Object.preventExtensions || returnIt), // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) set: reflectSet } // 26.1.14 Reflect.setPrototypeOf(target, proto) if(setPrototypeOf)reflect.setPrototypeOf = function(target, proto){ return setPrototypeOf(assertObject(target), proto), true; }; $define(GLOBAL, {Reflect: {}}); $define(STATIC, 'Reflect', reflect); }(); /****************************************************************************** * Module : es7.proposals * ******************************************************************************/ !function(){ $define(PROTO, ARRAY, { // https://github.com/domenic/Array.prototype.includes includes: createArrayContains(true) }); $define(PROTO, STRING, { // https://github.com/mathiasbynens/String.prototype.at 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, { // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-04/apr-9.md#51-objectentries-objectvalues values: createObjectToArray(false), entries: createObjectToArray(true) }); $define(STATIC, REGEXP, { // https://gist.github.com/kangax/9698100 escape: createReplacer(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true) }); }(); /****************************************************************************** * Module : es7.abstract-refs * ******************************************************************************/ // https://github.com/zenparsing/es-abstract-refs !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'); /****************************************************************************** * Module : core.dict * ******************************************************************************/ !function(DICT){ Dict = function(iterable){ var dict = create(null); if(iterable != undefined){ if(isIterable(iterable)){ for(var iter = getIterator(iterable), step, value; !(step = iter.next()).done;){ value = step.value; dict[value[0]] = value[1]; } } else assign(dict, iterable); } return dict; } Dict[PROTOTYPE] = null; function DictIterator(iterated, kind){ set(this, ITER, {o: toObject(iterated), a: getKeys(iterated), i: 0, k: kind}); } createIterator(DictIterator, DICT, function(){ var iter = this[ITER] , O = iter.o , keys = iter.a , kind = iter.k , key; do { if(iter.i >= keys.length){ iter.o = undefined; return iterResult(1); } } while(!has(O, key = keys[iter.i++])); if(kind == KEY) return iterResult(0, key); if(kind == VALUE)return iterResult(0, O[key]); return iterResult(0, [key, O[key]]); }); function createDictIter(kind){ return function(it){ return new DictIterator(it, kind); } } /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findKey * 7 -> mapPairs */ function createDictMethod(type){ var isMap = type == 1 , isEvery = type == 4; return function(object, callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = toObject(object) , result = isMap || type == 7 || type == 2 ? new (generic(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(isMap)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(isEvery)return false; // every } } return type == 3 || isEvery ? isEvery : result; } } function createDictReduce(isTurn){ return function(object, mapfn, init){ assertFunction(mapfn); var O = toObject(object) , keys = getKeys(O) , length = keys.length , i = 0 , memo, key, result; if(isTurn)memo = init == undefined ? new (generic(this, Dict)) : Object(init); else if(arguments.length < 3){ assert(length, REDUCE_ERROR); memo = O[keys[i++]]; } else memo = Object(init); while(length > i)if(has(O, key = keys[i++])){ result = mapfn(memo, O[key], key, object); if(isTurn){ if(result === false)break; } else memo = result; } return memo; } } var findKey = createDictMethod(6); function includes(object, el){ return (el == el ? keyOf(object, el) : findKey(object, sameNaN)) !== undefined; } var dictMethods = { keys: createDictIter(KEY), values: createDictIter(VALUE), entries: createDictIter(KEY+VALUE), forEach: createDictMethod(0), map: createDictMethod(1), filter: createDictMethod(2), some: createDictMethod(3), every: createDictMethod(4), find: createDictMethod(5), findKey: findKey, mapPairs:createDictMethod(7), reduce: createDictReduce(false), turn: createDictReduce(true), keyOf: keyOf, includes:includes, // Has / get / set own property has: has, get: get, set: createDefiner(0), isDict: function(it){ return isObject(it) && getPrototypeOf(it) === Dict[PROTOTYPE]; } }; if(REFERENCE_GET)for(var key in dictMethods)!function(fn){ function method(){ for(var args = [this], i = 0; i < arguments.length;)args.push(arguments[i++]); return invoke(fn, args); } fn[REFERENCE_GET] = function(){ return method; } }(dictMethods[key]); $define(GLOBAL + FORCED, {Dict: assignHidden(Dict, dictMethods)}); }('Dict'); /****************************************************************************** * Module : core.$for * ******************************************************************************/ !function(ENTRIES, FN){ function $for(iterable, entries){ if(!(this instanceof $for))return new $for(iterable, entries); this[ITER] = getIterator(iterable); this[ENTRIES] = !!entries; } createIterator($for, 'Wrapper', function(){ return this[ITER].next(); }); var $forProto = $for[PROTOTYPE]; setIterator($forProto, function(){ return this[ITER]; // unwrap }); function createChainIterator(next){ function Iter(I, fn, that){ this[ITER] = getIterator(I); this[ENTRIES] = I[ENTRIES]; this[FN] = ctx(fn, that, I[ENTRIES] ? 2 : 1); } createIterator(Iter, 'Chain', next, $forProto); setIterator(Iter[PROTOTYPE], returnThis); // override $forProto iterator return Iter; } var MapIter = createChainIterator(function(){ var step = this[ITER].next(); return step.done ? step : iterResult(0, stepCall(this[FN], step.value, this[ENTRIES])); }); var FilterIter = createChainIterator(function(){ for(;;){ var step = this[ITER].next(); if(step.done || stepCall(this[FN], step.value, this[ENTRIES]))return step; } }); assignHidden($forProto, { of: function(fn, that){ forOf(this, this[ENTRIES], fn, that); }, array: function(fn, that){ var result = []; forOf(fn != undefined ? this.map(fn, that) : this, false, push, result); return result; }, filter: function(fn, that){ return new FilterIter(this, fn, that); }, map: function(fn, that){ return new MapIter(this, fn, that); } }); $for.isIterable = isIterable; $for.getIterator = getIterator; $define(GLOBAL + FORCED, {$for: $for}); }('entries', safeSymbol('fn')); /****************************************************************************** * Module : core.delay * ******************************************************************************/ // https://esdiscuss.org/topic/promise-returning-delay-function $define(GLOBAL + FORCED, { delay: function(time){ return new Promise(function(resolve){ setTimeout(resolve, time, true); }); } }); /****************************************************************************** * Module : core.binding * ******************************************************************************/ !function(_, toLocaleString){ // Placeholder core._ = path._ = path._ || {}; $define(PROTO + FORCED, FUNCTION, { part: part, only: function(numberArguments, that /* = @ */){ var fn = assertFunction(this) , n = toLength(numberArguments) , isThat = arguments.length > 1; return function(/* ...args */){ var length = min(n, arguments.length) , args = Array(length) , i = 0; while(length > i)args[i] = arguments[i++]; return invoke(fn, args, isThat ? that : this); } } }); function tie(key){ var that = this , bound = {}; return hidden(that, _, function(key){ if(key === undefined || !(key in that))return toLocaleString.call(that); return has(bound, key) ? bound[key] : (bound[key] = ctx(that[key], that, -1)); })[_](key); } hidden(path._, TO_STRING, function(){ return _; }); hidden(ObjectProto, _, tie); DESC || hidden(ArrayProto, _, tie); // IE8- dirty hack - redefined toLocaleString is not enumerable }(DESC ? uid('tie') : TO_LOCALE, ObjectProto[TO_LOCALE]); /****************************************************************************** * Module : core.object * ******************************************************************************/ !function(){ function define(target, mixin){ var keys = ownKeys(toObject(mixin)) , length = keys.length , i = 0, key; while(length > i)defineProperty(target, key = keys[i++], getOwnDescriptor(mixin, key)); return target; }; $define(STATIC + FORCED, OBJECT, { isObject: isObject, classof: classof, define: define, make: function(proto, mixin){ return define(create(proto), mixin); } }); }(); /****************************************************************************** * Module : core.array * ******************************************************************************/ $define(PROTO + FORCED, ARRAY, { turn: function(fn, target /* = [] */){ assertFunction(fn); var memo = target == undefined ? [] : Object(target) , O = ES5Object(this) , length = toLength(O.length) , index = 0; while(length > index)if(fn(memo, O[index], index++, this) === false)break; return memo; } }); if(framework)ArrayUnscopables.turn = true; /****************************************************************************** * Module : core.number * ******************************************************************************/ !function(numberMethods){ function NumberIterator(iterated){ set(this, ITER, {l: toLength(iterated), i: 0}); } createIterator(NumberIterator, NUMBER, function(){ var iter = this[ITER] , i = iter.i++; return i < iter.l ? iterResult(0, i) : iterResult(1); }); defineIterator(Number, NUMBER, function(){ return new NumberIterator(this); }); numberMethods.random = function(lim /* = 0 */){ var a = +this , b = lim == undefined ? 0 : +lim , m = min(a, b); return random() * (max(a, b) - m) + m; }; forEach.call(array( // ES3: 'round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,' + // ES6: 'acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc' ), function(key){ var fn = Math[key]; if(fn)numberMethods[key] = function(/* ...args */){ // ie9- dont support strict mode & convert `this` to object -> convert it to number var args = [+this] , i = 0; while(arguments.length > i)args.push(arguments[i++]); return invoke(fn, args); } } ); $define(PROTO + FORCED, NUMBER, numberMethods); }({}); /****************************************************************************** * Module : core.string * ******************************************************************************/ !function(){ var escapeHTMLDict = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }, unescapeHTMLDict = {}, key; for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]] = key; $define(PROTO + FORCED, STRING, { escapeHTML: createReplacer(/[&<>"']/g, escapeHTMLDict), unescapeHTML: createReplacer(/&(?:amp|lt|gt|quot|apos);/g, unescapeHTMLDict) }); }(); /****************************************************************************** * Module : core.date * ******************************************************************************/ !function(formatRegExp, flexioRegExp, locales, current, SECONDS, MINUTES, HOURS, MONTH, YEAR){ function createFormat(prefix){ return function(template, locale /* = current */){ var that = this , dict = locales[has(locales, locale) ? locale : current]; function get(unit){ return that[prefix + unit](); } return String(template).replace(formatRegExp, function(part){ switch(part){ case 's' : return get(SECONDS); // Seconds : 0-59 case 'ss' : return lz(get(SECONDS)); // Seconds : 00-59 case 'm' : return get(MINUTES); // Minutes : 0-59 case 'mm' : return lz(get(MINUTES)); // Minutes : 00-59 case 'h' : return get(HOURS); // Hours : 0-23 case 'hh' : return lz(get(HOURS)); // Hours : 00-23 case 'D' : return get(DATE); // Date : 1-31 case 'DD' : return lz(get(DATE)); // Date : 01-31 case 'W' : return dict[0][get('Day')]; // Day : Понедельник case 'N' : return get(MONTH) + 1; // Month : 1-12 case 'NN' : return lz(get(MONTH) + 1); // Month : 01-12 case 'M' : return dict[2][get(MONTH)]; // Month : Январь case 'MM' : return dict[1][get(MONTH)]; // Month : Января case 'Y' : return get(YEAR); // Year : 2014 case 'YY' : return lz(get(YEAR) % 100); // Year : 14 } return part; }); } } function addLocale(lang, locale){ function split(index){ var result = []; forEach.call(array(locale.months), function(it){ result.push(it.replace(flexioRegExp, '$' + index)); }); return result; } locales[lang] = [array(locale.weekdays), split(1), split(2)]; return core; } $define(PROTO + FORCED, DATE, { format: createFormat('get'), formatUTC: createFormat('getUTC') }); addLocale(current, { weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday', months: 'January,February,March,April,May,June,July,August,September,October,November,December' }); addLocale('ru', { weekdays: 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота', months: 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,' + 'Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь' }); core.locale = function(locale){ return has(locales, locale) ? current = locale : current; }; core.addLocale = addLocale; }(/\b\w\w?\b/g, /:(.*)\|(.*)$/, {}, 'en', 'Seconds', 'Minutes', 'Hours', 'Month', 'FullYear'); /****************************************************************************** * Module : core.global * ******************************************************************************/ $define(GLOBAL + FORCED, {global: global}); /****************************************************************************** * Module : js.array.statics * ******************************************************************************/ // JavaScript 1.6 / Strawman array statics shim !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); }({}); /****************************************************************************** * Module : web.dom.itarable * ******************************************************************************/ !function(NodeList){ if(framework && NodeList && !(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){ hidden(NodeList[PROTOTYPE], SYMBOL_ITERATOR, Iterators[ARRAY]); } Iterators.NodeList = Iterators[ARRAY]; }(global.NodeList); /****************************************************************************** * Module : web.timers * ******************************************************************************/ // ie9- setTimeout & setInterval additional parameters fix !function(MSIE){ function wrap(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke(part, slice.call(arguments, 2), isFunction(fn) ? fn : Function(fn)), time); } : set; } $define(GLOBAL + BIND + FORCED * MSIE, { setTimeout: setTimeout = wrap(setTimeout), setInterval: wrap(setInterval) }); // ie9- dirty check }(!!navigator && /MSIE .\./.test(navigator.userAgent)); /****************************************************************************** * Module : core.log * ******************************************************************************/ !function(log, console, enabled){ forEach.call(array(CONSOLE_METHODS), function(key){ log[key] = function(){ if(enabled && key in console)return apply.call(console[key], console, arguments); }; }); $define(GLOBAL + FORCED, {log: assign(log.log, log, { enable: function(){ enabled = true; }, disable: function(){ enabled = false; } })}); }({}, global.console || {}, true); }(typeof self != 'undefined' && self.Math === Math ? self : Function('return this')(), false);
src/components/Main.js
helloworldzxy/gallery-by-react
require('normalize.css/normalize.css'); require('../css/App.css'); import React from 'react'; import ReactDOM from 'react-dom'; //获取图片相关数据 var imageDatas = require('../data/imageDatas.json'); //只执行一次的函数适用这种自执行函数(即时函数)的写法 imageDatas = (function genImageURL(imageDatasArr){ for(var i = 0, len = imageDatasArr.length; i < len; i++){ var singleImageData = imageDatasArr[i]; singleImageData.imageURL = require('../images/' + singleImageData.fileName); imageDatasArr[i] = singleImageData; } return imageDatasArr; })(imageDatas); //获取区间内的随机值 function getRangeRandom(low, high){ return Math.floor(Math.random() * (high - low) + low); } //获取0-30°之间的任意正负值 function get30DegRandom(){ return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30)); } var ImgFigure = React.createClass({ /* * imgFigure的点击处理函数 * */ handleClick: function(e){ if(this.props.arrange.isCenter){ this.props.inverse(); }else{ this.props.center(); } e.stopPropagation(); e.preventDefault(); }, render: function(){ var styleObj = {}; //如果props属性中指定了这张图片的位置,则使用 if(this.props.arrange.pos){ styleObj = this.props.arrange.pos; } //如果图片的旋转角度有值并且不为0, 添加旋转角度 if(this.props.arrange.rotate){ (['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach(function(value){ styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)'; }.bind(this)); } if(this.props.arrange.isCenter){ styleObj.zIndex = 11; } var imgFigureClassName = 'img-figure'; imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : ''; return( <figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}> <img src={this.props.data.imageURL} alt={this.props.data.title}/> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" onClick={this.handleClick}> <p> {this.props.data.desc} </p> </div> </figcaption> </figure> ); } }); //控制组件 var ControllerUnit = React.createClass({ handleClick: function(e){ //如果点击的是当前正在选中态的按钮,则翻转图片;否则将对应的图片居中 if(this.props.arrange.isCenter){ this.props.inverse(); }else{ this.props.center(); } e.preventDefault(); e.stopPropagation(); }, render: function(){ var controllerUnitClassName = 'controller-unit'; //如果对应的是居中的图片,显示控制按钮的居中态 if(this.props.arrange.isCenter){ controllerUnitClassName += ' is-center'; //如果同时对应的是翻转图片,显示控制按钮的翻转态 if(this.props.arrange.isInverse){ controllerUnitClassName += ' is-inverse'; } } return( <span className={controllerUnitClassName} onClick={this.handleClick}></span> ); } }) //"大管家":负责所有数据及数据的状态切换 var GalleryByReactApp = React.createClass({ //各个位置点(定义时先初始化为0,后面再重新初始化赋值) Constant: { centerPos:{ left: 0, right: 0 }, hPosRange: { //左右分区的取值范围 leftSecX: [0,0], rightSecX: [0,0], y: [0,0] }, vPosRange:{ //上分区的取值范围 x: [0,0], topY: [0,0] } }, /* * 翻转图片 * @params index 输入当前被执行inverse操作的图片对应的图片信息数组的index值 * @return {Function} 这是一个闭包函数,其内return一个真正待被执行的函数 * */ inverse: function(index){ return function(){ var imgsArrangeArr = this.state.imgsArrangeArr; imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse; this.setState({ imgsArrangeArr: imgsArrangeArr }); }.bind(this); }, /* * 重新布局所有图片 * @param centerIndex 指定居中排布哪个图片 * */ rearrange: function(centerIndex){ var imgsArrangeArr = this.state.imgsArrangeArr, Constant = this.Constant, centerPos = Constant.centerPos, hPosRange = Constant.hPosRange, vPosRange = Constant.vPosRange, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecX = hPosRange.rightSecX, hPosRangeY = hPosRange.y, vPosRangeTopY = vPosRange.topY, vPosRangeX = vPosRange.x, imgsArrangeTopArr = [], topImgNum = Math.floor(Math.random() * 2), //取1个或不取 左闭右开 topImgSpliceIndex = 0, //标记上分区的图片是从数组中的哪个位置拿出来的 //取出要布局居中的图片的状态信息 imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1); //splice() 方法可删除从 index 处开始的零个或多个元素,并且用参数列表中声明的一个或多个值来替换那些被删除的元素。 //如果从 arrayObject 中删除了元素,则返回的是含有被删除的元素的数组。 //centerIndex图片 居中,不旋转,在中间 imgsArrangeCenterArr[0] = { pos : centerPos, rotate: 0, isCenter: true }; //取出要布局上侧的图片的状态信息 topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum)); imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum); imgsArrangeTopArr.forEach(function(value, index){ imgsArrangeTopArr[index] = { pos: { top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]), left: getRangeRandom(vPosRangeX[0], vPosRangeX[1]) }, rotate: get30DegRandom(), isCenter: false }; }); //布局左右两侧的图片 for(var i = 0, len = imgsArrangeArr.length, k = len / 2; i < len; i++){ var hPosRangeLORX = null; //前半部分布局左边,后半部分布局右边 if(i < k){ hPosRangeLORX = hPosRangeLeftSecX; }else{ hPosRangeLORX = hPosRangeRightSecX; } imgsArrangeArr[i] = { pos: { top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]), left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]) }, rotate: get30DegRandom(), isCenter: false }; } //将取出的图片信息合并回去 if(imgsArrangeTopArr && imgsArrangeTopArr[0]){ imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]); } imgsArrangeArr.splice(centerIndex, 0 ,imgsArrangeCenterArr[0]); //触发重新渲染 this.setState({ imgsArrangeArr: imgsArrangeArr }); }, /* * 利用rearrange函数 居中对应index的图片 * @param index 需要被居中的图片对应在图片信息数组中的index * */ center: function(index){ return function(){ this.rearrange(index); }.bind(this); }, getInitialState: function(){ return { imgsArrangeArr: [ /*{ pos: { left: '0', top: '0' }, rotate : 0, //旋转角度 isInverse: false, //图片正面 false 反面 true isCenter: false }*/ ] }; }, //组件加载后,为每张图片计算其位置的范围 componentDidMount: function(){ //首先拿到stage大小 var stageDOM = ReactDOM.findDOMNode(this.refs.stage), stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.floor(stageW / 2), halfStageH = Math.floor(stageH / 2); //拿到一个imageFigure的大小 var imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0), imgW = imgFigureDOM.scrollWidth, imgH = imgFigureDOM.scrollHeight, halfImgW = Math.floor(imgW / 2), halfImgH = Math.floor(imgH / 2); //计算中心图片的位置点 this.Constant.centerPos = { left: halfStageW - halfImgW, top: halfStageH - halfImgH }; //计算左 右侧区域图片排布位置的取值范围 this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[1] = stageH - halfImgH; //计算上侧区域图片排布位置的取值范围 this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.Constant.vPosRange.x[0] = halfStageW - imgW; this.Constant.vPosRange.x[1] = halfStageW; this.rearrange(0); }, render: function(){ var controllerUnits = [], imgFigures = []; imageDatas.forEach(function(value, index){ if(!this.state.imgsArrangeArr[index]){ this.state.imgsArrangeArr[index] = { //图片布局信息的初始化工作 pos: { left: 0, top: 0 }, rotate: 0, isInverse: false, //默认正面 isCenter: false }; } imgFigures.push(<ImgFigure data={value} key={index} ref={'imgFigure' + index} arrange={this.state.imgsArrangeArr[index]} inverse = {this.inverse(index)} center={this.center(index)}/>); controllerUnits.push(<ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse = {this.inverse(index)} center={this.center(index)}/>); }.bind(this)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } }); // React.render(<GalleryByReactApp />, document.getElementById('content')); /* GalleryByReactApp.defaultProps = { };*/ export default GalleryByReactApp;
client/src/js/app.js
axcoto/rethink-weekly
import Footer from './footer' import Header from './header' import SubscribeForm from './form/subscribe' import IssueList from './issuelist' import IssueDetail from './issuedetail' import About from './about' import NavMenu from './nav' import React from 'react' import createBrowserHistory from 'history/lib/createBrowserHistory' import { Router, Route, Link, IndexRoute } from 'react-router' import { Button, Checkbox, Container, EmailInputGroup, FileDragAndDrop, FileUpload, Form, FormField, FormIconField, FormInput, FormNote, FormRow, FormSelect, InputGroup, PasswordInputGroup, Radio, RadioGroup, Table, Row } from 'elemental' (function() { const App = React.createClass({ render: function() { return ( <div className="page-wrapper"> <NavMenu /> <div className="page-body"> <Header /> <SubscribeForm /> <Container maxWidth={768} className="demo-container"> {this.props.children} </Container> </div> <Footer /> </div> ) } }) console.log("Thanks for interesting. Help me by buying my book Simply RethinkDB") // Declarative route configuration (could also load this config lazily // instead, all you really need is a single root route, you don't need to // colocate the entire config). // React.render(( // <Router> // <Route path="/" component={App}> // <Route path="about" component={About}/> // <Route path="users" component={Users}> // <Route path="/user/:userId" component={User}/> // </Route> // <Route path="*" component={NoMatch}/> // </Route> // </Router> // ), document.getElementById('app')) // Using https://github.com/rackt/react-router/blob/master/docs/guides/basics/Histories.md#createbrowserhistory // We want browser history for better looking URL instead of hash URL // This is used with the package https://github.com/rackt/history // We are writing our own Go lang server for serving static file. // The server has to be able to handle those link, basiclly whatever URL, we always show index.html file, // unless the /api route or some special route like /stats React.render(( <Router history={createBrowserHistory()}> <Route name="home" path="/" component={App}> <IndexRoute component={IssueList}/> <Route name="issues" path="issues" component={IssueList} /> <Route path="issues/:id" component={IssueDetail} /> <Route name="about" path="about" component={About} /> </Route> </Router> ), document.getElementById('app')) })()