target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
test/reactor/tag-test.js
nodejitsu/godot
/* * tag-test.js: Tests for the Tag reactor stream. * * (C) 2012, Nodejitsu Inc. * */ var assert = require('assert'), vows = require('vows'), range = require('r...e'), windowStream = require('window-stream'), godot = require('../../lib/godot'), helpers = require('../helpers'), macros = require('../macros').reactor; var M1_ALPHA = 1 - Math.exp(-5/60); vows.describe('godot/reactor/tag').addBatch({ "Godot tag": { "with a simple movingAverage": macros.shouldEmitDataSync( godot .reactor() .tag('avg', godot.reactor().movingAverage({ average: 'simple', window: new windowStream.EventWindow({ size: 10 }) })), helpers.timeSeries({ metric: function (num) { return num; } }, 1000, 10), 100, function (all) { all.forEach(function (data, i) { var num = data.metric, di = i + 1, avg, set; set = di < 10 ? range(1, di) : range(di - 9, di); avg = data.tags.filter(function (tag) { return tag.indexOf('avg') !== -1 })[0]; assert.equal(num, di); assert.isString(avg); avg = parseFloat(avg.split(':')[1], 10); assert.equal(avg, godot.math.mean(set.toArray().map(function (n) { return { metric: n }; }))); }); } ) } }).export(module);
docs/src/Root.js
dozoisch/react-bootstrap
import React from 'react'; const Root = React.createClass({ statics: { /** * Get the list of pages that are renderable * * @returns {Array} */ getPages() { return [ 'index.html', 'introduction.html', 'getting-started.html', 'components.html', 'support.html' ]; } }, childContextTypes: { metadata: React.PropTypes.object }, getChildContext() { return {metadata: Root.propData}; }, render() { // Dump out our current props to a global object via a script tag so // when initialising the browser environment we can bootstrap from the // same props as what each page was rendered with. let browserInitScriptObj = { __html: `window.ASSET_BASE_URL = ${JSON.stringify(Root.assetBaseUrl)}; window.PROP_DATA = ${JSON.stringify(Root.propData)}; // console noop shim for IE8/9 (function (w) { var noop = function () {}; if (!w.console) { w.console = {}; ['log', 'info', 'warn', 'error'].forEach(function (method) { w.console[method] = noop; }); } }(window));` }; let head = { __html: `<title>React-Bootstrap</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="${Root.assetBaseUrl}/assets/bundle.css" rel="stylesheet"> <link href="${Root.assetBaseUrl}/assets/favicon.ico?v=2" type="image/x-icon" rel="shortcut icon"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script> <![endif]-->` }; return ( <html> <head dangerouslySetInnerHTML={head} /> <body> {this.props.children} <script dangerouslySetInnerHTML={browserInitScriptObj} /> <script src={`${Root.assetBaseUrl}/assets/bundle.js`} /> </body> </html> ); } }); export default Root;
fixtures/ssr/src/index.js
jquense/react
import React from 'react'; import {render} from 'react-dom'; import App from './components/App'; render(<App assets={window.assetManifest} />, document);
src/icons/ForkRepo.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class ForkRepo extends React.Component { render() { if(this.props.bare) { return <g> <style type="text/css"> .st0{fill:#010101;} </style> <g> <polygon class="st0" points="416,80 368,80 368,32 304,32 304,80 256,80 256,144 304,144 304,192 368,192 368,144 416,144 "></polygon> <path class="st0" d="M304,240c0,38.6-4.5,42.3-14.4,50.3c-7.4,6-22.2,7.1-39.4,8.3c-9.5,0.7-20.4,1.5-31.4,3.3 c-9.4,1.5-18.4,4.7-26.8,8.8V151.4c19.1-11.1,32-31.7,32-55.4c0-35.3-28.7-64-64-64S96,60.7,96,96c0,23.7,12.9,44.3,32,55.4v209.2 c-19.1,11.1-32,31.7-32,55.4c0,35.3,28.7,64,64,64s64-28.7,64-64c0-15.7-5.7-30.1-15-41.2c6.7-4.8,13.9-8.7,20.2-9.7 c8.1-1.3,16.6-1.9,25.6-2.6c24.4-1.7,52.1-3.7,75.2-22.5c30.9-25.1,37.5-52.1,38-94.9l0,0V240H304z M160,64c17.6,0,32,14.4,32,32 s-14.4,32-32,32s-32-14.4-32-32S142.4,64,160,64z M160,448c-17.6,0-32-14.4-32-32s14.4-32,32-32s32,14.4,32,32S177.6,448,160,448z"></path> </g> </g>; } return <IconBase> <style type="text/css"> .st0{fill:#010101;} </style> <g> <polygon class="st0" points="416,80 368,80 368,32 304,32 304,80 256,80 256,144 304,144 304,192 368,192 368,144 416,144 "></polygon> <path class="st0" d="M304,240c0,38.6-4.5,42.3-14.4,50.3c-7.4,6-22.2,7.1-39.4,8.3c-9.5,0.7-20.4,1.5-31.4,3.3 c-9.4,1.5-18.4,4.7-26.8,8.8V151.4c19.1-11.1,32-31.7,32-55.4c0-35.3-28.7-64-64-64S96,60.7,96,96c0,23.7,12.9,44.3,32,55.4v209.2 c-19.1,11.1-32,31.7-32,55.4c0,35.3,28.7,64,64,64s64-28.7,64-64c0-15.7-5.7-30.1-15-41.2c6.7-4.8,13.9-8.7,20.2-9.7 c8.1-1.3,16.6-1.9,25.6-2.6c24.4-1.7,52.1-3.7,75.2-22.5c30.9-25.1,37.5-52.1,38-94.9l0,0V240H304z M160,64c17.6,0,32,14.4,32,32 s-14.4,32-32,32s-32-14.4-32-32S142.4,64,160,64z M160,448c-17.6,0-32-14.4-32-32s14.4-32,32-32s32,14.4,32,32S177.6,448,160,448z"></path> </g> </IconBase>; } };ForkRepo.defaultProps = {bare: false}
docs/app/Examples/views/Feed/Content/FeedExampleExtraText.js
aabustamante/Semantic-UI-React
import React from 'react' import { Feed } from 'semantic-ui-react' const FeedExampleExtraText = () => ( <Feed> <Feed.Event> <Feed.Label image='/assets/images/avatar/small/laura.jpg' /> <Feed.Content> <Feed.Date>3 days ago</Feed.Date> <Feed.Summary> <a>Laura Faucet</a> created a post </Feed.Summary> <Feed.Extra text> Have you seen what's going on in Israel? Can you believe it. </Feed.Extra> </Feed.Content> </Feed.Event> </Feed> ) export default FeedExampleExtraText
files/rxjs/2.3.9/rx.lite.js
spud2451/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = SerialDisposable = Rx.SerialDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var s = state; var id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; }(Scheduler.prototype)); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throw(new Error('Error')); * var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && observer.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; activeCount === 0 && observer.onCompleted(); })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.do(observer); * var res = observable.do(onNext); * var res = observable.do(onNext, onError); * var res = observable.do(onNext, onError, onCompleted); * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (!onError) { observer.onError(err); } else { try { onError(err); } catch (e) { observer.onError(e); } observer.onError(err); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * * @example * var res = source.takeLast(5); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function createListener (element, name, handler) { if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } throw new Error('No listener found'); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs // for proper loading order! var marionette = !!root.Backbone && !!root.Backbone.Marionette; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { if (marionette) { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { if (!subject.isDisposed) { subject.onNext(value); subject.onCompleted(); } }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new Error('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return !selector ? this.multicast(new Subject()) : this.multicast(function () { return new Subject(); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish(null).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return !selector ? this.multicast(new AsyncSubject()) : this.multicast(function () { return new AsyncSubject(); }, selector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue). refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return !selector ? this.multicast(new ReplaySubject(bufferSize, window, scheduler)) : this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, subject.subscribe.bind(subject)); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * * @example * 1 - res = Rx.Observable.timer(new Date()); * 2 - res = Rx.Observable.timer(new Date(), 1000); * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); * * 5 - res = Rx.Observable.timer(5000); * 6 - res = Rx.Observable.timer(5000, 1000); * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * * @example * 1 - res = source.timeout(new Date()); // As a date * 2 - res = source.timeout(5000); // 5 seconds * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { other || (other = observableThrow(new Error('Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); var createTimer = function () { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); }; createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * * @example * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); * * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; var firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false, setTimer = function (timeout) { var myId = id, timerWins = function () { return id === myId; }; var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } d.dispose(); }, function (e) { if (timerWins()) { observer.onError(e); } }, function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } })); }; setTimer(firstTimeout); var observerWins = function () { var res = !switched; if (res) { id++; } return res; }; original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(timeout); } }, function (e) { if (observerWins()) { observer.onError(e); } }, function () { if (observerWins()) { observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); if (hasValue) { observer.onNext(value); } observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * * @example * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { observer.onNext(next.value); } } observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } var PausableBufferedObservable = (function (_super) { inherits(PausableBufferedObservable, _super); function subscribe(observer) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { // change in shouldFire if (results.shouldFire) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } previousShouldFire = results.shouldFire; }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, _super); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { _super.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (_super) { function RemovableDisposable (subject, observer) { this.subject = subject; this.observer = observer; }; RemovableDisposable.prototype.dispose = function () { this.observer.dispose(); if (!this.subject.isDisposed) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); } }; function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = new RemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, _super); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; _super.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /* @private */ _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { var observer; checkDisposed.call(this); if (!this.isStopped) { var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onNext(value); observer.ensureActive(); } } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; } }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
src/DateRange.js
mimshwright/react-date-range
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import parseInput from './utils/parseInput.js'; import Calendar from './Calendar.js'; import PredefinedRanges from './PredefinedRanges.js'; import getTheme, { defaultClasses } from './styles.js'; class DateRange extends Component { constructor(props, context) { super(props, context); const { format, linkedCalendars, theme } = props; const startDate = parseInput(props.startDate, format, 'startOf'); const endDate = parseInput(props.endDate, format, 'endOf'); this.state = { range : { startDate, endDate }, link : linkedCalendars && endDate, } this.step = 0; this.styles = getTheme(theme); } componentDidMount() { const { onInit } = this.props; onInit && onInit(this.state.range); } orderRange(range) { const { startDate, endDate } = range; const swap = startDate.isAfter(endDate); if (!swap) return range; return { startDate : endDate, endDate : startDate } } setRange(range, source, triggerChange) { const { onChange } = this.props range = this.orderRange(range); this.setState({ range }, () => triggerChange && onChange && onChange(range, source)); } handleSelect(date, source) { if (date.startDate && date.endDate) { this.step = 0; return this.setRange(date, source, true); } const { startDate, endDate } = this.state.range; const range = { startDate : startDate, endDate : endDate }; switch (this.step) { case 0: range['startDate'] = date; range['endDate'] = date; this.step = 1; break; case 1: range['endDate'] = date; this.step = 0; break; } const triggerChange = !this.props.twoStepChange || this.step === 0 && this.props.twoStepChange; this.setRange(range, source, triggerChange); } handleLinkChange(direction) { const { link } = this.state; this.setState({ link : link.clone().add(direction, 'months') }); } componentWillReceiveProps(newProps) { // Whenever date props changes, update state with parsed variant if (newProps.startDate || newProps.endDate) { const format = newProps.format || this.props.format; const startDate = newProps.startDate && parseInput(newProps.startDate, format, 'startOf'); const endDate = newProps.endDate && parseInput(newProps.endDate, format, 'endOf'); const oldStartDate = this.props.startDate && parseInput(this.props.startDate, format, 'startOf'); const oldEndDate = this.props.endDate && parseInput(this.props.endDate, format, 'endOf'); if (!startDate.isSame(oldStartDate) || !endDate.isSame(oldEndDate)) { this.setRange({ startDate: startDate || oldStartDate, endDate: endDate || oldEndDate }); } } } render() { const { ranges, format, linkedCalendars, style, calendars, firstDayOfWeek, minDate, maxDate, classNames, onlyClasses, specialDays, lang, disableDaysBeforeToday, offsetPositive, shownDate, showMonthArrow, rangedCalendars } = this.props; const { range, link } = this.state; const { styles } = this; const classes = { ...defaultClasses, ...classNames }; const yearsDiff = range.endDate.year() - range.startDate.year(); const monthsDiff = range.endDate.month() - range.startDate.month(); const diff = yearsDiff * 12 + monthsDiff; const calendarsCount = Number(calendars) - 1; return ( <div style={onlyClasses ? undefined : { ...styles['DateRange'], ...style }} className={classes.dateRange}> { ranges && ( <PredefinedRanges format={ format } ranges={ ranges } range={ range } theme={ styles } onSelect={this.handleSelect.bind(this)} onlyClasses={ onlyClasses } classNames={ classes } /> )} {(()=>{ const _calendars = []; const _method = offsetPositive ? 'unshift' : 'push'; for (var i = calendarsCount; i >= 0; i--) { const offset = offsetPositive ? i : -i; const realDiff = offsetPositive ? diff : -diff; const realOffset = (rangedCalendars && i == calendarsCount && diff != 0) ? realDiff : offset; _calendars[_method]( <Calendar showMonthArrow={ showMonthArrow } shownDate={ shownDate } disableDaysBeforeToday={ disableDaysBeforeToday } lang={ lang } key={i} offset={ realOffset } link={ linkedCalendars && link } linkCB={ this.handleLinkChange.bind(this) } range={ range } format={ format } firstDayOfWeek={ firstDayOfWeek } theme={ styles } minDate={ minDate } maxDate={ maxDate } onlyClasses={ onlyClasses } specialDays={ specialDays } classNames={ classes } onChange={ this.handleSelect.bind(this) } /> ); } return _calendars; })()} </div> ); } } DateRange.defaultProps = { linkedCalendars : false, theme : {}, format : 'DD/MM/YYYY', calendars : 2, onlyClasses : false, offsetPositive : false, classNames : {}, specialDays : [], rangedCalendars : false, twoStepChange : false, } DateRange.propTypes = { format : PropTypes.string, firstDayOfWeek : PropTypes.number, calendars : PropTypes.oneOfType([PropTypes.string, PropTypes.number]), startDate : PropTypes.oneOfType([PropTypes.object, PropTypes.func, PropTypes.string]), endDate : PropTypes.oneOfType([PropTypes.object, PropTypes.func, PropTypes.string]), minDate : PropTypes.oneOfType([PropTypes.object, PropTypes.func, PropTypes.string]), maxDate : PropTypes.oneOfType([PropTypes.object, PropTypes.func, PropTypes.string]), dateLimit : PropTypes.func, ranges : PropTypes.object, linkedCalendars : PropTypes.bool, twoStepChange : PropTypes.bool, theme : PropTypes.object, onInit : PropTypes.func, onChange : PropTypes.func, onlyClasses : PropTypes.bool, specialDays : PropTypes.array, offsetPositive : PropTypes.bool, classNames : PropTypes.object, rangedCalendars : PropTypes.bool, } export default DateRange;
WebCola/extern/jquery-1.10.2.min.js
repos-viz/WebCola
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery-1.10.2.min.map */ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t }({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
admin/client/components/Toolbar/index.js
qwales1/keystone
import React from 'react'; import { Container } from 'elemental'; module.exports = React.createClass({ displayName: 'Toolbar', render () { return ( <div {...this.props} className="Toolbar"> <Container clearfix > {this.props.children} </Container> </div> ); }, }); // expose the children to the top level export module.exports.Section = require('./ToolbarSection');
docs/src/ComponentsPage.js
Sipree/react-bootstrap
import React from 'react'; import AutoAffix from 'react-overlays/lib/AutoAffix'; import Waypoint from 'react-waypoint'; import Nav from '../../src/Nav'; import NavItem from '../../src/NavItem'; import Anchor from './Anchor'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; import SubNav from './SubNav'; import AlertsSection from './sections/AlertsSection'; import BadgeSection from './sections/BadgeSection'; import BreadcrumbSection from './sections/BreadcrumbSection'; import ButtonGroupSection from './sections/ButtonGroupSection'; import ButtonSection from './sections/ButtonSection'; import CarouselSection from './sections/CarouselSection'; import DropdownSection from './sections/DropdownSection'; import FormSection from './sections/FormSection'; import GlyphiconSection from './sections/GlyphiconSection'; import GridSection from './sections/GridSection'; import ImageSection from './sections/ImageSection'; import JumbotronSection from './sections/JumbotronSection'; import LabelSection from './sections/LabelSection'; import ListGroupSection from './sections/ListGroupSection'; import MenuItemSection from './sections/MenuItemSection'; import ModalSection from './sections/ModalSection'; import NavbarSection from './sections/NavbarSection'; import NavSection from './sections/NavSection'; import OverlaySection from './sections/OverlaySection'; import PageHeaderSection from './sections/PageHeaderSection'; import PagerSection from './sections/PagerSection'; import PaginationSection from './sections/PaginationSection'; import PanelSection from './sections/PanelSection'; import PopoverSection from './sections/PopoverSection'; import ProgressBarSection from './sections/ProgressBarSection'; import ResponsiveEmbedSection from './sections/ResponsiveEmbedSection'; import TableSection from './sections/TableSection'; import TabsSection from './sections/TabsSection'; import ThumbnailSection from './sections/ThumbnailSection'; import TooltipSection from './sections/TooltipSection'; import TransitionSection from './sections/TransitionSection'; import WellSection from './sections/WellSection'; // order matters /* eslint-disable indent */ const sections = { buttons: '#buttons', btnGroups: '#btn-groups', dropdowns: '#btn-dropdowns', menuitems: '#menu-items', overlays: '#overlays', modals: '#modals', tooltips: '#tooltips', popovers: '#popovers', customOverlays: '#custom-overlays', navigation: '#navigation', navs: '#navs', navbars: '#navbars', crumbs: '#breadcrumbs', tabs: '#tabs', pagination: '#pagination', pager: '#pager', layout: '#page-layout', grid: '#grid', jumbotron: '#jumbotron', pageHeader: '#page-header', listGroup: '#listgroup', tables: '#tables', panels: '#panels', wells: '#wells', forms: '#forms', media: '#media-content', images: '#images', thumbnails: '#thumbnail', embed: '#responsive-embed', carousels: '#carousels', misc: '#misc', icons: '#glyphicons', labels: '#labels', badges: '#badges', alerts: '#alerts', progress: '#progress', utilities: '#utilities', transitions: '#transitions', missing: '#missing', affix: '#affix', scrollspy: '#scrollspy' }; /* eslint-enable indent */ let ScrollSpy = ({ href, onBefore, onAfter }) => ( <Waypoint onEnter={(e, dir) => dir === 'above' && onBefore(href)} onLeave={(e, dir) => dir === 'above' && onAfter(href)} threshold={-0.02} /> ); const ComponentsPage = React.createClass({ getInitialState() { return { activeNavItemHref: null }; }, getMain() { return this.refs.main; }, handleNavItemSelect(key, href) { window.location = href; }, componentDidMount() { this.afterSections = {}; Object.keys(sections).forEach( key => this.afterSections[sections[key]] = false ); const { hash } = window.location; if (this.afterSections[hash] !== undefined) { for (const href of Object.keys(this.afterSections)) { this.afterSections[href] = true; if (href === hash) { this.setActiveNavItem(); break; } } } }, setActiveNavItem() { let activeNavItemHref = null; for (const href of Object.keys(this.afterSections)) { if (!this.afterSections[href]) { this.setState({ activeNavItemHref }); return; } activeNavItemHref = href; } }, renderScrollSpy(href) { return ( <ScrollSpy href={href} onBefore={this.onBefore} onAfter={this.onAfter} /> ); }, onBefore(href) { this.afterSections[href] = false; this.updateActiveHref(); }, onAfter(href) { this.afterSections[href] = true; this.updateActiveHref(); }, updateActiveHref() { if (this.updateActiveHrefHandle != null) { return; } this.updateActiveHrefHandle = setTimeout(() => { this.updateActiveHrefHandle = null; this.setActiveNavItem(); }); }, render() { return ( <div> <NavMain activePage="components" ref="topNav" /> <PageHeader title="Components" subTitle="" /> <div ref="main" className="container bs-docs-container"> <div className="row"> <div className="col-md-9" role="main"> {this.renderScrollSpy(sections.buttons)} <ButtonSection /> {this.renderScrollSpy(sections.btnGroups)} <ButtonGroupSection /> {this.renderScrollSpy(sections.dropdowns)} <DropdownSection /> {this.renderScrollSpy(sections.menuitems)} <MenuItemSection /> {this.renderScrollSpy(sections.overlays)} <div className="bs-docs-section"> <h1 className="page-header"> <Anchor id="overlays">Overlays</Anchor> </h1> <p className="lead">React-Bootstrap offers a number of accessible overlay components built using <a href="http://react-bootstrap.github.io/react-overlays/examples/">react-overlays</a>.</p> </div> {this.renderScrollSpy(sections.modals)} <ModalSection /> {this.renderScrollSpy(sections.tooltips)} <TooltipSection /> {this.renderScrollSpy(sections.popovers)} <PopoverSection /> {this.renderScrollSpy(sections.customOverlays)} <OverlaySection /> {this.renderScrollSpy(sections.navigation)} <div className="bs-docs-section"> <h1 className="page-header"> <Anchor id="navigation">Navigation</Anchor> </h1> <p className="lead">React-Bootstrap offers a variety of responsive, accessible components for setting up navigation both across your website and within your pages.</p> </div> {this.renderScrollSpy(sections.navs)} <NavSection /> {this.renderScrollSpy(sections.navbars)} <NavbarSection /> {this.renderScrollSpy(sections.crumbs)} <BreadcrumbSection /> {this.renderScrollSpy(sections.tabs)} <TabsSection /> {this.renderScrollSpy(sections.pagination)} <PaginationSection /> {this.renderScrollSpy(sections.pager)} <PagerSection /> {this.renderScrollSpy(sections.layout)} <div className="bs-docs-section"> <h1 className="page-header"> <Anchor id="page-layout">Page layout</Anchor> </h1> <p className="lead">The components in this section offer different ways to structure and present data on your page.</p> </div> {this.renderScrollSpy(sections.grid)} <GridSection /> {this.renderScrollSpy(sections.jumbotron)} <JumbotronSection /> {this.renderScrollSpy(sections.pageHeader)} <PageHeaderSection /> {this.renderScrollSpy(sections.listGroup)} <ListGroupSection /> {this.renderScrollSpy(sections.tables)} <TableSection /> {this.renderScrollSpy(sections.panels)} <PanelSection /> {this.renderScrollSpy(sections.wells)} <WellSection /> {this.renderScrollSpy(sections.forms)} <FormSection /> {this.renderScrollSpy(sections.media)} <div className="bs-docs-section"> <h1 className="page-header"> <Anchor id="media-content">Media content</Anchor> </h1> <p className="lead">The React-Bootstrap media content components offer ways to present images and other media to your users in a responsive way, along with support for styling those components.</p> </div> {this.renderScrollSpy(sections.images)} <ImageSection /> {this.renderScrollSpy(sections.thumbnails)} <ThumbnailSection /> {this.renderScrollSpy(sections.embed)} <ResponsiveEmbedSection /> {this.renderScrollSpy(sections.carousels)} <CarouselSection /> {this.renderScrollSpy(sections.misc)} <div className="bs-docs-section"> <h1 className="page-header"> <Anchor id="misc">Miscellaneous components</Anchor> </h1> <p className="lead">React-Bootstrap also offers various standalone components that can be used to present specific, relevant kinds of information across your pages.</p> </div> {this.renderScrollSpy(sections.icons)} <GlyphiconSection /> {this.renderScrollSpy(sections.labels)} <LabelSection /> {this.renderScrollSpy(sections.badges)} <BadgeSection /> {this.renderScrollSpy(sections.alerts)} <AlertsSection /> {this.renderScrollSpy(sections.progress)} <ProgressBarSection /> {this.renderScrollSpy(sections.utilities)} <div className="bs-docs-section"> <h1 className="page-header"> <Anchor id="utilities">Utilities</Anchor> </h1> <p className="lead">React-Bootstrap also exposes certain utility components used internally. They can be used to enhance your own custom components as well.</p> </div> {this.renderScrollSpy(sections.transitions)} <TransitionSection /> {this.renderScrollSpy(sections.missing)} <div className="bs-docs-section"> <h1 className="page-header"> <Anchor id="missing">Missing components</Anchor> </h1> <p className="lead">We've intentionally omitted a few components from React-Bootstrap. Don't worry, though &ndash; we cover what to do in this section.</p> </div> {this.renderScrollSpy(sections.affix)} <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="affix">Affix</Anchor> </h2> <p>Use <a href="http://react-bootstrap.github.io/react-overlays/examples/#affixes"><code>{'<AutoAffix>'}</code> or <code>{'<Affix>'}</code> from react-overlays</a>.</p> <p>There isn't really any additional Bootstrap markup associated with affixes, so we didn't add a Bootstrap-specific affix class. The upstream ones already give you everything you need.</p> </div> {this.renderScrollSpy(sections.scrollspy)} <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="scrollspy">Scrollspy</Anchor> </h2> <p>Setting up a scrollspy in idiomatic React requires wiring up a number of components across your entire page, both to handle elements scrolling in and to wire that up to the navigation. It's a poor fit for a component library, because it's not a standalone component.</p> <p> To implement this functionality, use a library like <a href="http://brigade.github.io/react-waypoint/">React Waypoint</a> along with a bit of your own state management. You can check out how we implemented it on the side panel here by reading the <a href="https://github.com/react-bootstrap/react-bootstrap/blob/master/docs/src/ComponentsPage.js">docs source</a>. </p> </div> </div> <div className="col-md-3 bs-docs-sidebar-holder"> <AutoAffix viewportOffsetTop={20} container={this.getMain} > <div className="bs-docs-sidebar hidden-print" role="complementary" > <Nav className="bs-docs-sidenav" activeHref={this.state.activeNavItemHref} onSelect={this.handleNavItemSelect} > <SubNav href={sections.buttons} text="Buttons"> <NavItem href={sections.btnGroups}>Button groups</NavItem> <NavItem href={sections.dropdowns}>Dropdowns</NavItem> <NavItem href={sections.menuitems}>Menu items</NavItem> </SubNav> <SubNav href={sections.overlays} text="Overlays"> <NavItem href={sections.modals}>Modals</NavItem> <NavItem href={sections.tooltips}>Tooltips</NavItem> <NavItem href={sections.popovers}>Popovers</NavItem> <NavItem href={sections.customOverlays}>Custom overlays</NavItem> </SubNav> <SubNav href={sections.navigation} text="Navigation"> <NavItem href={sections.navs}>Navs</NavItem> <NavItem href={sections.navbars}>Navbars</NavItem> <NavItem href={sections.crumbs}>Breadcrumbs</NavItem> <NavItem href={sections.tabs}>Tabs</NavItem> <NavItem href={sections.pagination}>Pagination</NavItem> <NavItem href={sections.pager}>Pager</NavItem> </SubNav> <SubNav href={sections.layout} text="Page layout"> <NavItem href={sections.grid}>Grid system</NavItem> <NavItem href={sections.jumbotron}>Jumbotron</NavItem> <NavItem href={sections.pageHeader}>Page header</NavItem> <NavItem href={sections.listGroup}>List group</NavItem> <NavItem href={sections.tables}>Tables</NavItem> <NavItem href={sections.panels}>Panels</NavItem> <NavItem href={sections.wells}>Wells</NavItem> </SubNav> <NavItem href={sections.forms}>Forms</NavItem> <SubNav href={sections.media} text="Media content"> <NavItem href={sections.images}>Images</NavItem> <NavItem href={sections.thumbnails}>Thumbnails</NavItem> <NavItem href={sections.embed}>Responsive embed</NavItem> <NavItem href={sections.carousels}>Carousels</NavItem> </SubNav> <SubNav href={sections.misc} text="Miscellaneous"> <NavItem href={sections.icons}>Glyphicons</NavItem> <NavItem href={sections.labels}>Labels</NavItem> <NavItem href={sections.badges}>Badges</NavItem> <NavItem href={sections.alerts}>Alerts</NavItem> <NavItem href={sections.progress}>Progress bars</NavItem> </SubNav> <SubNav href={sections.utilities} text="Utilities"> <NavItem href={sections.transitions}>Transitions</NavItem> </SubNav> <SubNav href={sections.missing} text="Missing components"> <NavItem href={sections.affix}>Affix</NavItem> <NavItem href={sections.scrollspy}>Scrollspy</NavItem> </SubNav> </Nav> <a className="back-to-top" href="#top"> Back to top </a> </div> </AutoAffix> </div> </div> </div> <PageFooter ref="footer" /> </div> ); } }); export default ComponentsPage;
ajax/libs/material-ui/5.0.0-alpha.10/esm/Tooltip/Tooltip.min.js
cdnjs/cdnjs
import _extends from"@babel/runtime/helpers/esm/extends";import _slicedToArray from"@babel/runtime/helpers/esm/slicedToArray";import _objectWithoutProperties from"@babel/runtime/helpers/esm/objectWithoutProperties";import _defineProperty from"@babel/runtime/helpers/esm/defineProperty";import*as React from"react";import PropTypes from"prop-types";import clsx from"clsx";import{deepmerge,elementAcceptingRef}from"@material-ui/utils";import{fade}from"../styles/colorManipulator";import withStyles from"../styles/withStyles";import capitalize from"../utils/capitalize";import Grow from"../Grow";import Popper from"../Popper";import useEventCallback from"../utils/useEventCallback";import useForkRef from"../utils/useForkRef";import useId from"../utils/useId";import useIsFocusVisible from"../utils/useIsFocusVisible";import useControlled from"../utils/useControlled";import useTheme from"../styles/useTheme";function round(e){return Math.round(1e5*e)/1e5}function arrowGenerator(){return{'&[x-placement*="bottom"] $arrow':{top:0,left:0,marginTop:"-0.71em",marginLeft:4,marginRight:4,"&::before":{transformOrigin:"0 100%"}},'&[x-placement*="top"] $arrow':{bottom:0,left:0,marginBottom:"-0.71em",marginLeft:4,marginRight:4,"&::before":{transformOrigin:"100% 0"}},'&[x-placement*="right"] $arrow':{left:0,marginLeft:"-0.71em",height:"1em",width:"0.71em",marginTop:4,marginBottom:4,"&::before":{transformOrigin:"100% 100%"}},'&[x-placement*="left"] $arrow':{right:0,marginRight:"-0.71em",height:"1em",width:"0.71em",marginTop:4,marginBottom:4,"&::before":{transformOrigin:"0 0"}}}}export var styles=function(e){return{popper:{zIndex:e.zIndex.tooltip,pointerEvents:"none"},popperInteractive:{pointerEvents:"auto"},popperArrow:arrowGenerator(),tooltip:{backgroundColor:fade(e.palette.grey[700],.92),borderRadius:e.shape.borderRadius,color:e.palette.common.white,fontFamily:e.typography.fontFamily,padding:"4px 8px",fontSize:e.typography.pxToRem(11),maxWidth:300,wordWrap:"break-word",fontWeight:e.typography.fontWeightMedium},tooltipArrow:{position:"relative",margin:"0"},arrow:{overflow:"hidden",position:"absolute",width:"1em",height:"0.71em",boxSizing:"border-box",color:fade(e.palette.grey[700],.9),"&::before":{content:'""',margin:"auto",display:"block",width:"100%",height:"100%",backgroundColor:"currentColor",transform:"rotate(45deg)"}},touch:{padding:"8px 16px",fontSize:e.typography.pxToRem(14),lineHeight:"".concat(round(16/14),"em"),fontWeight:e.typography.fontWeightRegular},tooltipPlacementLeft:_defineProperty({transformOrigin:"right center",margin:"0 24px "},e.breakpoints.up("sm"),{margin:"0 14px"}),tooltipPlacementRight:_defineProperty({transformOrigin:"left center",margin:"0 24px"},e.breakpoints.up("sm"),{margin:"0 14px"}),tooltipPlacementTop:_defineProperty({transformOrigin:"center bottom",margin:"24px 0"},e.breakpoints.up("sm"),{margin:"14px 0"}),tooltipPlacementBottom:_defineProperty({transformOrigin:"center top",margin:"24px 0"},e.breakpoints.up("sm"),{margin:"14px 0"})}};var hystersisOpen=!1,hystersisTimer=null;export function testReset(){hystersisOpen=!1,clearTimeout(hystersisTimer)};var Tooltip=React.forwardRef(function(e,t){var o=e.arrow,r=void 0!==o&&o,n=e.children,i=e.classes,s=e.disableFocusListener,a=void 0!==s&&s,p=e.disableHoverListener,l=void 0!==p&&p,c=e.disableTouchListener,u=void 0!==c&&c,m=e.enterDelay,d=void 0===m?100:m,f=e.enterNextDelay,h=void 0===f?0:f,T=e.enterTouchDelay,y=void 0===T?700:T,v=e.id,b=e.interactive,g=void 0!==b&&b,P=e.leaveDelay,R=void 0===P?0:P,x=e.leaveTouchDelay,w=void 0===x?1500:x,E=e.onClose,O=e.onOpen,k=e.open,F=e.placement,L=void 0===F?"bottom":F,C=e.PopperComponent,D=void 0===C?Popper:C,N=e.PopperProps,_=e.title,M=e.TransitionComponent,S=void 0===M?Grow:M,A=e.TransitionProps,I=_objectWithoutProperties(e,["arrow","children","classes","disableFocusListener","disableHoverListener","disableTouchListener","enterDelay","enterNextDelay","enterTouchDelay","id","interactive","leaveDelay","leaveTouchDelay","onClose","onOpen","open","placement","PopperComponent","PopperProps","title","TransitionComponent","TransitionProps"]),B=useTheme(),W=React.useState(),j=W[0],z=W[1],V=React.useState(null),G=V[0],H=V[1],$=React.useRef(!1),q=React.useRef(),U=React.useRef(),Y=React.useRef(),J=React.useRef(),K=useControlled({controlled:k,default:!1,name:"Tooltip",state:"open"}),Q=_slicedToArray(K,2),X=Q[0],Z=Q[1],ee=X;if("production"!==process.env.NODE_ENV){var te=React.useRef(void 0!==k).current;React.useEffect(function(){j&&j.disabled&&!te&&""!==_&&"button"===j.tagName.toLowerCase()&&console.error(["Material-UI: You are providing a disabled `button` child to the Tooltip component.","A disabled element does not fire events.","Tooltip needs to listen to the child element's events to display the title.","","Add a simple wrapper element, such as a `span`."].join("\n"))},[_,j,te])}var oe=useId(v);React.useEffect(function(){return function(){clearTimeout(q.current),clearTimeout(U.current),clearTimeout(Y.current),clearTimeout(J.current)}},[]);var re=function(e){clearTimeout(hystersisTimer),hystersisOpen=!0,Z(!0),O&&O(e)},ne=function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function(t){var o=n.props;"mouseover"===t.type&&o.onMouseOver&&e&&o.onMouseOver(t),$.current&&"touchstart"!==t.type||(j&&j.removeAttribute("title"),clearTimeout(U.current),clearTimeout(Y.current),d||hystersisOpen&&h?(t.persist(),U.current=setTimeout(function(){re(t)},hystersisOpen?h:d)):re(t))}},ie=useIsFocusVisible(),se=ie.isFocusVisibleRef,ae=ie.onBlur,pe=ie.onFocus,le=ie.ref,ce=React.useState(!1)[1],ue=function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function(t){j||z(t.currentTarget),pe(t),!0===se.current&&(ce(!0),ne()(t));var o=n.props;o.onFocus&&e&&o.onFocus(t)}},me=useEventCallback(function(e){clearTimeout(hystersisTimer),hystersisTimer=setTimeout(function(){hystersisOpen=!1},800+R),Z(!1),E&&E(e),clearTimeout(q.current),q.current=setTimeout(function(){$.current=!1},B.transitions.duration.shortest)}),de=function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function(t){var o=n.props;"blur"===t.type&&(o.onBlur&&e&&o.onBlur(t),function(e){ae(e),!1===se.current&&ce(!1)}(t)),"mouseleave"===t.type&&o.onMouseLeave&&t.currentTarget===j&&o.onMouseLeave(t),clearTimeout(U.current),clearTimeout(Y.current),t.persist(),Y.current=setTimeout(function(){me(t)},R)}},fe=function(e){$.current=!0;var t=n.props;t.onTouchStart&&t.onTouchStart(e)};React.useEffect(function(){if(ee)return document.addEventListener("keydown",e),function(){document.removeEventListener("keydown",e)};function e(e){"Escape"!==e.key&&"Esc"!==e.key||me(e)}},[me,ee]);var he=useForkRef(z,t),Te=useForkRef(le,he),ye=useForkRef(n.ref,Te);""===_&&(ee=!1);var ve=_extends({"aria-describedby":ee?oe:null,title:!ee&&!l&&"string"==typeof _?_:null},I,n.props,{className:clsx(I.className,n.props.className),onTouchStart:fe,ref:ye}),be={};u||(ve.onTouchStart=function(e){fe(e),clearTimeout(Y.current),clearTimeout(q.current),clearTimeout(J.current),e.persist(),J.current=setTimeout(function(){ne()(e)},y)},ve.onTouchEnd=function(e){n.props.onTouchEnd&&n.props.onTouchEnd(e),clearTimeout(J.current),clearTimeout(Y.current),e.persist(),Y.current=setTimeout(function(){me(e)},w)}),l||(ve.onMouseOver=ne(),ve.onMouseLeave=de(),g&&(be.onMouseOver=ne(!1),be.onMouseLeave=de(!1))),a||(ve.onFocus=ue(),ve.onBlur=de(),g&&(be.onFocus=ue(!1),be.onBlur=de(!1))),"production"!==process.env.NODE_ENV&&n.props.title&&console.error(["Material-UI: You have provided a `title` prop to the child of <Tooltip />.","Remove this title prop `".concat(n.props.title,"` or the Tooltip component.")].join("\n"));var ge=React.useMemo(function(){return deepmerge({popperOptions:{modifiers:{arrow:{enabled:Boolean(G),element:G}}}},N)},[G,N]);return React.createElement(React.Fragment,null,React.cloneElement(n,ve),React.createElement(D,_extends({className:clsx(i.popper,g&&i.popperInteractive,r&&i.popperArrow),placement:L,anchorEl:j,open:!!j&&ee,id:ve["aria-describedby"],transition:!0},be,ge),function(e){var t=e.placement,o=e.TransitionProps;return React.createElement(S,_extends({timeout:B.transitions.duration.shorter},o,A),React.createElement("div",{className:clsx(i.tooltip,i["tooltipPlacement".concat(capitalize(t.split("-")[0]))],$.current&&i.touch,r&&i.tooltipArrow)},_,r?React.createElement("span",{className:i.arrow,ref:H}):null))}))});"production"!==process.env.NODE_ENV&&(Tooltip.propTypes={arrow:PropTypes.bool,children:elementAcceptingRef.isRequired,classes:PropTypes.object,className:PropTypes.string,disableFocusListener:PropTypes.bool,disableHoverListener:PropTypes.bool,disableTouchListener:PropTypes.bool,enterDelay:PropTypes.number,enterNextDelay:PropTypes.number,enterTouchDelay:PropTypes.number,id:PropTypes.string,interactive:PropTypes.bool,leaveDelay:PropTypes.number,leaveTouchDelay:PropTypes.number,onClose:PropTypes.func,onOpen:PropTypes.func,open:PropTypes.bool,placement:PropTypes.oneOf(["bottom-end","bottom-start","bottom","left-end","left-start","left","right-end","right-start","right","top-end","top-start","top"]),PopperComponent:PropTypes.elementType,PopperProps:PropTypes.object,title:PropTypes.node.isRequired,TransitionComponent:PropTypes.elementType,TransitionProps:PropTypes.object});export default withStyles(styles,{name:"MuiTooltip",flip:!1})(Tooltip);
src/components/Header/Header.js
ynu/res-track-wxe
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Header.css'; import Link from '../Link'; import Navigation from '../Navigation'; import logoUrl from './logo-small.png'; function Header() { return ( <div className={s.root}> <div className={s.container}> <Navigation className={s.nav} /> <Link className={s.brand} to="/"> <img src={logoUrl} width="38" height="38" alt="React" /> <span className={s.brandTxt}>Your Company</span> </Link> <div className={s.banner}> <h1 className={s.bannerTitle}>React</h1> <p className={s.bannerDesc}>Complex web apps made easy</p> </div> </div> </div> ); } export default withStyles(s)(Header);
ajax/libs/mediaelement/2.2.2/jquery.js
mgoldsborough/cdnjs
/*! * jQuery JavaScript Library v1.6.1 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu May 12 15:04:36 2011 -0400 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Check for digits rdigit = /\d/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return (context || rootjQuery).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.6.1", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.done( fn ); return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).unbind( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery._Deferred(); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNaN: function( obj ) { return obj == null || !rdigit.test( obj ) || isNaN( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return (new Function( "return " + data ))(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing // (xml & tmp used internally) parseXML: function( data , xml , tmp ) { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } tmp = xml.documentElement; if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( indexOf ) { return indexOf.call( array, elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { if ( typeof context === "string" ) { var tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return (new Date()).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } // Expose jQuery to the global object return jQuery; })(); var // Promise methods promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ // Create a simple deferred (one callbacks list) _Deferred: function() { var // callbacks list callbacks = [], // stored [ context , args ] fired, // to avoid firing when already doing so firing, // flag to know if the deferred has been cancelled cancelled, // the deferred itself deferred = { // done( f1, f2, ...) done: function() { if ( !cancelled ) { var args = arguments, i, length, elem, type, _fired; if ( fired ) { _fired = fired; fired = 0; } for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { deferred.done.apply( deferred, elem ); } else if ( type === "function" ) { callbacks.push( elem ); } } if ( _fired ) { deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); } } return this; }, // resolve with given context and args resolveWith: function( context, args ) { if ( !cancelled && !fired && !firing ) { // make sure args are available (#8421) args = args || []; firing = 1; try { while( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); } } finally { fired = [ context, args ]; firing = 0; } } return this; }, // resolve with this as context and given arguments resolve: function() { deferred.resolveWith( this, arguments ); return this; }, // Has this deferred been resolved? isResolved: function() { return !!( firing || fired ); }, // Cancel cancel: function() { cancelled = 1; callbacks = []; return this; } }; return deferred; }, // Full fledged deferred (two callbacks list) Deferred: function( func ) { var deferred = jQuery._Deferred(), failDeferred = jQuery._Deferred(), promise; // Add errorDeferred methods, then and promise jQuery.extend( deferred, { then: function( doneCallbacks, failCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ); return this; }, always: function() { return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); }, fail: failDeferred.done, rejectWith: failDeferred.resolveWith, reject: failDeferred.resolve, isRejected: failDeferred.isResolved, pipe: function( fnDone, fnFail ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject ); } else { newDefer[ action ]( returned ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { if ( promise ) { return promise; } promise = obj = {}; } var i = promiseMethods.length; while( i-- ) { obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; } return obj; } }); // Make sure only one callback list will be used deferred.done( failDeferred.cancel ).fail( deferred.cancel ); // Unexpose cancel delete deferred.cancel; // Call given func if any if ( func ) { func.call( deferred, deferred ); } return deferred; }, // Deferred helper when: function( firstParam ) { var args = arguments, i = 0, length = args.length, count = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { // Strange bug in FF4: // Values changed onto the arguments object sometimes end up as undefined values // outside the $.when method. Cloning the object into a fresh array solves the issue deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); } }; } if ( length > 1 ) { for( ; i < length; i++ ) { if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return deferred.promise(); } }); jQuery.support = (function() { var div = document.createElement( "div" ), documentElement = document.documentElement, all, a, select, opt, input, marginDiv, support, fragment, body, bodyStyle, tds, events, eventName, i, isSupported; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName( "tbody" ).length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName( "link" ).length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute( "href" ) === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; div.detachEvent( "onclick", click ); }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains it's value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; div.innerHTML = ""; // Figure out if the W3C box model works as expected div.style.width = div.style.paddingLeft = "1px"; // We use our own, invisible, body body = document.createElement( "body" ); bodyStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, // Set background to avoid IE crashes when removing (#9028) background: "none" }; for ( i in bodyStyle ) { body.style[ i ] = bodyStyle[ i ]; } body.appendChild( div ); documentElement.insertBefore( body, documentElement.firstChild ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; support.boxModel = div.offsetWidth === 2; if ( "zoom" in div.style ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); } div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE < 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); div.innerHTML = ""; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( document.defaultView && document.defaultView.getComputedStyle ) { marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } // Remove the body element we added body.innerHTML = ""; documentElement.removeChild( body ); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for( i in { submit: 1, change: 1, focusin: 1 } ) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } return support; })(); // Keep track of boxModel jQuery.boxModel = jQuery.support.boxModel; var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([a-z])([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ jQuery.expando ] = id = ++jQuery.uuid; } else { id = jQuery.expando; } } if ( !cache[ id ] ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); } else { cache[ id ] = jQuery.extend(cache[ id ], name); } } thisCache = cache[ id ]; // Internal jQuery data is stored in a separate object inside the object's data // cache in order to avoid key collisions between internal data and user-defined // data if ( pvt ) { if ( !thisCache[ internalKey ] ) { thisCache[ internalKey ] = {}; } thisCache = thisCache[ internalKey ]; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should // not attempt to inspect the internal events object using jQuery.data, as this // internal data object is undocumented and subject to change. if ( name === "events" && !thisCache[name] ) { return thisCache[ internalKey ] && thisCache[ internalKey ].events; } return getByName ? thisCache[ jQuery.camelCase( name ) ] : thisCache; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; if ( thisCache ) { delete thisCache[ name ]; // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !isEmptyDataObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( pvt ) { delete cache[ id ][ internalKey ]; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } var internalCache = cache[ id ][ internalKey ]; // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care if ( jQuery.support.deleteExpando || cache != window ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the entire user cache at once because it's faster than // iterating through each key, but we need to continue to persist internal // data if it existed if ( internalCache ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } cache[ id ][ internalKey ] = internalCache; // Otherwise, we need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist } else if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } else { elem[ jQuery.expando ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 ) { var attr = this[0].attributes, name; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( this[0], name, data[ name ] ); } } } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var $this = jQuery( this ), args = [ parts[0], value ]; $this.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); $this.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : !jQuery.isNaN( data ) ? parseFloat( data ) : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON // property to be considered empty objects; this property always exists in // order to make sure JSON.stringify does not expose internal metadata function isEmptyDataObject( obj ) { for ( var name in obj ) { if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery.data( elem, deferDataKey, undefined, true ); if ( defer && ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) && ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery.data( elem, queueDataKey, undefined, true ) && !jQuery.data( elem, markDataKey, undefined, true ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.resolve(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = (type || "fx") + "mark"; jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 ); if ( count ) { jQuery.data( elem, key, count, true ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { if ( elem ) { type = (type || "fx") + "queue"; var q = jQuery.data( elem, type, undefined, true ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data), true ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), defer; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function() { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { count++; tmp.done( resolve ); } } resolve(); return defer.promise(); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, rinvalidChar = /\:/, formHook, boolHook; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.prop ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class") || "") ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[c] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attrFix: { // Always normalize to ensure hook usage tabindex: "tabIndex" }, attr: function( elem, name, value, pass ) { var nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( !("getAttribute" in elem) ) { return jQuery.prop( elem, name, value ); } var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // Normalize the name if needed name = notxml && jQuery.attrFix[ name ] || name; hooks = jQuery.attrHooks[ name ]; if ( !hooks ) { // Use boolHook for boolean attributes if ( rboolean.test( name ) && (typeof value === "boolean" || value === undefined || value.toLowerCase() === name.toLowerCase()) ) { hooks = boolHook; // Use formHook for forms and if the name contains certain characters } else if ( formHook && (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) { hooks = formHook; } } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return undefined; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml ) { return hooks.get( elem, name ); } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, name ) { var propName; if ( elem.nodeType === 1 ) { name = jQuery.attrFix[ name ] || name; if ( jQuery.support.getSetAttribute ) { // Use removeAttribute in browsers that support it elem.removeAttribute( name ); } else { jQuery.attr( elem, name, "" ); elem.removeAttributeNode( elem.getAttributeNode( name ) ); } // Set corresponding property to false for boolean attributes if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) { elem[ propName ] = false; } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabIndex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // Try to normalize/fix the name name = notxml && jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return (elem[ name ] = value); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) { return ret; } else { return elem[ name ]; } } }, propHooks: {} }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties return elem[ jQuery.propFix[ name ] || name ] ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = value; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // Use the value property for back compat // Use the formHook for button elements in IE6/7 (#1954) jQuery.attrHooks.value = { get: function( elem, name ) { if ( formHook && jQuery.nodeName( elem, "button" ) ) { return formHook.get( elem, name ); } return elem.value; }, set: function( elem, value, name ) { if ( formHook && jQuery.nodeName( elem, "button" ) ) { return formHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !jQuery.support.getSetAttribute ) { // propFix is more comprehensive and contains all fixes jQuery.attrFix = jQuery.propFix; // Use this for any attribute on a form in IE6/7 formHook = jQuery.attrHooks.name = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); // Return undefined if nodeValue is empty string return ret && ret.nodeValue !== "" ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Check form objects in IE (multiple bugs related) // Only use nodeValue if the attribute node exists on the form var ret = elem.getAttributeNode( name ); if ( ret ) { ret.nodeValue = value; return value; } } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return (elem.style.cssText = "" + value); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }); } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0); } } }); }); var hasOwn = Object.prototype.hasOwnProperty, rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspaces = / /g, rescape = /[^\w\s.|`]/g, fcleanup = function( nm ) { return nm.replace(rescape, "\\$&"); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } else if ( !handler ) { // Fixes bug #7229. Fix recommended by jdalton return; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery._data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events, eventHandle = elemData.handle; if ( !events ) { elemData.events = events = {}; } if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; if ( !handleObj.guid ) { handleObj.guid = handler.guid; } // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem, undefined, true ); } } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Event object or event type var type = event.type || event, namespaces = [], exclusive; if ( type.indexOf("!") >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.exclusive = exclusive; event.namespace = namespaces.join("."); event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); // triggerHandler() and global events don't bubble or run the default action if ( onlyHandlers || !elem ) { event.preventDefault(); event.stopPropagation(); } // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document jQuery.each( jQuery.cache, function() { // internalKey variable is just used to make it easier to find // and potentially change this stuff later; currently it just // points to jQuery.expando var internalKey = jQuery.expando, internalCache = this[ internalKey ]; if ( internalCache && internalCache.events && internalCache.events[ type ] ) { jQuery.event.trigger( event, data, internalCache.handle.elem ); } }); return; } // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // Clean up the event in case it is being reused event.result = undefined; event.target = elem; // Clone any incoming data and prepend the event, creating the handler arg list data = data ? jQuery.makeArray( data ) : []; data.unshift( event ); var cur = elem, // IE doesn't like method names with a colon (#3533, #8272) ontype = type.indexOf(":") < 0 ? "on" + type : ""; // Fire event on the current element, then bubble up the DOM tree do { var handle = jQuery._data( cur, "handle" ); event.currentTarget = cur; if ( handle ) { handle.apply( cur, data ); } // Trigger an inline bound script if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) { event.result = false; event.preventDefault(); } // Bubble up to document, then to window cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window; } while ( cur && !event.isPropagationStopped() ); // If nobody prevented the default action, do it now if ( !event.isDefaultPrevented() ) { var old, special = jQuery.event.special[ type ] || {}; if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction)() check here because IE6/7 fails that test. // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch. try { if ( ontype && elem[ type ] ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } jQuery.event.triggered = type; elem[ type ](); } } catch ( ieError ) {} if ( old ) { elem[ ontype ] = old; } jQuery.event.triggered = undefined; } } return event.result; }, handle: function( event ) { event = jQuery.event.fix( event || window.event ); // Snapshot the handlers list since a called handler may add/remove events. var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0), run_all = !event.exclusive && !event.namespace, args = Array.prototype.slice.call( arguments, 0 ); // Use the fix-ed Event rather than the (read-only) native event args[0] = event; event.currentTarget = this; for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Triggered event must 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event. if ( run_all || event.namespace_re.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } return event.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( event ) { if ( event[ jQuery.expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { // Fixes #1925 where srcElement might not be defined either event.target = event.srcElement || document; } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var eventDocument = event.target.ownerDocument || document, doc = eventDocument.documentElement, body = eventDocument.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { event.which = event.charCode != null ? event.charCode : event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, liveConvert( handleObj.origType, handleObj.selector ), jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); }, remove: function( handleObj ) { jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // set the correct event type event.type = event.data; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Chrome does something similar, the parentNode property // can be accessed but is null. if ( parent && parent !== document && !parent.parentNode ) { return; } // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( !jQuery.nodeName( this, "form" ) ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( jQuery.nodeName( elem, "select" ) ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery._data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery._data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; e.liveFired = undefined; jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, beforedeactivate: testChange, click: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) { testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information beforeactivate: function( e ) { var elem = e.target; jQuery._data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return rformElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return rformElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; // Handle when the input is .focus()'d changeFilters.focus = changeFilters.beforeactivate; } function trigger( type, elem, args ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. // Don't pass args or remember liveFired; they apply to the donor event. var event = jQuery.extend( {}, args[ 0 ] ); event.type = type; event.originalEvent = {}; event.liveFired = undefined; jQuery.event.handle.call( elem, event ); if ( event.isDefaultPrevented() ) { args[ 0 ].preventDefault(); } } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; function handler( donor ) { // Donor event is always a native one; fix it and switch its type. // Let focusin/out handler cancel the donor focus/blur event. var e = jQuery.event.fix( donor ); e.type = fix; e.originalEvent = {}; jQuery.event.trigger( e, null, e.target ); if ( e.isDefaultPrevented() ) { donor.preventDefault(); } } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { var handler; // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( arguments.length === 2 || data === false ) { fn = data; data = undefined; } if ( name === "one" ) { handler = function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }; handler.guid = fn.guid || jQuery.guid++; } else { handler = fn; } if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( typeof types === "object" && !types.preventDefault ) { for ( var key in types ) { context[ name ]( key, data, types[key], selector ); } return this; } if ( name === "die" && !types && origSelector && origSelector.charAt(0) === "." ) { context.unbind( origSelector ); return this; } if ( data === false || jQuery.isFunction( data ) ) { fn = data || returnFalse; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( liveMap[ type ] ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler for ( var j = 0, l = context.length; j < l; j++ ) { jQuery.event.add( context[j], "live." + liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); } } else { // unbind live handler context.unbind( "live." + liveConvert( type, selector ), fn ); } } return this; }; }); function liveHandler( event ) { var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, elems = [], selectors = [], events = jQuery._data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { return; } if ( event.namespace ) { namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { close = match[i]; for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { elem = close.elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { event.type = handleObj.preType; related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; // Make sure not to accidentally match a child element with the same selector if ( related && jQuery.contains( elem, related ) ) { related = elem; } } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj, level: close.level }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; if ( maxLevel && match.level > maxLevel ) { break; } event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; ret = match.handleObj.origHandler.apply( match.elem, arguments ); if ( ret === false || event.isPropagationStopped() ) { maxLevel = match.level; if ( ret === false ) { stop = false; } if ( event.isImmediatePropagationStopped() ) { break; } } } return stop; } function liveConvert( type, selector ) { return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&"); } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.bind( name, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var match, type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var found, item, filter = Expr.filter[ type ], left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Utility function for retreiving the text value of an array of DOM nodes Sizzle.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += Sizzle.getText( elem.childNodes ); } } return ret; }; // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array if ( jQuery.isArray( selectors ) ) { var match, selector, matches = {}, level = 1; if ( cur && selectors.length ) { for ( i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[ selector ] ) { matches[ selector ] = POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[ selector ]; if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) { ret.push({ selector: selector, elem: cur, level: level }); } } cur = cur.parentNode; level++; } } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ), // The variable 'args' was introduced in // https://github.com/jquery/jquery/commit/52a0238 // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. // http://code.google.com/p/v8/issues/detail?id=1050 args = slice.call(arguments); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, args.join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); } var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<(?:script|object|embed|option|style)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || (l > 1 && i < lastIndex) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var internalKey = jQuery.expando, oldData = jQuery.data( src ), curData = jQuery.data( dest, oldData ); // Switch to use the internal data object, if it exists, for the next // stage of data copying if ( (oldData = oldData[ internalKey ]) ) { var events = oldData.events; curData = curData[ internalKey ] = jQuery.extend({}, oldData); if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); } } } } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( "getElementsByTagName" in elem ) { return elem.getElementsByTagName( "*" ); } else if ( "querySelectorAll" in elem ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( elem.getElementsByTagName ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var clone = elem.cloneNode(true), srcElements, destElements, i; if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName // instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = [], j; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ] && cache[ id ][ internalKey ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rdashAlpha = /-([a-z])/ig, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, rrelNum = /^[+\-]=/, rrelNumFilter = /[^+\-\.\de]+/g, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle, fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "zIndex": true, "fontWeight": true, "opacity": true, "zoom": true, "lineHeight": true, "widows": true, "orphans": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Make sure that NaN and null values aren't set. See: #7116 if ( type === "number" && isNaN( value ) || value == null ) { return; } // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && rrelNum.test( value ) ) { value = +value.replace( rrelNumFilter, "" ) + parseFloat( jQuery.css( elem, name ) ); } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } }, camelCase: function( string ) { return string.replace( rdashAlpha, fcamelCase ); } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { val = getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } if ( val <= 0 ) { val = curCSS( elem, name, name ); if ( val === "0px" && currentStyle ) { val = currentStyle( elem, name, name ); } if ( val != null ) { // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } } if ( val < 0 || val == null ) { val = elem.style[ name ]; // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } return typeof val === "string" ? val : val + "px"; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat(value); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = jQuery.isNaN( value ) ? "" : "alpha(opacity=" + value * 100 + ")", filter = currentStyle && currentStyle.filter || style.filter || ""; style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block var ret; jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { ret = curCSS( elem, "margin-right", "marginRight" ); } else { ret = elem.style.marginRight; } }); return ret; } }; } }); if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( !(defaultView = elem.ownerDocument.defaultView) ) { return undefined; } if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, ret = elem.currentStyle && elem.currentStyle[ name ], rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ], style = elem.style; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { var which = name === "width" ? cssWidth : cssHeight, val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return val; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.css( elem, "margin" + this )) || 0; } else { val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0; } }); return val; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for(; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for(; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.bind( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function ( target, settings ) { if ( !settings ) { // Only one parameter, we extend ajaxSettings settings = target; target = jQuery.extend( true, jQuery.ajaxSettings, settings ); } else { // target was provided, we extend into it jQuery.extend( true, target, jQuery.ajaxSettings, settings ); } // Flatten fields we don't want deep extended for( var field in { context: 1, url: 1 } ) { if ( field in settings ) { target[ field ] = settings[ field ]; } else if( field in jQuery.ajaxSettings ) { target[ field ] = jQuery.ajaxSettings[ field ]; } } return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": "*/*" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery._Deferred(), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, statusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status ? 4 : 0; var isSuccess, success, error, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = statusText; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.done; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefiler, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( status < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { jQuery.error( e ); } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for( key in s.converters ) { if( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = s.contentType === "application/x-www-form-urlencoded" && ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } responses.text = xhr.responseText; // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow, requestAnimationFrame = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( display === "" && jQuery.css( elem, "display" ) === "none" ) { jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName)); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data(elem, "olddisplay") || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { if ( this[i].style ) { var display = jQuery.css( this[i], "display" ); if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) { jQuery._data( this[i], "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); return this[ optall.queue === false ? "each" : "queue" ](function() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, display, e, parts, start, end, unit; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; for ( p in prop ) { // property name normalization name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height // animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { if ( !jQuery.support.inlineBlockNeedsLayout ) { this.style.display = "inline-block"; } else { display = defaultDisplay( this.nodeName ); // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( display === "inline" ) { this.style.display = "inline-block"; } else { this.style.display = "inline"; this.style.zoom = 1; } } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ](); } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ((end || 1) / e.cur()) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { if ( clearQueue ) { this.queue([]); } this.each(function() { var timers = jQuery.timers, i = timers.length; // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } while ( i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function( noUnmark ) { if ( opt.queue !== false ) { jQuery.dequeue( this ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); }, // Get the current size cur: function() { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx, raf; this.startTime = fxNow || createFxNow(); this.start = from; this.end = to; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); this.now = this.start; this.pos = this.state = 0; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { // Use requestAnimationFrame instead of setInterval if available if ( requestAnimationFrame ) { timerId = 1; raf = function() { // When timerId gets set to null at any point, this stops if ( timerId ) { requestAnimationFrame( raf ); fx.tick(); } }; requestAnimationFrame( raf ); } else { timerId = setInterval( fx.tick, fx.interval ); } } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options, i, n; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( i in options.animatedProperties ) { if ( options.animatedProperties[i] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function (index, value) { elem.style[ "overflow" + value ] = options.overflow[index]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery(elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( var p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[p] ); } } // Execute the complete function options.complete.call( elem ); } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[ this.prop ] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ((this.end - this.start) * this.pos); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { for ( var timers = jQuery.timers, i = 0 ; i < timers.length ; ++i ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var elem = jQuery( "<" + nodeName + ">" ).appendTo( "body" ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } document.body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake html // document to it, Webkit & Firefox won't allow reusing the iframe document if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( "<!doctype><html><body></body></html>" ); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0, html = "<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>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed"; checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden"; innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if (options.top != null) { props.top = (options.top - curOffset.top) + curTop; } if (options.left != null) { props.left = (options.left - curOffset.left) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function( val ) { var elem, win; if ( val === undefined ) { elem = this[ 0 ]; if ( !elem ) { return null; } win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery( win ).scrollLeft(), i ? val : jQuery( win ).scrollTop() ); } else { this[ method ] = val; } }); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { return this[0] ? parseFloat( jQuery.css( this[0], type, "padding" ) ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ]; return elem.document.compatMode === "CSS1Compat" && docElemProp || elem.document.body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNaN( ret ) ? orig : ret; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); window.jQuery = window.$ = jQuery; })(window);
src/containers/auth/Forms/FormView.js
jeanlescure/detox-react-native-demo
/** * Login/Sign Up/Forgot Password Screen * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, ScrollView, AsyncStorage, TouchableOpacity, } from 'react-native'; import FormValidation from 'tcomb-form-native'; import { Actions } from 'react-native-router-flux'; // Consts and Libs import { AppStyles } from '@theme/'; // Components import { Alerts, Card, Spacer, Text, Button } from '@ui/'; import TcombTextInput from '@components/tcomb/TextInput'; /* Component ==================================================================== */ let redirectTimeout; class AuthForm extends Component { static componentName = 'Login'; static propTypes = { user: PropTypes.shape({ email: PropTypes.string, firstName: PropTypes.string, lastName: PropTypes.string, }), submit: PropTypes.func, onSuccessfulSubmit: PropTypes.func, formType: PropTypes.oneOf(['login', 'signUp', 'passwordReset', 'updateProfile']), formFields: PropTypes.arrayOf(PropTypes.string), formTestID: PropTypes.string, buttonTitle: PropTypes.string, successMessage: PropTypes.string, introTitle: PropTypes.string, introText: PropTypes.string, } static defaultProps = { user: null, submit: null, onSuccessfulSubmit: null, formType: 'login', formFields: ['Email', 'Password'], buttonTitle: 'Login', successMessage: 'Awesome, you\'re now logged in', introTitle: null, introText: null, } constructor(props) { super(props); // What fields should exist in the form? const formFields = {}; if (props.formFields.indexOf('Email') > -1) formFields.Email = this.validEmail; if (props.formFields.indexOf('Password') > -1) formFields.Password = this.validPassword; if (props.formFields.indexOf('ConfirmPassword') > -1) formFields.ConfirmPassword = this.validPassword; if (props.formFields.indexOf('FirstName') > -1) formFields.FirstName = FormValidation.String; if (props.formFields.indexOf('LastName') > -1) formFields.LastName = FormValidation.String; this.state = { resultMsg: { status: '', success: '', error: '', }, form_fields: FormValidation.struct(formFields), form_values: { Email: (props.user && props.user.email) ? props.user.email : '', FirstName: (props.user && props.user.firstName) ? props.user.firstName : '', LastName: (props.user && props.user.lastName) ? props.user.lastName : '', }, options: { fields: { Email: { template: TcombTextInput, error: 'Please enter a valid email', autoCapitalize: 'none', clearButtonMode: 'while-editing', }, Password: { template: TcombTextInput, error: 'Passwords must be more than 8 characters and contain letters and numbers', clearButtonMode: 'while-editing', secureTextEntry: true, }, ConfirmPassword: { template: TcombTextInput, error: 'Your passwords must match', clearButtonMode: 'while-editing', secureTextEntry: true, }, FirstName: { template: TcombTextInput, error: 'Please enter your first name', clearButtonMode: 'while-editing', }, LastName: { template: TcombTextInput, error: 'Please enter your first name', clearButtonMode: 'while-editing', }, }, }, }; } componentDidMount = async () => { // Pre-populate any details stored in AsyncStorage const values = await this.getStoredCredentials(); if (values !== null && values.email && values.password) { this.setState({ form_values: { ...this.state.form_values, Email: values.email || '', Password: values.password || '', }, }); } } componentWillUnmount = () => clearTimeout(redirectTimeout); /** * Get user data from AsyncStorage to populate fields */ getStoredCredentials = async () => { const values = await AsyncStorage.getItem('api/credentials'); const jsonValues = JSON.parse(values); return jsonValues; } /** * Email Validation */ validEmail = FormValidation.refinement( FormValidation.String, (email) => { const regularExpression = /^.+@.+\..+$/i; return regularExpression.test(email); }, ); /** * Password Validation - Must be 6 chars long */ validPassword = FormValidation.refinement( FormValidation.String, (password) => { if (password.length < 8) return false; // Too short if (password.search(/\d/) === -1) return false; // No numbers if (password.search(/[a-zA-Z]/) === -1) return false; // No letters return true; }, ); /** * Password Confirmation - password fields must match * - Sets the error and returns bool of whether to process form or not */ passwordsMatch = (form) => { const error = form.Password !== form.ConfirmPassword; this.setState({ options: FormValidation.update(this.state.options, { fields: { ConfirmPassword: { hasError: { $set: error }, error: { $set: error ? 'Passwords don\'t match' : '' }, }, }, }), form_values: form, }); return error; } /** * Handle Form Submit */ handleSubmit = () => { // Get new credentials and update const formData = this.form.getValue(); // Check whether passwords match if (formData && formData.Password && formData.ConfirmPassword) { const passwordsDontMatch = this.passwordsMatch(formData); if (passwordsDontMatch) return false; } // Form is valid if (formData) { this.setState({ form_values: formData }, () => { this.setState({ resultMsg: { status: 'One moment...' } }); // Scroll to top, to show message if (this.scrollView) this.scrollView.scrollTo({ y: 0 }); if (this.props.submit) { this.props.submit(formData).then(() => { this.setState({ resultMsg: { success: this.props.successMessage }, }, () => { // If there's another function to fire on successful submit // eg. once signed up, let's log them in - pass the Login function // through as the onSuccessfulSubmit prop if (this.props.onSuccessfulSubmit) { return this.props.onSuccessfulSubmit(formData, true) .then(() => { Actions.app({ type: 'reset' }); Actions.pop(); }).catch(err => this.setState({ resultMsg: { error: err.message } })); } // Timeout to ensure success message is seen/read by user redirectTimeout = setTimeout(() => { Actions.app({ type: 'reset' }); Actions.pop(); }, 500); return true; }); }).catch(err => this.setState({ resultMsg: { error: err.message } })); } else { this.setState({ resultMsg: { error: 'Submit function missing' } }); } }); } return true; } render = () => { const Form = FormValidation.form.Form; return ( <ScrollView automaticallyAdjustContentInsets={false} ref={(a) => { this.scrollView = a; }} style={[AppStyles.container]} contentContainerStyle={[AppStyles.container]} > <Card> <Alerts status={this.state.resultMsg.status} success={this.state.resultMsg.success} error={this.state.resultMsg.error} /> {(!!this.props.introTitle || !!this.props.introText) && <View> {!!this.props.introTitle && <Text h1>{this.props.introTitle}</Text> } {!!this.props.introText && <Text>{this.props.introText}</Text> } <Spacer size={10} /> </View> } <Form ref={(b) => { this.form = b; }} type={this.state.form_fields} value={this.state.form_values} options={this.state.options} testID={this.props.formTestID} /> <Spacer size={20} /> <Button title={this.props.buttonTitle} onPress={this.handleSubmit} /> <Spacer size={10} /> {this.props.formType === 'login' && <View> <TouchableOpacity onPress={Actions.passwordReset}> <Text p style={[AppStyles.textCenterAligned, AppStyles.link]}> Forgot Password </Text> </TouchableOpacity> <Spacer size={10} /> <Text p style={[AppStyles.textCenterAligned]}> - or - </Text> <Button outlined title={'Sign Up'} onPress={Actions.signUp} /> </View> } </Card> <Spacer size={60} /> </ScrollView> ); } } /* Export Component ==================================================================== */ export default AuthForm;
app/assets/javascripts/NewNodeWidget/Section/Overview.js
sozialhelden/wheelmap
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { createStructuredSelector } from 'reselect'; import { Link } from 'react-router'; import I18n from '../../common/I18n'; import { Map, Marker } from '../../common/Mapbox'; import { NAME_CATEGORY, ADDRESS, ACCESSIBILITY, CONTACT, OVERVIEW } from '../models/sections'; import { saveNode } from '../actions'; import * as selectors from '../selectors'; import { nodeTypesSelector, categoriesSelector } from '../../common/selectors'; import { node, nodeType, category, immutableMapOf } from '../../common/propTypes'; import Section from './Section'; const { func, bool } = React.PropTypes; function OverviewSection({ node, nodeTypes, loading, categories, onClickAction }) { let nodeTypeTrans = '—'; let street = '—'; let city = '—'; let website = '—'; const nodeType = nodeTypes.find(nodeType => nodeType.identifier === node.nodeType); if (nodeType != null) { const category = categories.get(nodeType.category); nodeTypeTrans = I18n.t(`poi.name.${category.identifier}.${nodeType.identifier}`); } if (node.street != null && node.housenumber != null) { street = `${node.street} ${node.housenumber}`; } if (node.postcode != null && node.city != null) { city = `${node.postcode} ${node.city}`; } const icon = nodeType != null ? nodeType.icon : null; const location = node.location(); const marker = ( <Marker position={location} wheelchair={node.wheelchair} icon={icon} /> ); if (node.website != null) { website = <a href={node.website}>{node.website}</a>; } return ( <Section section={OVERVIEW} onClickAction={onClickAction} actionLabelScope="actions.save" loading={loading}> <div> <h3>Name & Kategorie:</h3> <dl className="nodes-new-content-section--overview-list"> <dt><I18n scope="activerecord.attributes.poi.name" />:</dt> <dd>{node.name || '—'}</dd> <dt><I18n scope="activerecord.attributes.poi.type" />:</dt> <dd>{nodeTypeTrans}</dd> </dl> <Link to={Routes.newNodeSectionPath({ section: NAME_CATEGORY })} className="nodes-new-content-section--overview-edit" > <I18n scope="nodes.node_edit.edit" /> <i className="icon-chevron-right" /> </Link> </div> <div> <h3><I18n scope="activerecord.attributes.poi.address" />:</h3> <dl className="nodes-new-content-section--overview-list"> <dt><I18n scope="activerecord.attributes.poi.address_street" />:</dt> <dd>{street}</dd> <dt><I18n scope="activerecord.attributes.poi.address_city" />:</dt> <dd>{city}</dd> </dl> <Map center={location} zoom={16} dragging={false} touchZoom={false} doubleClickZoom={false} scrollWheelZoom={false} keyboard={false} zoomControl={false} className="nodes-new-content-section--overview-map" > {marker} </Map> <Link to={Routes.newNodeSectionPath({ section: ADDRESS })} className="nodes-new-content-section--overview-edit" > <I18n scope="nodes.node_edit.edit" /> <i className="icon-chevron-right" /> </Link> </div> <div> <h3><I18n scope="nodes.new.form.section.accessibility.name" />:</h3> <dl className="nodes-new-content-section--overview-list"> <dt>Status:</dt> <dd><I18n scope={`wheelchairstatus.${node.wheelchair}`} className={node.wheelchair} /></dd> <dt>WC-Status:</dt> <dd><I18n scope={`toiletstatus.${node.wheelchairToilet}`} className={node.wheelchairToilet} /></dd> </dl> <Link to={Routes.newNodeSectionPath({ section: ACCESSIBILITY })} className="nodes-new-content-section--overview-edit" > <I18n scope="nodes.node_edit.edit" /> <i className="icon-chevron-right" /> </Link> </div> <div> <h3><I18n scope="nodes.new.form.section.contact.name" />:</h3> <dl className="nodes-new-content-section--overview-list"> <dt><I18n scope="activerecord.attributes.poi.website" />:</dt> <dd>{website}</dd> <dt><I18n scope="activerecord.attributes.poi.phone" />:</dt> <dd>{node.phone || '—'}</dd> </dl> <Link to={Routes.newNodeSectionPath({ section: CONTACT })} className="nodes-new-content-section--overview-edit" > <I18n scope="nodes.node_edit.edit" /> <i className="icon-chevron-right" /> </Link> </div> </Section> ); } OverviewSection.propTypes = { onClickAction: func.isRequired, node: node.isRequired, loading: bool.isRequired, nodeTypes: immutableMapOf(nodeType), categories: immutableMapOf(category) }; const mapStateToProps = createStructuredSelector({ node: selectors.node, nodeTypes: nodeTypesSelector, categories: categoriesSelector, loading: selectors.loading }); function mapDispatchToProps(dispatch) { return bindActionCreators({ onClickAction: saveNode }, dispatch); } export default connect( mapStateToProps, mapDispatchToProps )(OverviewSection);
packages/material-ui-icons/src/BallotSharp.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M13 9.5h5v-2h-5v2zm0 7h5v-2h-5v2zm8 4.5H3V3h18v18zM6 11h5V6H6v5zm1-4h3v3H7V7zM6 18h5v-5H6v5zm1-4h3v3H7v-3z" /> , 'BallotSharp');
src/fe/components/FourOhFour/index.js
searsaw/react-router-demo
import React from 'react'; import { Header } from 'semantic-ui-react'; import Page from '../Page'; import styles from './styles.css'; const FourOhFour = () => ( <Page> <div className={styles.container}> <Header as="h1">404</Header> <p>Uh oh! Are you sure you wanted to go here?</p> </div> </Page> ); export default FourOhFour;
packages/icons/src/md/editor/Functions.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdFunctions(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <polygon points="36 8 12 8 12 12 25 24 12 36 12 40 36 40 36 34 22 34 32 24 22 14 36 14" /> </IconBase> ); } export default MdFunctions;
src/components/movies/detail.js
scholtzm/arnold
import React, { Component } from 'react'; import { Modal, Image, Button, Rating } from 'semantic-ui-react'; import YouTube from 'react-youtube'; import PlayMovieButton from './play-button.js'; class MovieDetail extends Component { render() { const movie = this.props.movie; const runtimeHours = Math.floor(movie.runtime / 60 / 60); const runtimeMinutes = Math.floor((movie.runtime % (runtimeHours * 60 * 60)) / 60); const runtime = `${runtimeHours} hour${runtimeHours > 1 ? 's' : ''} ${runtimeMinutes} minute${runtimeMinutes > 1 ? 's' : ''}`; return ( <Modal open={this.props.active} onClose={this.props.hide}> <Modal.Header>{movie.originaltitle} ({movie.year})</Modal.Header> <Modal.Content image> <Image wrapped bordered shape='rounded' className='medium' src={movie.thumbnail} /> <Modal.Description> <div>{movie.plot}</div> <div style={{padding: '10px 0'}}> <div><b>Directed by:</b> {movie.director[0]}</div> <div><b>Year:</b> {movie.year}</div> <div><b>Rating:</b> {movie.rating.toFixed(1)} <Rating defaultRating={Math.round(movie.rating)} maxRating={10} icon='star' disabled /></div> <div><b>Runtime:</b> {runtime}</div> </div> <div><b>Trailer:</b></div> <YouTube videoId={movie.youtubeId} opts={{width: '600'}} /> </Modal.Description> </Modal.Content> <Modal.Actions> <PlayMovieButton movie={movie} /> <Button color='black' onClick={this.props.hide}> Close </Button> </Modal.Actions> </Modal> ); } } export default MovieDetail;
ui/src/plugins/epl-dashboard/components/SystemOverview.js
mkacper/erlangpl
// @flow import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Row, Col, ListGroup, ListGroupItem } from 'react-bootstrap'; import Measure from 'react-measure'; import Chart from './SystemOverviewChart'; import './SystemOverview.css'; class SystemOverview extends Component { state: { width: number }; constructor(props) { super(props); this.state = { width: 0 }; } render() { const { info, overview } = this.props; const mem = ['KB', 'MB', 'GB']; const memory = mem.reduce( (acc, a) => { if (acc.v > 1000) { return { v: acc.v / 1000, t: a }; } else { return acc; } }, { v: parseInt(info.memoryTotal, 10), t: 'B' } ); const systemOverview = [ ['Throughput', info.receive ? `${info.receive.count} msg` : undefined], ['Throughput', info.receive ? `${info.receive.sizes} B` : undefined], ['Processes', info.processCount], ['Spawns', info.spawn ? info.spawn.count : undefined], ['Exits', info.exit ? info.exit.count : undefined], ['Abnormal Exits', info.exit ? info.exit.abnormal : undefined], [ 'Memory', info.memoryTotal ? `${memory.v.toFixed(2)} ${memory.t}` : undefined ] ]; const throughputData = overview.receive.map(a => ({ name: 'Throughput (msg)', count: parseInt(a.count, 10) })); const memoryData = overview.memoryTotal.map(a => { return { name: 'Memory (MB)', usage: Number((parseInt(a, 10) / 1000000).toFixed(2)) }; }); const processesData = overview.processCount.map(a => ({ name: 'Processes', count: parseInt(a, 10) })); const maxProcesses = Math.max(...overview.processCount); const dimensions = { width: this.state.width - this.state.width / 10, height: 210 }; return ( <Row className="SystemOverview"> <Col xs={4}> <h5 className="SystemInfo-list-header"> Overview (last 5 sec) </h5> <ListGroup className="SystemInfo-list"> {systemOverview.map(([name, value], i) => ( <ListGroupItem key={i}> <span>{name}</span> <span className="value">{value || 'N/A'}</span> </ListGroupItem> ))} </ListGroup> </Col> <Measure includeMargin={false} onMeasure={({ width }) => this.setState({ width })} > <Col xs={8} className="charts"> <Chart title="Memory usage" height={dimensions.height} width={dimensions.width} data={memoryData} color="#8FBF47" dataKey="usage" domain={['dataMin', 'dataMax']} loaderText="Gathering memory usage data" /> <Chart title="Processes" height={dimensions.height} width={dimensions.width} data={processesData} color="#227A50" dataKey="count" domain={[ `dataMin - ${Math.floor(maxProcesses / 5)}`, `dataMax + ${Math.floor(maxProcesses / 5)}` ]} loaderText="Gathering processes data" /> <Chart title="Throughput" height={dimensions.height} width={dimensions.width} data={throughputData} color="#1F79B7" dataKey="count" loaderText="Gathering throughput data" /> </Col> </Measure> </Row> ); } } export default connect(state => { return { info: state.eplDashboard.systemInfo, overview: state.eplDashboard.systemOverview }; }, {})(SystemOverview);
test/Stories.js
insin/react-heatpack
var React = require('react') async function fetchStories(subreddit) { var req = await window.fetch(`https://www.reddit.com/r/${subreddit}.json`, {mode: 'cors'}) var json = await req.json() return json } var SUBREDDITS = ['javascript', 'programming', 'deepdream'] var Stories = React.createClass({ getInitialState() { return { loading: false, stories: [], subreddit: 'javascript' } }, componentDidMount() { this.updateStories() }, async updateStories() { var loadingTimeout = setTimeout(() => { this.setState({loading: true}) loadingTimeout = null }, 333) try { var data = await fetchStories(this.state.subreddit) this.setState({stories: data.data.children.map(child => child.data)}) } catch (e) { // pass } if (loadingTimeout) { clearTimeout(loadingTimeout) } else { this.setState({loading: false}) } }, handleChange(e) { var subreddit = e.target.value this.setState({subreddit}, this.updateStories) }, render() { return <div className="Stories"> <h2> <select disabled={this.state.loading} value={this.state.subreddit} onChange={this.handleChange}> {SUBREDDITS.map(subreddit => <option key={subreddit}>{subreddit}</option>)} </select>{' '} Stories </h2> {this.state.loading && <h3>Loading...</h3>} <ol style={{opacity: this.state.loading ? '.5' : '1'}}> {this.state.stories.map(story => <li key={story.id}>{story.title}</li>)} </ol> </div> } }) module.exports = Stories
ajax/libs/rxjs/2.3.14/rx.compat.js
luhad/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; Rx.iterator = $iterator$; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; 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 slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; 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) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return {}.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { 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].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (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); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); 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, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { var notification = new Notification('E'); notification.exception = e; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @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.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } /** * 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(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (err) { var self = this; this.queue.push(function () { self.observer.onError(err); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver() { __super__.apply(this, arguments); } 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(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @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(arguments.length === 2 ? 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, arguments.length === 2 ? 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, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { if (!subject.isDisposed) { subject.onNext(value); subject.onCompleted(); } }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next; try { next = it.next(); } catch (e) { observer.onError(e); return; } if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = !!list.charAt ? list.charAt(i) : list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * 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 = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.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.catchException = Observable.catchError = Observable['catch'] = function () { return enumerableOf(argsOrArray(arguments, 0)).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * @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 () { return enumerableOf(argsOrArray(arguments, 0)).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && observer.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; activeCount === 0 && observer.onCompleted(); })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll = function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(innerSubscription); isStopped && group.length === 1 && observer.onCompleted(); })); }, observer.onError.bind(observer), function () { isStopped = true; group.length === 1 && observer.onCompleted(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), 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 (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(this.subscribe.bind(this)); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (onError) { try { onError(err); } catch (e) { observer.onError(e); } } observer.onError(err); }, function () { if (onCompleted) { try { onCompleted(); } catch (e) { observer.onError(e); } } observer.onCompleted(); }); }); }; /** * 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(arguments.length === 2 ? 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, arguments.length === 2 ? 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, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { !hasValue && hasSeed && observer.onNext(seed); observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && observer.onNext(q.shift()); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableOf([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new Error(argumentOutOfRange); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new Error(argumentOutOfRange); } 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; }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i, source); isPromise(result) && (result = observableFromPromise(result)); (Array.isArray(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 (typeof selector === 'function' && typeof resultSelector === 'function') { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (Array.isArray(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return typeof selector === 'function' ? 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; 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(); }); }).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { observer.onError(e); return; } } hashSet.push(key) && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} prop The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (prop) { return this.map(function (x) { return x[prop]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i, source); isPromise(result) && (result = observableFromPromise(result)); (Array.isArray(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {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 (typeof selector === 'function' && typeof resultSelector === 'function') { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (Array.isArray(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return typeof selector === 'function' ? 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(); }); }).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 Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (observer) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } running && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new RangeError(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining-- > 0) { observer.onNext(x); remaining === 0 && observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } shouldRun && observer.onNext(value); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * 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); } ); }); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
src/components/footer.js
mkleung/mkleung.github.io
import React from 'react'; const Footer = () => ( <div> <footer className='footer'> <div className='content has-text-centered'> <div className='socialMediaIcons'> <span className='icon-wrapper'> <a target='_blank' rel='noopener noreferrer' href='https://codepen.io/mkleung/'> <svg className='icon' role='img' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'> <title>CodePen icon</title> <path d='M24 8.182l-.018-.087-.017-.05c-.01-.024-.018-.05-.03-.075-.003-.018-.015-.034-.02-.05l-.035-.067-.03-.05-.044-.06-.046-.045-.06-.045-.046-.03-.06-.044-.044-.04-.015-.02L12.58.19c-.347-.232-.796-.232-1.142 0L.453 7.502l-.015.015-.044.035-.06.05-.038.04-.05.056-.037.045-.05.06c-.02.017-.03.03-.03.046l-.05.06-.02.06c-.02.01-.02.04-.03.07l-.01.05C0 8.12 0 8.15 0 8.18v7.497c0 .044.003.09.01.135l.01.046c.005.03.01.06.02.086l.015.05c.01.027.016.053.027.075l.022.05c0 .01.015.04.03.06l.03.04c.015.01.03.04.045.06l.03.04.04.04c.01.013.01.03.03.03l.06.042.04.03.01.014 10.97 7.33c.164.12.375.163.57.163s.39-.06.57-.18l10.99-7.28.014-.01.046-.037.06-.043.048-.036.052-.058.033-.045.04-.06.03-.05.03-.07.016-.052.03-.077.015-.045.03-.08v-7.5c0-.05 0-.095-.016-.14l-.014-.045.044.003zm-11.99 6.28l-3.65-2.44 3.65-2.442 3.65 2.44-3.65 2.44zm-1.034-6.674l-4.473 2.99L2.89 8.362l8.086-5.39V7.79zm-6.33 4.233l-2.582 1.73V10.3l2.582 1.726zm1.857 1.25l4.473 2.99v4.82L2.89 15.69l3.618-2.417v-.004zm6.537 2.99l4.474-2.98 3.613 2.42-8.087 5.39v-4.82zm6.33-4.23l2.583-1.72v3.456l-2.583-1.73zm-1.855-1.24L13.042 7.8V2.97l8.085 5.39-3.612 2.415v.003z' /> </svg> </a> </span> <span className='icon-wrapper'> <a target='_blank' rel='noopener noreferrer' href='https://www.instagram.com/morningmike/'> <svg className='icon' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24' fill='#000000'> <path d='M 8 3 C 5.243 3 3 5.243 3 8 L 3 16 C 3 18.757 5.243 21 8 21 L 16 21 C 18.757 21 21 18.757 21 16 L 21 8 C 21 5.243 18.757 3 16 3 L 8 3 z M 8 5 L 16 5 C 17.654 5 19 6.346 19 8 L 19 16 C 19 17.654 17.654 19 16 19 L 8 19 C 6.346 19 5 17.654 5 16 L 5 8 C 5 6.346 6.346 5 8 5 z M 17 6 A 1 1 0 0 0 16 7 A 1 1 0 0 0 17 8 A 1 1 0 0 0 18 7 A 1 1 0 0 0 17 6 z M 12 7 C 9.243 7 7 9.243 7 12 C 7 14.757 9.243 17 12 17 C 14.757 17 17 14.757 17 12 C 17 9.243 14.757 7 12 7 z M 12 9 C 13.654 9 15 10.346 15 12 C 15 13.654 13.654 15 12 15 C 10.346 15 9 13.654 9 12 C 9 10.346 10.346 9 12 9 z' /> </svg> </a> </span> <span className='icon-wrapper'> <a target='_blank' rel='noopener noreferrer' href='https://www.linkedin.com/in/leungpak/'> <svg className='icon' role='img' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'> <title>LinkedIn icon</title> <path d='M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z' /> </svg> </a> </span> <span className='icon-wrapper'> <a target='_blank' rel='noopener noreferrer' href='https://github.com/mkleung'> <svg className='icon' role='img' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'> <title>GitHub icon</title> <path d='M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12' /> </svg> </a> </span> {/* <span className="has-margin-right-25"> <a target="_blank" rel="noopener noreferrer" href="https://dribbble.com/mkleung"> <svg className="icon" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Dribbble icon</title><path d="M12 24C5.385 24 0 18.615 0 12S5.385 0 12 0s12 5.385 12 12-5.385 12-12 12zm10.12-10.358c-.35-.11-3.17-.953-6.384-.438 1.34 3.684 1.887 6.684 1.992 7.308 2.3-1.555 3.936-4.02 4.395-6.87zm-6.115 7.808c-.153-.9-.75-4.032-2.19-7.77l-.066.02c-5.79 2.015-7.86 6.025-8.04 6.4 1.73 1.358 3.92 2.166 6.29 2.166 1.42 0 2.77-.29 4-.814zm-11.62-2.58c.232-.4 3.045-5.055 8.332-6.765.135-.045.27-.084.405-.12-.26-.585-.54-1.167-.832-1.74C7.17 11.775 2.206 11.71 1.756 11.7l-.004.312c0 2.633.998 5.037 2.634 6.855zm-2.42-8.955c.46.008 4.683.026 9.477-1.248-1.698-3.018-3.53-5.558-3.8-5.928-2.868 1.35-5.01 3.99-5.676 7.17zM9.6 2.052c.282.38 2.145 2.914 3.822 6 3.645-1.365 5.19-3.44 5.373-3.702-1.81-1.61-4.19-2.586-6.795-2.586-.825 0-1.63.1-2.4.285zm10.335 3.483c-.218.29-1.935 2.493-5.724 4.04.24.49.47.985.68 1.486.08.18.15.36.22.53 3.41-.43 6.8.26 7.14.33-.02-2.42-.88-4.64-2.31-6.38z" /></svg> </a> </span> */} </div> <p> Built with <a rel="noopener noreferrer" target="_blank" href="https://www.gatsbyjs.org/">Gatsby</a> and <a target="_blank" rel="noopener noreferrer" href="https://www.netlify.com/">Netlify</a></p> <br /> </div> </footer> </div> ); export default Footer;
app/addons/documents/routes-index-editor.js
benkeen/couchdb-fauxton
// Licensed under the Apache License, Version 2.0 (the 'License'); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import app from "../../app"; import FauxtonAPI from "../../core/api"; import Helpers from "./helpers"; import BaseRoute from "./shared-routes"; import Documents from "./resources"; import IndexEditorComponents from "./index-editor/components.react"; import ActionsIndexEditor from "./index-editor/actions"; import Databases from "../databases/base"; import Components from "../fauxton/components"; import IndexResultsStores from "./index-results/stores"; import IndexResultsActions from "./index-results/actions"; import IndexResultsComponents from "./index-results/index-results.components.react"; import ReactPagination from "./pagination/pagination.react"; import ReactHeader from "./header/header.react"; import ReactHeaderActions from "./header/header.actions"; import SidebarActions from "./sidebar/actions"; import RightAllDocsHeader from './rightalldocsheader.react'; var IndexEditorAndResults = BaseRoute.extend({ layout: 'with_tabs_sidebar', routes: { 'database/:database/new_view': { route: 'createView', roles: ['fx_loggedIn'] }, 'database/:database/new_view/:designDoc': { route: 'createView', roles: ['fx_loggedIn'] }, 'database/:database/_design/:ddoc/_view/:view': { route: 'showView', roles: ['fx_loggedIn'] }, 'database/:database/_design/:ddoc/_view/:view/edit': { route: 'editView', roles: ['fx_loggedIn'] } }, initialize: function (route, masterLayout, options) { var databaseName = options[0]; this.databaseName = databaseName; this.database = new Databases.Model({id: databaseName}); this.allDatabases = new Databases.List(); this.createDesignDocsCollection(); this.addLeftHeader(); this.addSidebar(); this.setComponent("#right-header", RightAllDocsHeader, { database: this.database }); }, establish: function () { return [ this.designDocs.fetch({ reset: true }), this.allDatabases.fetchOnce() ]; }, showView: function (databaseName, ddoc, viewName) { var params = this.createParams(), urlParams = params.urlParams, docParams = params.docParams, decodeDdoc = decodeURIComponent(ddoc); viewName = viewName.replace(/\?.*$/, ''); this.setComponent('#footer', ReactPagination.Footer); this.indexedDocs = new Documents.IndexCollection(null, { database: this.database, design: decodeDdoc, view: viewName, params: docParams, paging: { pageSize: IndexResultsStores.indexResultsStore.getPerPage() } }); ActionsIndexEditor.clearIndex(); IndexResultsActions.newResultsList({ collection: this.indexedDocs, bulkCollection: new Documents.BulkDeleteDocCollection([], { databaseId: this.database.safeID() }), }); ActionsIndexEditor.fetchDesignDocsBeforeEdit({ viewName: viewName, newView: false, database: this.database, designDocs: this.designDocs, designDocId: '_design/' + decodeDdoc }); SidebarActions.selectNavItem('designDoc', { designDocName: ddoc, designDocSection: 'Views', indexName: viewName }); this.setComponent('#react-headerbar', ReactHeader.BulkDocumentHeaderController, {showIncludeAllDocs: true}); this.setComponent('#dashboard-lower-content', IndexResultsComponents.List); this.apiUrl = function () { return [this.indexedDocs.urlRef('apiurl'), FauxtonAPI.constants.DOC_URLS.GENERAL]; }; this.showQueryOptions(urlParams, ddoc, viewName); }, createView: function (database, _designDoc) { var newDesignDoc = true; var designDoc = 'new-doc'; if (_designDoc) { designDoc = '_design/' + _designDoc; newDesignDoc = false; } ActionsIndexEditor.fetchDesignDocsBeforeEdit({ viewName: 'new-view', newView: true, database: this.database, designDocs: this.designDocs, designDocId: designDoc, newDesignDoc: newDesignDoc }); this.removeComponent('#react-headerbar'); this.removeComponent('#footer'); this.setComponent('#dashboard-lower-content', IndexEditorComponents.EditorController); SidebarActions.selectNavItem(''); }, editView: function (databaseName, ddocName, viewName) { ActionsIndexEditor.fetchDesignDocsBeforeEdit({ viewName: viewName, newView: false, database: this.database, designDocs: this.designDocs, designDocId: '_design/' + ddocName }); SidebarActions.selectNavItem('designDoc', { designDocName: ddocName, designDocSection: 'Views', indexName: viewName }); this.apiUrl = function () { return [FauxtonAPI.urls('view', 'apiurl', databaseName, ddocName, viewName), FauxtonAPI.constants.DOC_URLS.GENERAL]; }; this.removeView('#right-header'); this.removeComponent('#react-headerbar'); this.removeComponent('#footer'); this.setComponent('#dashboard-lower-content', IndexEditorComponents.EditorController); } }); export default IndexEditorAndResults;
src/svg-icons/action/info.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionInfo = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/> </SvgIcon> ); ActionInfo = pure(ActionInfo); ActionInfo.displayName = 'ActionInfo'; export default ActionInfo;
htmlwidgets_deps/leaflet-binding-1.0.0/leaflet.js
bradleyboehmke/old_blog
function recycle(values, length, inPlace) { if (length === 0 && !inPlace) return []; if (!(values instanceof Array)) { if (inPlace) { throw new Error("Can't do in-place recycling of a non-Array value"); } values = [values]; } if (typeof(length) === 'undefined') length = values.length; var dest = inPlace ? values : []; var origLength = values.length; while (dest.length < length) { dest.push(values[dest.length % origLength]); } if (dest.length > length) { dest.splice(length, dest.length - length); } return dest; } function asArray(value) { if (value instanceof Array) return value; else return [value]; } var dataframe = (function() { var exports = {}; var DataFrame = function() { this.columns = []; this.colnames = []; this.colstrict = []; this.effectiveLength = 0; this.colindices = {}; }; DataFrame.prototype._updateCachedProperties = function() { var self = this; this.effectiveLength = 0; this.colindices = {}; $.each(this.columns, function(i, column) { self.effectiveLength = Math.max(self.effectiveLength, column.length); self.colindices[self.colnames[i]] = i; }); }; DataFrame.prototype._colIndex = function(colname) { var index = this.colindices[colname]; if (typeof(index) === 'undefined') return -1; return index; }; DataFrame.prototype.col = function(name, values, strict) { if (typeof(name) !== 'string') throw new Error('Invalid column name "' + name + '"'); var index = this._colIndex(name); if (arguments.length === 1) { if (index < 0) return null; else return recycle(this.columns[index], this.effectiveLength); } if (index < 0) { index = this.colnames.length; this.colnames.push(name); } this.columns[index] = asArray(values); this.colstrict[index] = !!strict; // TODO: Validate strictness (ensure lengths match up with other stricts) this._updateCachedProperties(); return this; }; DataFrame.prototype.cbind = function(obj, strict) { var self = this, name; $.each(obj, function(name, coldata) { self.col(name, coldata); }); return this; }; DataFrame.prototype.get = function(row, col) { var self = this; if (row > this.effectiveLength) throw new Error('Row argument was out of bounds: ' + row + ' > ' + this.effectiveLength); var colIndex = -1; if (typeof(col) === 'undefined') { var rowData = {}; $.each(this.colnames, function(i, name) { rowData[name] = self.columns[i][row % self.columns[i].length]; }); return rowData; } else if (typeof(col) === 'string') { colIndex = this._colIndex(col); } else if (typeof(col) === 'number') { colIndex = col; } if (colIndex < 0 || colIndex > this.columns.length) throw new Error('Unknown column index: ' + col); return this.columns[colIndex][row % this.columns[colIndex].length]; }; DataFrame.prototype.nrow = function() { return this.effectiveLength; }; function test() { var df = new DataFrame(); df.col("speed", [4, 4, 7, 7, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16, 16, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 20, 20, 20, 20, 20, 22, 23, 24, 24, 24, 24, 25]) .col("dist", [2, 10, 4, 22, 16, 10, 18, 26, 34, 17, 28, 14, 20, 24, 28, 26, 34, 34, 46, 26, 36, 60, 80, 20, 26, 54, 32, 40, 32, 40, 50, 42, 56, 76, 84, 36, 46, 68, 32, 48, 52, 56, 64, 66, 54, 70, 92, 93, 120, 85]) .col("color", ["yellow", "red"]) .cbind({ "Make" : ["Toyota", "Cadillac", "BMW"], "Model" : ["Corolla", "CTS", "435i"] }) ; console.log(df.get(9, "speed")); console.log(df.get(9, "dist")); console.log(df.get(9, "color")); console.log(df.get(9, "Make")); console.log(df.get(9, "Model")); console.log(df.get(9)); } return { create: function() { return new DataFrame(); } }; })(); (function() { // This class simulates a mipmap, which shrinks images by powers of two. This // stepwise reduction results in "pixel-perfect downscaling" (where every // pixel of the original image has some contribution to the downscaled image) // as opposed to a single-step downscaling which will discard a lot of data // (and with sparse images at small scales can give very surprising results). function Mipmapper(img) { this._layers = [img]; } // The various functions on this class take a callback function BUT MAY OR MAY // NOT actually behave asynchronously. Mipmapper.prototype.getBySize = function(desiredWidth, desiredHeight, callback) { var self = this; var i = 0; var lastImg = this._layers[0]; function testNext() { self.getByIndex(i, function(img) { // If current image is invalid (i.e. too small to be rendered) or // it's smaller than what we wanted, return the last known good image. if (!img || img.width < desiredWidth || img.height < desiredHeight) { callback(lastImg); return; } else { lastImg = img; i++; testNext(); return; } }); } testNext(); }; Mipmapper.prototype.getByIndex = function(i, callback) { var self = this; if (this._layers[i]) { callback(this._layers[i]); return; } this.getByIndex(i-1, function(prevImg) { if (!prevImg) { // prevImg could not be calculated (too small, possibly) callback(null); return; } if (prevImg.width < 2 || prevImg.height < 2) { // Can't reduce this image any further callback(null); return; } // If reduce ever becomes truly asynchronous, we should stuff a promise or // something into self._layers[i] before calling self.reduce(), to prevent // redundant reduce operations from happening. self.reduce(prevImg, function(reducedImg) { self._layers[i] = reducedImg; callback(reducedImg); return; }); }); }; Mipmapper.prototype.reduce = function(img, callback) { var imgDataCanvas = document.createElement("canvas"); imgDataCanvas.width = Math.ceil(img.width / 2); imgDataCanvas.height = Math.ceil(img.height / 2); imgDataCanvas.style.display = "none"; document.body.appendChild(imgDataCanvas); try { var imgDataCtx = imgDataCanvas.getContext("2d"); imgDataCtx.drawImage(img, 0, 0, img.width/2, img.height/2); callback(imgDataCanvas); } finally { document.body.removeChild(imgDataCanvas); } }; function LayerManager(map) { this._map = map; // BEGIN layer indices // {<groupname>: {<stamp>: layer}} this._byGroup = {}; // {<categoryName>: {<stamp>: layer}} this._byCategory = {}; // {<categoryName_layerId>: layer} this._byLayerId = {}; // {<stamp>: { // "group": <groupname>, // "layerId": <layerId>, // "category": <category>, // "container": <container> // } // } this._byStamp = {}; // END layer indices // {<categoryName>: L.layerGroup} this._categoryContainers = {}; // {<groupName>: L.layerGroup} this._groupContainers = {}; } LayerManager.prototype.addLayer = function(layer, category, layerId, group) { // Was a group provided? var hasId = typeof(layerId) === "string"; var grouped = typeof(group) === "string"; var stamp = L.Util.stamp(layer); // This will be the default layer group to add the layer to. // We may overwrite this var before using it (i.e. if a group is assigned). // This one liner creates the _categoryContainers[category] entry if it // doesn't already exist. var container = this._categoryContainers[category] = this._categoryContainers[category] || L.layerGroup().addTo(this._map); var oldLayer = null; if (hasId) { // First, remove any layer with the same category and layerId var prefixedLayerId = this._layerIdKey(category, layerId); oldLayer = this._byLayerId[prefixedLayerId]; if (oldLayer) { this._removeLayer(oldLayer); } // Update layerId index this._byLayerId[prefixedLayerId] = layer; } // Update group index if (grouped) { this._byGroup[group] = this._byGroup[group] || {}; this._byGroup[group][stamp] = layer; // Since a group is assigned, don't add the layer to the category's layer // group; instead, use the group's layer group. // This one liner creates the _groupContainers[group] entry if it doesn't // already exist. container = this.getLayerGroup(group, true); } // Update category index this._byCategory[category] = this._byCategory[category] || {}; this._byCategory[category][stamp] = layer; // Update stamp index this._byStamp[stamp] = { layer: layer, group: group, layerId: layerId, category: category, container: container }; // Add to container container.addLayer(layer); return oldLayer; }; LayerManager.prototype.getLayer = function(category, layerId) { return this._byLayerId[this._layerIdKey(category, layerId)]; }; LayerManager.prototype.removeLayer = function(category, layerId) { // Find layer info var layer = this._byLayerId[this._layerIdKey(category, layerId)]; if (!layer) { return false; } this._removeLayer(layer); return true; }; LayerManager.prototype.clearLayers = function(category) { var self = this; // Find all layers in _byCategory[category] var catTable = this._byCategory[category]; if (!catTable) { return false; } // Remove all layers. Make copy of keys to avoid mutating the collection // behind the iterator you're accessing. var stamps = []; $.each(catTable, function(k, v) { stamps.push(k); }); $.each(stamps, function(i, stamp) { self._removeLayer(stamp); }); }; LayerManager.prototype.getLayerGroup = function(group, ensureExists) { var g = this._groupContainers[group]; if (ensureExists && !g) { this._byGroup[group] = this._byGroup[group] || {}; g = this._groupContainers[group] = L.layerGroup(); g.groupname = group; g.addTo(this._map); } return g; }; LayerManager.prototype.getGroupNameFromLayerGroup = function(layerGroup) { return layerGroup.groupname; }; LayerManager.prototype.getVisibleGroups = function() { var self = this; var result = []; $.each(this._groupContainers, function(k, v) { if (self._map.hasLayer(v)) { result.push(k); } }); return result; }; LayerManager.prototype.clearGroup = function(group) { var self = this; // Find all layers in _byGroup[group] var groupTable = this._byGroup[group]; if (!groupTable) { return false; } // Remove all layers. Make copy of keys to avoid mutating the collection // behind the iterator you're accessing. var stamps = []; $.each(groupTable, function(k, v) { stamps.push(k); }); $.each(stamps, function(i, stamp) { self._removeLayer(stamp); }); }; LayerManager.prototype.clear = function() { function clearLayerGroup(key, layerGroup) { layerGroup.clearLayers(); } // Clear all indices and layerGroups this._byGroup = {}; this._byCategory = {}; this._byLayerId = {}; this._byStamp = {}; $.each(this._categoryContainers, clearLayerGroup); this._categoryContainers = {}; $.each(this._groupContainers, clearLayerGroup); this._groupContainers = {}; }; LayerManager.prototype._removeLayer = function(layer) { var stamp; if (typeof(layer) === "string") { stamp = layer; } else { stamp = L.Util.stamp(layer); } var layerInfo = this._byStamp[stamp]; if (!layerInfo) { return false; } layerInfo.container.removeLayer(stamp); if (typeof(layerInfo.group) === "string") { delete this._byGroup[layerInfo.group][stamp]; } if (typeof(layerInfo.layerId) === "string") { delete this._byLayerId[this._layerIdKey(layerInfo.category, layerInfo.layerId)]; } delete this._byCategory[layerInfo.category][stamp]; delete this._byStamp[stamp]; }; LayerManager.prototype._layerIdKey = function(category, layerId) { return category + "\n" + layerId; }; function ControlStore(map) { this._controlsNoId = []; this._controlsById = {}; this._map = map } ControlStore.prototype.add = function(control, id, html) { if (typeof(id) !== 'undefined' && id !== null) { if (this._controlsById[id]) { this._map.removeControl(this._controlsById[id]); } this._controlsById[id] = control; } else { this._controlsNoId.push(control) } this._map.addControl(control); }; ControlStore.prototype.remove = function(id) { if (this._controlsById[id]) { var control = this._controlsById[id]; this._map.removeControl(control); delete this._controlsById[id]; } }; ControlStore.prototype.clear = function() { for (var i = 0; i < this._controlsNoId.length; i++) { var control = this._controlsNoId[i]; this._map.removeControl(control); }; this._controlsNoId = []; for (var key in this._controlsById) { var control = this._controlsById[key]; this._map.removeControl(control) } this._controlsById = {} } function ClusterLayerStore(group) { this._layers = {}; this._group = group; } ClusterLayerStore.prototype.add = function(layer, id) { if (typeof(id) !== 'undefined' && id !== null) { if (this._layers[id]) { this._group.removeLayer(this._layers[id]); } this._layers[id] = layer; } this._group.addLayer(layer); }; ClusterLayerStore.prototype.remove = function(id) { if (typeof(id) === 'undefined' || id === null) { return; } id = asArray(id); for (var i = 0; i < id.length; i++) { if (this._layers[id[i]]) { this._group.removeLayer(this._layers[id[i]]); delete this._layers[id[i]]; } } }; ClusterLayerStore.prototype.clear = function() { this._layers = {}; this._group.clearLayers(); }; function mouseHandler(mapId, layerId, group, eventName, extraInfo) { return function(e) { if (!HTMLWidgets.shinyMode) return; var eventInfo = $.extend( { id: layerId, '.nonce': Math.random() // force reactivity }, group !== null ? {group: group} : null, e.target.getLatLng ? e.target.getLatLng() : e.latlng, extraInfo ); Shiny.onInputChange(mapId + '_' + eventName, eventInfo); }; } // Send updated bounds back to app. Takes a leaflet event object as input. function updateBounds(map) { var id = map.getContainer().id; var bounds = map.getBounds(); Shiny.onInputChange(id + '_bounds', { north: bounds.getNorthEast().lat, east: bounds.getNorthEast().lng, south: bounds.getSouthWest().lat, west: bounds.getSouthWest().lng }); Shiny.onInputChange(id + '_zoom', map.getZoom()); } window.LeafletWidget = {}; var methods = window.LeafletWidget.methods = {}; methods.clearGroup = function(group) { var self = this; $.each(asArray(group), function(i, v) { self.layerManager.clearGroup(v); }); }; methods.setView = function(center, zoom, options) { this.setView(center, zoom, options); }; methods.fitBounds = function(lat1, lng1, lat2, lng2) { this.fitBounds([ [lat1, lng1], [lat2, lng2] ]); }; methods.setMaxBounds = function(lat1, lng1, lat2, lng2) { this.setMaxBounds([ [lat1, lng1], [lat2, lng2] ]); }; methods.addPopups = function(lat, lng, popup, layerId, group, options) { var df = dataframe.create() .col('lat', lat) .col('lng', lng) .col('popup', popup) .col('layerId', layerId) .col('group', group) .cbind(options); for (var i = 0; i < df.nrow(); i++) { (function() { var popup = L.popup(df.get(i)) .setLatLng([df.get(i, 'lat'), df.get(i, 'lng')]) .setContent(df.get(i, 'popup')); var thisId = df.get(i, 'layerId'); var thisGroup = df.get(i, 'group'); this.layerManager.addLayer(popup, "popup", thisId, thisGroup); popup.on('click', mouseHandler(this.id, thisId, thisGroup, 'popup_click'), this); popup.on('mouseover', mouseHandler(this.id, thisId, thisGroup, 'popup_mouseover'), this); popup.on('mouseout', mouseHandler(this.id, thisId, thisGroup, 'popup_mouseout'), this); }).call(this); } }; methods.removePopup = function(layerId) { this.layerManager.removeLayer("popup", layerId); }; methods.clearPopups = function() { this.layerManager.clearLayers("popup"); }; methods.addTiles = function(urlTemplate, layerId, group, options) { this.layerManager.addLayer(L.tileLayer(urlTemplate, options), "tile", layerId, group); }; methods.removeTiles = function(layerId) { this.layerManager.removeLayer("tile", layerId); }; methods.clearTiles = function() { this.layerManager.clearLayers("tile"); }; methods.addWMSTiles = function(baseUrl, layerId, group, options) { this.layerManager.addLayer(L.tileLayer.wms(baseUrl, options), "tile", layerId, group); }; // Given: // {data: ["a", "b", "c"], index: [0, 1, 0, 2]} // returns: // ["a", "b", "a", "c"] function unpackStrings(iconset) { if (!iconset) { return iconset; } if (typeof(iconset.index) === 'undefined') { return iconset; } iconset.data = asArray(iconset.data); iconset.index = asArray(iconset.index); return $.map(iconset.index, function(e, i) { return iconset.data[e]; }); } function addMarkers(map, df, group, clusterOptions, clusterId, markerFunc) { (function() { var clusterGroup = this.layerManager.getLayer("cluster", clusterId), cluster = clusterOptions !== null; if (cluster && !clusterGroup) { clusterGroup = L.markerClusterGroup(clusterOptions); clusterGroup.clusterLayerStore = new ClusterLayerStore(clusterGroup); } var extraInfo = cluster ? { clusterId: clusterId } : {}; for (var i = 0; i < df.nrow(); i++) { (function() { var marker = markerFunc(df, i); var thisId = df.get(i, 'layerId'); var thisGroup = cluster ? null : df.get(i, 'group'); if (cluster) { clusterGroup.clusterLayerStore.add(marker, thisId); } else { this.layerManager.addLayer(marker, "marker", thisId, thisGroup); } var popup = df.get(i, 'popup'); if (popup !== null) marker.bindPopup(popup); marker.on('click', mouseHandler(this.id, thisId, thisGroup, 'marker_click', extraInfo), this); marker.on('mouseover', mouseHandler(this.id, thisId, thisGroup, 'marker_mouseover', extraInfo), this); marker.on('mouseout', mouseHandler(this.id, thisId, thisGroup, 'marker_mouseout', extraInfo), this); }).call(this); } if (cluster) { this.layerManager.addLayer(clusterGroup, "cluster", clusterId, group); } }).call(map); } methods.addMarkers = function(lat, lng, icon, layerId, group, options, popup, clusterOptions, clusterId) { if (icon) { // Unpack icons icon.iconUrl = unpackStrings(icon.iconUrl); icon.iconRetinaUrl = unpackStrings(icon.iconRetinaUrl); icon.shadowUrl = unpackStrings(icon.shadowUrl); icon.shadowRetinaUrl = unpackStrings(icon.shadowRetinaUrl); // This cbinds the icon URLs and any other icon options; they're all // present on the icon object. var icondf = dataframe.create().cbind(icon); // Constructs an icon from a specified row of the icon dataframe. var getIcon = function(i) { var opts = icondf.get(i); if (!opts.iconUrl) { return new L.Icon.Default(); } // Composite options (like points or sizes) are passed from R with each // individual component as its own option. We need to combine them now // into their composite form. if (opts.iconWidth) { opts.iconSize = [opts.iconWidth, opts.iconHeight]; } if (opts.shadowWidth) { opts.shadowSize = [opts.shadowWidth, opts.shadowHeight]; } if (opts.iconAnchorX) { opts.iconAnchor = [opts.iconAnchorX, opts.iconAnchorY]; } if (opts.shadowAnchorX) { opts.shadowAnchor = [opts.shadowAnchorX, opts.shadowAnchorY]; } if (opts.popupAnchorX) { opts.popupAnchor = [opts.popupAnchorX, opts.popupAnchorY]; } return new L.Icon(opts); }; } var df = dataframe.create() .col('lat', lat) .col('lng', lng) .col('layerId', layerId) .col('group', group) .col('popup', popup) .cbind(options); if (icon) icondf.effectiveLength = df.nrow(); addMarkers(this, df, group, clusterOptions, clusterId, function(df, i) { var options = df.get(i); if (icon) options.icon = getIcon(i); return L.marker([df.get(i, 'lat'), df.get(i, 'lng')], options); }); }; addLayers = function(map, category, df, layerFunc) { for (var i = 0; i < df.nrow(); i++) { (function() { var layer = layerFunc(df, i); var thisId = df.get(i, 'layerId'); var thisGroup = df.get(i, 'group'); this.layerManager.addLayer(layer, category, thisId, thisGroup); if (layer.bindPopup) { var popup = df.get(i, 'popup'); if (popup !== null) layer.bindPopup(popup); } layer.on('click', mouseHandler(this.id, thisId, thisGroup, category + '_click'), this); layer.on('mouseover', mouseHandler(this.id, thisId, thisGroup, category + '_mouseover'), this); layer.on('mouseout', mouseHandler(this.id, thisId, thisGroup, category + '_mouseout'), this); }).call(map); } } methods.addCircles = function(lat, lng, radius, layerId, group, options, popup) { var df = dataframe.create() .col('lat', lat) .col('lng', lng) .col('radius', radius) .col('layerId', layerId) .col('group', group) .col('popup', popup) .cbind(options); addLayers(this, "shape", df, function(df, i) { return L.circle([df.get(i, 'lat'), df.get(i, 'lng')], df.get(i, 'radius'), df.get(i)); }); }; methods.addCircleMarkers = function(lat, lng, radius, layerId, group, options, clusterOptions, clusterId, popup) { var df = dataframe.create() .col('lat', lat) .col('lng', lng) .col('radius', radius) .col('layerId', layerId) .col('group', group) .col('popup', popup) .cbind(options); addMarkers(this, df, group, clusterOptions, clusterId, function(df, i) { return L.circleMarker([df.get(i, 'lat'), df.get(i, 'lng')], df.get(i)); }); }; /* * @param lat Array of arrays of latitude coordinates for polylines * @param lng Array of arrays of longitude coordinates for polylines */ methods.addPolylines = function(polygons, layerId, group, options, popup) { var df = dataframe.create() .col('shapes', polygons) .col('layerId', layerId) .col('group', group) .col('popup', popup) .cbind(options); addLayers(this, "shape", df, function(df, i) { var shape = df.get(i, 'shapes')[0]; shape = HTMLWidgets.dataframeToD3(shape); return L.polyline(shape, df.get(i)); }); }; methods.removeMarker = function(layerId) { this.layerManager.removeLayer("marker", layerId); }; methods.clearMarkers = function() { this.layerManager.clearLayers("marker"); }; methods.removeMarkerCluster = function(layerId) { this.layerManager.removeLayer("cluster", layerId); } methods.removeMarkerFromCluster = function(layerId, clusterId) { var cluster = this.layerManager.getLayer("cluster", clusterId); if (!cluster) return; cluster.clusterLayerStore.remove(layerId); } methods.clearMarkerClusters = function() { this.layerManager.clearLayers("cluster"); }; methods.removeShape = function(layerId) { this.layerManager.removeLayer("shape", layerId); }; methods.clearShapes = function() { this.layerManager.clearLayers("shape"); }; methods.addRectangles = function(lat1, lng1, lat2, lng2, layerId, group, options, popup) { var df = dataframe.create() .col('lat1', lat1) .col('lng1', lng1) .col('lat2', lat2) .col('lng2', lng2) .col('layerId', layerId) .col('group', group) .col('popup', popup) .cbind(options); addLayers(this, "shape", df, function(df, i) { return L.rectangle([ [df.get(i, 'lat1'), df.get(i, 'lng1')], [df.get(i, 'lat2'), df.get(i, 'lng2')] ], df.get(i)); }); }; /* * @param lat Array of arrays of latitude coordinates for polygons * @param lng Array of arrays of longitude coordinates for polygons */ methods.addPolygons = function(polygons, layerId, group, options, popup) { var df = dataframe.create() .col('shapes', polygons) .col('layerId', layerId) .col('group', group) .col('popup', popup) .cbind(options); addLayers(this, "shape", df, function(df, i) { var shapes = df.get(i, 'shapes'); for (var j = 0; j < shapes.length; j++) { shapes[j] = HTMLWidgets.dataframeToD3(shapes[j]); } return L.polygon(shapes, df.get(i)); }); }; methods.addGeoJSON = function(data, layerId, group, style) { var self = this; if (typeof(data) === "string") { data = JSON.parse(data); } var globalStyle = $.extend({}, style, data.style || {}); var gjlayer = L.geoJson(data, { style: function(feature) { if (feature.style || feature.properties.style) { return $.extend({}, globalStyle, feature.style, feature.properties.style); } else { return globalStyle; } }, onEachFeature: function(feature, layer) { var extraInfo = { featureId: feature.id, properties: feature.properties }; var popup = feature.properties.popup; if (typeof popup !== 'undefined' && popup !== null) layer.bindPopup(popup); layer.on("click", mouseHandler(self.id, layerId, group, "geojson_click", extraInfo), this); layer.on("mouseover", mouseHandler(self.id, layerId, group, "geojson_mouseover", extraInfo), this); layer.on("mouseout", mouseHandler(self.id, layerId, group, "geojson_mouseout", extraInfo), this); } }); this.layerManager.addLayer(gjlayer, "geojson", layerId, group); }; methods.removeGeoJSON = function(layerId) { this.layerManager.removeLayer("geojson", layerId); }; methods.clearGeoJSON = function() { this.layerManager.clearLayers("geojson"); }; methods.addTopoJSON = function(data, layerId, group, style) { var self = this; if (typeof(data) === "string") { data = JSON.parse(data); } var globalStyle = $.extend({}, style, data.style || {}); var gjlayer = L.geoJson(null, { style: function(feature) { if (feature.style || feature.properties.style) { return $.extend({}, globalStyle, feature.style, feature.properties.style); } else { return globalStyle; } }, onEachFeature: function(feature, layer) { var extraInfo = { featureId: feature.id, properties: feature.properties }; var popup = feature.properties.popup; if (typeof popup !== 'undefined' && popup !== null) layer.bindPopup(popup); layer.on("click", mouseHandler(self.id, layerId, group, "topojson_click", extraInfo), this); layer.on("mouseover", mouseHandler(self.id, layerId, group, "topojson_mouseover", extraInfo), this); layer.on("mouseout", mouseHandler(self.id, layerId, group, "topojson_mouseout", extraInfo), this); } }); omnivore.topojson.parse(data, null, gjlayer); this.layerManager.addLayer(gjlayer, "topojson", layerId, group); }; methods.removeTopoJSON = function(layerId) { this.layerManager.removeLayer("topojson", layerId); }; methods.clearTopoJSON = function() { this.layerManager.clearLayers("topojson"); }; methods.addControl = function(html, position, layerId, classes) { function onAdd(map) { var div = L.DomUtil.create('div', classes); if (typeof layerId !== 'undefined' && layerId !== null) { div.setAttribute('id', layerId) } this._div = div; // It's possible for window.Shiny to be true but Shiny.initializeInputs to // not be, when a static leaflet widget is included as part of the shiny // UI directly (not through leafletOutput or uiOutput). In this case we // don't do the normal Shiny stuff as that will all happen when Shiny // itself loads and binds the entire doc. if (window.Shiny && Shiny.initializeInputs) { Shiny.renderHtml(html, this._div); Shiny.initializeInputs(this._div); Shiny.bindAll(this._div); } else { this._div.innerHTML = html; } return this._div; } function onRemove(map) { if (window.Shiny && Shiny.unbindAll) { Shiny.unbindAll(this._div); } } var Control = L.Control.extend({ options: {position: position}, onAdd: onAdd, onRemove: onRemove }) this.controls.add(new Control, layerId, html); }; methods.removeControl = function(layerId) { this.controls.remove(layerId); }; methods.clearControls = function() { this.controls.clear(); }; methods.addLegend = function(options) { var legend = L.control({position: options.position}); var gradSpan; legend.onAdd = function (map) { var div = L.DomUtil.create('div', options.className), colors = options.colors, labels = options.labels, legendHTML = ''; if (options.type === 'numeric') { // # Formatting constants. var singleBinHeight = 20; // The distance between tick marks, in px var vMargin = 8; // If 1st tick mark starts at top of gradient, how // many extra px are needed for the top half of the // 1st label? (ditto for last tick mark/label) var tickWidth = 4; // How wide should tick marks be, in px? var labelPadding = 6; // How much distance to reserve for tick mark? // (Must be >= tickWidth) // # Derived formatting parameters. // What's the height of a single bin, in percentage (of gradient height)? // It might not just be 1/(n-1), if the gradient extends past the tick // marks (which can be the case for pretty cut points). var singleBinPct = (options.extra.p_n - options.extra.p_1) / (labels.length - 1); // Each bin is `singleBinHeight` high. How tall is the gradient? var totalHeight = (1 / singleBinPct) * singleBinHeight + 1; // How far should the first tick be shifted down, relative to the top // of the gradient? var tickOffset = (singleBinHeight / singleBinPct) * options.extra.p_1; gradSpan = $('<span/>').css({ 'background': 'linear-gradient(' + colors + ')', 'opacity': options.opacity, 'height': totalHeight + 'px', 'width': '18px', 'display': 'block', 'margin-top': vMargin + 'px' }); var leftDiv = $('<div/>').css('float', 'left'), rightDiv = $('<div/>').css('float', 'left'); leftDiv.append(gradSpan); $(div).append(leftDiv).append(rightDiv) .append($("<br clear='both'/>")); // Have to attach the div to the body at this early point, so that the // svg text getComputedTextLength() actually works, below. document.body.appendChild(div); var ns = 'http://www.w3.org/2000/svg'; var svg = document.createElementNS(ns, 'svg'); rightDiv.append(svg); var g = document.createElementNS(ns, 'g'); $(g).attr("transform", "translate(0, " + vMargin + ")"); svg.appendChild(g); // max label width needed to set width of svg, and right-justify text var maxLblWidth = 0; // Create tick marks and labels $.each(labels, function(i, label) { var y = tickOffset + i*singleBinHeight + 0.5; var thisLabel = document.createElementNS(ns, 'text'); $(thisLabel) .text(labels[i]) .attr('y', y) .attr('dx', labelPadding) .attr('dy', '0.5ex'); g.appendChild(thisLabel); maxLblWidth = Math.max(maxLblWidth, thisLabel.getComputedTextLength()); var thisTick = document.createElementNS(ns, 'line'); $(thisTick) .attr('x1', 0) .attr('x2', tickWidth) .attr('y1', y) .attr('y2', y) .attr('stroke-width', 1); g.appendChild(thisTick); }); // Now that we know the max label width, we can right-justify $(svg).find('text') .attr('dx', labelPadding + maxLblWidth) .attr('text-anchor', 'end'); // Final size for <svg> $(svg).css({ width: (maxLblWidth + labelPadding) + "px", height: totalHeight + vMargin*2 + "px" }); if (options.na_color) { $(div).append('<div><i style="background:' + options.na_color + '"></i> ' + options.na_label + '</div>'); } } else { if (options.na_color) { colors.push(options.na_color); labels.push(options.na_label); } for (var i = 0; i < colors.length; i++) { legendHTML += '<i style="background:' + colors[i] + ';opacity:' + options.opacity + '"></i> ' + labels[i] + '<br/>'; } div.innerHTML = legendHTML; } if (options.title) $(div).prepend('<div style="margin-bottom:3px"><strong>' + options.title + '</strong></div>'); return div; }; this.controls.add(legend, options.layerId); }; methods.addLayersControl = function(baseGroups, overlayGroups, options) { var self = this; // Only allow one layers control at a time methods.removeLayersControl.call(this); var firstLayer = true; var base = {}; $.each(asArray(baseGroups), function(i, g) { var layer = self.layerManager.getLayerGroup(g, true); if (layer) { base[g] = layer; // Check if >1 base layers are visible; if so, hide all but the first one if (self.hasLayer(layer)) { if (firstLayer) { firstLayer = false; } else { self.removeLayer(layer); } } } }); var overlay = {}; $.each(asArray(overlayGroups), function(i, g) { var layer = self.layerManager.getLayerGroup(g, true); if (layer) { overlay[g] = layer; } }); var layersControl = L.control.layers(base, overlay, options).addTo(this); this.currentLayersControl = layersControl; }; methods.removeLayersControl = function() { if (this.currentLayersControl) { this.currentLayersControl.removeFrom(this); this.currentLayersControl = null; } }; methods.hideGroup = function(group) { var self = this; $.each(asArray(group), function(i, g) { var layer = self.layerManager.getLayerGroup(g, true); if (layer) { self.removeLayer(layer); } }); }; methods.showGroup = function(group) { var self = this; $.each(asArray(group), function(i, g) { var layer = self.layerManager.getLayerGroup(g, true); if (layer) { self.addLayer(layer); } }); }; methods.addRasterImage = function(uri, bounds, opacity, attribution, layerId, group) { // uri is a data URI containing an image. We want to paint this image as a // layer at (top-left) bounds[0] to (bottom-right) bounds[1]. // We can't simply use ImageOverlay, as it uses bilinear scaling which looks // awful as you zoom in (and sometimes shifts positions or disappears). // Instead, we'll use a TileLayer.Canvas to draw pieces of the image. // First, some helper functions. // degree2tile converts latitude, longitude, and zoom to x and y tile // numbers. The tile numbers returned can be non-integral, as there's no // reason to expect that the lat/lng inputs are exactly on the border of two // tiles. // // We'll use this to convert the bounds we got from the server, into coords // in tile-space at a given zoom level. Note that once we do the conversion, // we don't to do any more trigonometry to convert between pixel coordinates // and tile coordinates; the source image pixel coords, destination canvas // pixel coords, and tile coords all can be scaled linearly. function degree2tile(lat, lng, zoom) { // See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames var latRad = lat * Math.PI / 180; var n = Math.pow(2, zoom); var x = (lng + 180) / 360 * n var y = (1 - Math.log(Math.tan(latRad) + (1 / Math.cos(latRad))) / Math.PI) / 2 * n return {x: x, y: y}; } // Given a range [from,to) and either one or two numbers, returns true if // there is any overlap between [x,x1) and the range--or if x1 is omitted, // then returns true if x is within [from,to). function overlap(from, to, x, /* optional */ x1) { if (arguments.length == 3) x1 = x; return x < to && x1 >= from; } function getCanvasSmoothingProperty(ctx) { var candidates = ["imageSmoothingEnabled", "mozImageSmoothingEnabled", "webkitImageSmoothingEnabled", "msImageSmoothingEnabled"]; for (var i = 0; i < candidates.length; i++) { if (typeof(ctx[candidates[i]]) !== "undefined") { return candidates[i]; } } return null; } // Our general strategy is to: // 1. Load the data URI in an Image() object, so we can get its pixel // dimensions and the underlying image data. (We could have done this // by not encoding as PNG at all but just send an array of RGBA values // from the server, but that would inflate the JSON too much.) // 2. Create a hidden canvas that we use just to extract the image data // from the Image (using Context2D.getImageData()). // 3. Create a TileLayer.Canvas and add it to the map. // We want to synchronously create and attach the TileLayer.Canvas (so an // immediate call to clearRasters() will be respected, for example), but // Image loads its data asynchronously. Fortunately we can resolve this // by putting TileLayer.Canvas into async mode, which will let us create // and attach the layer but have it wait until the image is loaded before // it actually draws anything. // These are the variables that we will populate once the image is loaded. var imgData = null; // 1d row-major array, four [0-255] integers per pixel var imgDataMipMapper = null; var w = null; // image width in pixels var h = null; // image height in pixels // We'll use this array to store callbacks that need to be invoked once // imgData, w, and h have been resolved. var imgDataCallbacks = []; // Consumers of imgData, w, and h can call this to be notified when data // is available. Unlike most async/promise-based APIs, the callback will // be invoked immediately/synchronously if the data is already available. function getImageData(callback) { if (imgData != null) { callback(imgData, w, h, imgDataMipMapper); } else { imgDataCallbacks.push(callback); } } var img = new Image(); img.onload = function() { // Save size w = img.width; h = img.height; // Create a dummy canvas to extract the image data var imgDataCanvas = document.createElement("canvas"); imgDataCanvas.width = w; imgDataCanvas.height = h; imgDataCanvas.style.display = "none"; document.body.appendChild(imgDataCanvas); var imgDataCtx = imgDataCanvas.getContext("2d"); imgDataCtx.drawImage(img, 0, 0); // Save the image data. imgData = imgDataCtx.getImageData(0, 0, w, h).data; imgDataMipMapper = new Mipmapper(img); // Done with the canvas, remove it from the page so it can be gc'd. document.body.removeChild(imgDataCanvas); // Alert any getImageData callers who are waiting. for (var i = 0; i < imgDataCallbacks.length; i++) { imgDataCallbacks[i](imgData, w, h, imgDataMipMapper); } imgDataCallbacks = []; }; img.src = uri; var canvasTiles = L.tileLayer.canvas({ opacity: opacity, attribution: attribution, detectRetina: true, async: true }); canvasTiles.drawTile = function(canvas, tilePoint, zoom) { getImageData(function(imgData, w, h, mipmapper) { try { // The Context2D we'll being drawing onto. It's always 256x256. var ctx = canvas.getContext('2d'); // Convert our image data's top-left and bottom-right locations into // x/y tile coordinates. This is essentially doing a spherical mercator // projection, then multiplying by 2^zoom. var topLeft = degree2tile(bounds[0][0], bounds[0][1], zoom); var bottomRight = degree2tile(bounds[1][0], bounds[1][1], zoom); // The size of the image in x/y tile coordinates. var extent = {x: bottomRight.x - topLeft.x, y: bottomRight.y - topLeft.y}; // Short circuit if tile is totally disjoint from image. if (!overlap(tilePoint.x, tilePoint.x + 1, topLeft.x, bottomRight.x)) return; if (!overlap(tilePoint.y, tilePoint.y + 1, topLeft.y, bottomRight.y)) return; // The linear resolution of the tile we're drawing is always 256px per tile unit. // If the linear resolution (in either direction) of the image is less than 256px // per tile unit, then use nearest neighbor; otherwise, use the canvas's built-in // scaling. var imgRes = { x: w / extent.x, y: h / extent.y }; // We can do the actual drawing in one of three ways: // - Call drawImage(). This is easy and fast, and results in smooth // interpolation (bilinear?). This is what we want when we are // reducing the image from its native size. // - Call drawImage() with imageSmoothingEnabled=false. This is easy // and fast and gives us nearest-neighbor interpolation, which is what // we want when enlarging the image. However, it's unsupported on many // browsers (including QtWebkit). // - Do a manual nearest-neighbor interpolation. This is what we'll fall // back to when enlarging, and imageSmoothingEnabled isn't supported. // In theory it's slower, but still pretty fast on my machine, and the // results look the same AFAICT. // Is imageSmoothingEnabled supported? If so, we can let canvas do // nearest-neighbor interpolation for us. var smoothingProperty = getCanvasSmoothingProperty(ctx); if (smoothingProperty || imgRes.x >= 256 && imgRes.y >= 256) { // Use built-in scaling // Turn off anti-aliasing if necessary if (smoothingProperty) { ctx[smoothingProperty] = imgRes.x >= 256 && imgRes.y >= 256; } // Don't necessarily draw with the full-size image; if we're // downscaling, use the mipmapper to get a pre-downscaled image // (see comments on Mipmapper class for why this matters). mipmapper.getBySize(extent.x*256, extent.y*256, function(mip) { // It's possible that the image will go off the edge of the canvas-- // that's OK, the canvas should clip appropriately. ctx.drawImage(mip, // Convert abs tile coords to rel tile coords, then *256 to convert // to rel pixel coords (topLeft.x - tilePoint.x) * 256, (topLeft.y - tilePoint.y) * 256, // Always draw the whole thing and let canvas clip; so we can just // convert from size in tile coords straight to pixels extent.x * 256, extent.y * 256 ); }); } else { // Use manual nearest-neighbor interpolation // Calculate the source image pixel coordinates that correspond with // the top-left and bottom-right of this tile. (If the source image // only partially overlaps the tile, we use max/min to limit the // sourceStart/End to only reflect the overlapping portion.) var sourceStart = { x: Math.max(0, Math.floor((tilePoint.x - topLeft.x) * imgRes.x)), y: Math.max(0, Math.floor((tilePoint.y - topLeft.y) * imgRes.y)) }; var sourceEnd = { x: Math.min(w, Math.ceil((tilePoint.x + 1 - topLeft.x) * imgRes.x)), y: Math.min(h, Math.ceil((tilePoint.y + 1 - topLeft.y) * imgRes.y)) }; // The size, in dest pixels, that each source pixel should occupy. // This might be greater or less than 1 (e.g. if x and y resolution // are very different). var pixelSize = { x: 256 / imgRes.x, y: 256 / imgRes.y }; // For each pixel in the source image that overlaps the tile... for (var row = sourceStart.y; row < sourceEnd.y; row++) { for (var col = sourceStart.x; col < sourceEnd.x; col++) { // ...extract the pixel data... var i = ((row * w) + col) * 4; var r = imgData[i]; var g = imgData[i+1]; var b = imgData[i+2]; var a = imgData[i+3]; ctx.fillStyle = "rgba(" + [r,g,b,a/255].join(",") + ")"; // ...calculate the corresponding pixel coord in the dest image // where it should be drawn... var pixelPos = { x: (((col / imgRes.x) + topLeft.x) - tilePoint.x) * 256, y: (((row / imgRes.y) + topLeft.y) - tilePoint.y) * 256 }; // ...and draw a rectangle there. ctx.fillRect( Math.round(pixelPos.x), Math.round(pixelPos.y), // Looks crazy, but this is necessary to prevent rounding from // causing overlap between this rect and its neighbors. The // minuend is the location of the next pixel, while the // subtrahend is the position of the current pixel (to turn an // absolute coordinate to a width/height). Yes, I had to look // up minuend and subtrahend. Math.round(pixelPos.x + pixelSize.x) - Math.round(pixelPos.x), Math.round(pixelPos.y + pixelSize.y) - Math.round(pixelPos.y)); } } } } finally { canvasTiles.tileDrawn(canvas); } }); }; this.layerManager.addLayer(canvasTiles, "image", layerId, group); }; methods.removeImage = function(layerId) { this.layerManager.removeLayer("image", layerId); }; methods.clearImages = function() { this.layerManager.clearLayers("image"); }; function preventUnintendedZoomOnScroll(map) { // Prevent unwanted scroll capturing. Similar in purpose to // https://github.com/CliffCloud/Leaflet.Sleep but with a // different set of heuristics. // The basic idea is that when a mousewheel/DOMMouseScroll // event is seen, we disable scroll wheel zooming until the // user moves their mouse cursor or clicks on the map. This // is slightly trickier than just listening for mousemove, // because mousemove is fired when the page is scrolled, // even if the user did not physically move the mouse. We // handle this by examining the mousemove event's screenX // and screenY properties; if they change, we know it's a // "true" move. // lastScreen can never be null, but its x and y can. var lastScreen = {x: null, y: null}; $(document).on("mousewheel DOMMouseScroll", "*", function(e) { // Disable zooming (until the mouse moves or click) map.scrollWheelZoom.disable(); // Any mousemove events at this screen position will be ignored. lastScreen = {x: e.originalEvent.screenX, y: e.originalEvent.screenY}; }); $(document).on("mousemove", "*", function(e) { // Did the mouse really move? if (lastScreen.x !== null && e.screenX !== lastScreen.x || e.screenY !== lastScreen.y) { // It really moved. Enable zooming. map.scrollWheelZoom.enable(); lastScreen = {x: null, y: null}; } }); $(document).on("mousedown", ".leaflet", function(e) { // Clicking always enables zooming. map.scrollWheelZoom.enable(); lastScreen = {x: null, y: null}; }); } HTMLWidgets.widget({ name: "leaflet", type: "output", initialize: function(el, width, height) { // hard-coding center/zoom here for a non-empty initial view, since there // is no way for htmlwidgets to pass initial params to initialize() var map = L.map(el, { center: [51.505, -0.09], zoom: 13 }); preventUnintendedZoomOnScroll(map); // Store some state in the map object map.leafletr = { // Has the map ever rendered successfully? hasRendered: false, // Data to be rendered when resize is called with area != 0 pendingRenderData: null }; if (!HTMLWidgets.shinyMode) return map; // The map is rendered staticly (no output binding, so no this.getId()) if (typeof this.getId === 'undefined') return map; map.id = this.getId(el); // Store the map on the element so we can find it later by ID $(el).data("leaflet-map", map); // When the map is clicked, send the coordinates back to the app map.on('click', function(e) { Shiny.onInputChange(map.id + '_click', { lat: e.latlng.lat, lng: e.latlng.lng, '.nonce': Math.random() // Force reactivity if lat/lng hasn't changed }); }); var groupTimerId = null; map .on('moveend', function(e) { updateBounds(e.target); }) .on('layeradd layerremove', function(e) { // If the layer that's coming or going is a group we created, tell // the server. if (map.layerManager.getGroupNameFromLayerGroup(e.layer)) { // But to avoid chattiness, coalesce events if (groupTimerId) { clearTimeout(groupTimerId); groupTimerId = null; } groupTimerId = setTimeout(function() { groupTimerId = null; Shiny.onInputChange(map.id + '_groups', map.layerManager.getVisibleGroups()); }, 100); } }); return map; }, renderValue: function(el, data, map) { // Leaflet does not behave well when you set up a bunch of layers when // the map is not visible (width/height == 0). Popups get misaligned // relative to their owning markers, and the fitBounds calculations // are off. Therefore we wait until the map is actually showing to // render the value (we rely on the resize() callback being invoked // at the appropriate time). // // There may be an issue with leafletProxy() calls being made while // the map is not being viewed--not sure what the right solution is // there. if (el.offsetWidth === 0 || el.offsetHeight === 0) { map.leafletr.pendingRenderData = data; return; } map.leafletr.pendingRenderData = null; // Merge data options into defaults var options = $.extend({ zoomToLimits: "always" }, data.options); if (!map.layerManager) { map.controls = new ControlStore(map); map.layerManager = new LayerManager(map); } else { map.controls.clear(); map.layerManager.clear(); } var explicitView = false; if (data.setView) { explicitView = true; map.setView.apply(map, data.setView); } if (data.fitBounds) { explicitView = true; methods.fitBounds.apply(map, data.fitBounds); } // Returns true if the zoomToLimits option says that the map should be // zoomed to map elements. function needsZoom() { return options.zoomToLimits === "always" || (options.zoomToLimits === "first" && !map.leafletr.hasRendered); } if (!explicitView && needsZoom()) { if (data.limits) { // Use the natural limits of what's being drawn on the map // If the size of the bounding box is 0, leaflet gets all weird var pad = 0.006; if (data.limits.lat[0] === data.limits.lat[1]) { data.limits.lat[0] = data.limits.lat[0] - pad; data.limits.lat[1] = data.limits.lat[1] + pad; } if (data.limits.lng[0] === data.limits.lng[1]) { data.limits.lng[0] = data.limits.lng[0] - pad; data.limits.lng[1] = data.limits.lng[1] + pad; } map.fitBounds([ [ data.limits.lat[0], data.limits.lng[0] ], [ data.limits.lat[1], data.limits.lng[1] ] ]); } else { map.fitWorld(); } } for (var i = 0; data.calls && i < data.calls.length; i++) { var call = data.calls[i]; if (methods[call.method]) methods[call.method].apply(map, call.args); else console.log("Unknown method " + call.method); } map.leafletr.hasRendered = true; if (!HTMLWidgets.shinyMode) return; setTimeout(function() { updateBounds(map); }, 1); }, resize: function(el, width, height, map) { map.invalidateSize(); if (map.leafletr.pendingRenderData) { this.renderValue(el, map.leafletr.pendingRenderData, map); } } }); if (!HTMLWidgets.shinyMode) return; Shiny.addCustomMessageHandler('leaflet-calls', function(data) { var id = data.id; var el = document.getElementById(id); var map = el ? $(el).data('leaflet-map') : null; if (!map) { console.log("Couldn't find map with id " + id); return; } for (var i = 0; i < data.calls.length; i++) { var call = data.calls[i]; if (call.dependencies) { Shiny.renderDependencies(call.dependencies); } if (methods[call.method]) methods[call.method].apply(map, call.args); else console.log("Unknown method " + call.method); } }); })(); // In RMarkdown's self-contained mode, we don't have a way to carry around the // images that Leaflet needs but doesn't load into the page. Instead, we'll set // data URIs for the default marker, and let any others be loaded via CDN. if (typeof(L.Icon.Default.imagePath) === "undefined") { L.Icon.Default.imagePath = "http://cdn.leafletjs.com/leaflet-0.7.3/images"; if (L.Browser.retina) { L.Icon.Default.prototype.options.iconUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAABSCAYAAAAWy4frAAAPiElEQVR42t1bCVCU5xkmbabtZJJOO+l0mhgT0yQe0WXZgz2570NB8I6J6UzaTBoORRFEruVGDhWUPRAQRFFREDnVxCtEBRb24DBNE3Waaatpkmluo4m+fd9v999olGVBDu3OPLj+//s+7/W93/f9//6/EwA4/T9g3AlFOUeeUGR2uMqzOyJk2R2x0qyOAmnmkS3SrCPrZJlHlsqzjypcs49OX1Jf//P7KhD885A0u10my2ovQscvybI6wEF8ivI7pFntAV6qkw9PWSBK1bEnZRltm2WZ7R8h4FbI0VG33GPgXXgCAra+A4EIn8KT4JH/FigoiJ/IIz6TZbVVKLLan5u0QESqlkckWW3p0sy2bxDAgZwO13TDytoB+NPe9+zild2DEFGuB7/NpzDodriF55o0o7XIRXXoNxMaiCSj9VU09C8EENxyj0C4thterh2EV+veuwOr6s7Dy3ssoO93k3llzxBE6PTgkXcMOF7EJ9KMtqjR9JFDQnNV9b+QqlqqEECQZ7TBgu1nYdXuIXgVneSwYtcgRFb1Q1iFGULLzRCsM90GOrZghxkiKvthec0grLpFlxCu6cKh1w6cHUSbctPhx8YlEElu4+NSVfNpBBACtpyGlbsGmBOElRhMBDofgk4GobOjQXC5CRZiUC/VDtn4qLrBJZ3A2cNg+nE4P31PgSDBbImq5UNJejMQFqi7cCicZ3iZBTAAQVoTBI4DKKCVGBDHH6nrBRlWxWr7sljVIhlTIDLVoRkS1eH/SNIPgzyzFRZV9NnG++LqQcyoGQLQgfFEIFYpcueAzc6SSiMOtTYgH9CXr+WpTbxRBeKlqn9UktZkRoACZ5PlO81YgfMM4RX9EKAxTSjCdvTjELPYW17dD8rsdiBfEBclSY2POxQIHnlIknroEAJk6U2wpMLISF/aNQShWAV/tWlSEIK2VqBNsr200gRyGmLokyS18cTdFtA7AnFNbcxAACGMrQtDLAjqBT+1cVJBNsk2+bBQ1wOcX5K0xs12A8GyzXRNafgeAYFb3mEkrBI4I/mWGUeNQI1lyp2PoO9j4aDKcH4Ebe0E8g3xgyylcc6wgbimNjSSoFtWK1sTqLRh2BM+SOgIfDGLJL8IG3ZZjUX/ViyvGYLFOwdZn/ljYI7yzsee4TjcsV/IR3FqQ+tdAxEnNSjFyQeBEK7pgRVodEnVIPhsNzqEYK0ZluFsRnq3YjH22KJyA6z4yTmSpZ5zlH8RTvWkt1CrB85PYUqjzx2BuG6sPyfeeAA8sjtwphhiCFSbwXub0S7ISPiOAZvO4h048xSfBM+cDpDieCZOggSz6JHdBv5FJ3CN6LPJR1QMgO9204h2aALgdDxzjlp4kw8YaHKyBSJJPigWb6wHQiRmbxkKL0QDXkhgD94YxGKsGskTQkvfxVnlIHBcBNfkegziwB3HAnHDuGynRXcp/utXZhrRHiWM5CPLjbdwHVDYAhFt3J8rTtoPbpktSDrE4INZ8iw12kUYEpPs4kozeOW0A3EQIovbYcfxITj798vwxbfX4Or1H8B46ROo7fwbvKY9bpNzy2hmiSOOyMrBEe2RT5x/7tjHxCFK2l/4YyBJ+95HQABmibKzEJvRs9RgF4FqE5MleGS3AumLN+6D4lYjfIeOD/e5eROg7sz7oEg7wHRk6Y3Yi/2MJwT7bCS75BvJBuGsSvqID1ggaHyeaAMeQERgyajBg3BG8SgxDAsvJFxUOcBkg7d0Ml3XjfuhCyvg6Ofix1+Al6qB6fpueotxsckFh5A92+QbydHw4vymGJxEG+rWiRL3goJWcSwvwbPECO5bDcMiRGNmchS4a1I9kP62DhOM9tPad4npEhaUdTPOsPJ+u7bJN85PpaqJ6YoT6xKcRIl1pQjwxIukxXhyIY57N1Swh7DyASbrm38MSHdRUStc+/4GjOUTV32acbhlNjNO6pWR7FPTk6xX3lGmK0ys0zrhn0Zhwh7wK3ibnVyg6we3LQa7WFQxyGSpiqRbe/o8jPXTe+EK4xDjECHOxdYRYc8++UhyfgXHma5w/Z5mJ+H63T3ChN3Y6O/guMcxj8NGicLDgYyQ3CKcnsUbMBuoa7j48ZgD+erqdczqbsYTpulj3LSu2POBfCQ58pn0EH1OwoTafwvX1+JV2VmIxEwHlJlBsdkwLHy2mZjcgjI9kJ4Ynbh6/Xu4l09YfhPjCsSJg7hpIbbng/92M5Mjn0kPcdlJGF/7JQJCSrsgAseeHzoqL+4bFnSe5EJKzgHpeaTsg3v9rCrtYFz+hScZdzAGYs8HX84H9Jn0KAYnQfyuIQT4Y5mo0akiMhQeDh44tEguXGcE0iP845MvxxzEjRs3QZ5Ux3hCtnUxbqq6PR/8cRdAcuSz1YfzGEhNm2BdDfjkvw0LcTYKokCK+oaFAolIjiDFBYl02/oujDmQC1c+ZxzC+BoIp2t35HXHPrDnA/lIcuQz6SKOOAnWVqsRbHscjidDNf0gRWF7CNX2M1l3VTOQbmpd55gDqT01xDhkmBTiJMhGsB+isdrPbGe6wrU15RjIzkQEyHB3GqYbYCAiSeHwCMBmI7mAYiwt6grX7QT9h5dHHcQ/P/sKlEm7GYd37lHGGaLut2tbirD5iT6TriCuKsVJsLrCwyWuih2Yj/unMC2VFlfsgr5hodxsZHIEZVoTkP787APw7TXHZy/ac/25rJ3pSpP24tRrZnyeW012bbtZbS9AefKZ+b6mMtjJS6V6GP/zOR3wK+pkQn7bzHbJCCRDsqFlBpz+djHCV7a2wMUr/x0xiM++ugprq45bnFhbhdNoF+MKLOt32C75SvqIb7xUO3/Fdr/8uMqDLmsqwU3VipH2QzA2k3hTr11ICnqZHMn7F+HCFIfZQQ5JfDVUvW1mzv708/V316FV/wF4Je9hsgSv3GOMYz71Jg6bkezS0CN5N1WLhSOussW2jResrnzNZXUFm5PnW0nl2CciVLQHebHBJh9U0g1S3GYQD4eQjH2QWH0C0utw15DXAEIybD0nxoUsYPMZmz4N59HYE+K0SzyC2Mo3bIHw4zTT+Kt33ESAX/FZCMWovUtMIMzvHRFKJA9G+VAGvJ7IPsKGC3HdDYI4qnwzhJQZmQ5l2AODcMSWb6mJ6fgWn+H4bsxbWzX9tmt2l9Xl7fzYcpwJGhl5MI5XESoL8kaGKB9XWww8xOoYIXBrD3hvOgnK9BbEYdypHsctSBcGYLbJ+FMvbupz2AanJ01uAPLVJab88B03H1xidKH8WB0TCCq1KNEM4YgRDm7FRlys+m8L6G6gJLmPkpuqxhJU0st8JF8FMeV+dwTipFL9zDlGewmB1wYdzJh/qRlccntHDcqevBCv6NBZ3xIz+CGP5xYTKIoMIMZzo+UTIAK3WRKgULUB+egcrTs/7A06XpQ20Tlai+O4mm0DKLuSAgPwkWgqIcOkkC+BOBRdVlcC+ciL0kUNG4jodd3vnKM13yHAK/8UBG6nTBrBOUc/pfDBRZJ88cg9DuQbL1rzxdw3yx61exPbOUazi4Rd8VqYMhBIwyunF5yz9VMCUV6vxQ+ECJcH8s05SlMy4t145xi1jAkjfIu7GIESxzYPSacC1Gfkg3fhGbD6ddMlVvuCQz/0oHAfKclSmiAAK0JN75zdC/Oy9JMKanKyTxBvOGAJJEbd4fAvVrxo9UukxMfZwbu4hwWiKDLCXCSfTNAUTba9Cs5x1SD4OBwIm4qjNQOkKE1uBH+aQkssVZmbqZ8UCLAvyS5BnLDf2hvaE6P+MZQfpYngsuBd2A1+W7EqBUZ4MUM/KXAvMjGbHvm23gCXaI1yTD9Po7KezWBJB8EXp0ACD0s+J6NnQkGzJGdPlFDHBdI+5t/Z+dGaQC4bHpvOgg+uznJcIGereiYUykIjs+WW22mrBi9WLbqnJx9wlugkIlHifvBGcgLNKLPQ4ESA+pCzI4jfwy2Ajff8CAduWzy4rLjnnWEGqFdmpfdMCKgaZEOZc5qrxg3nWM28cXmohhetPcqqsn4veG02MczDmWVmWs+4wjmr18YvWFfLBVI3bk8HubxZ5spVRZHTyQzJsSovoPHxhAKrQdyKrFNcED/wo8pnjuvzWrgHayJyIY5bz2ITw1ycJp9P7R4X8LDCHK/L2l0sEH60tmrcHzzjRet4tM9hVck+xQzKNxnGLRDqO+KUZZ7gqnHdZY1mxoQ8QUfjlYwI1taCBy5YBKrKcynd9wTqNwufEfhrqq17Ko16wh4FpPFK45ZtKDNOgnshZjDfAH9M7r4nyPONjEua/hZXjav8NzTTJvThTF6UppJtF+JqwA2NE15U6eFZdGgsmJvRyziUeBXIX7PT2huazRP+lKkgavszeM18jW0oVcfBrYCqYoRnN3aPGlw1iMM17ai1Gtqvnd/Q/H5SnvvF7f12ljkcz0psUmWBpSoz0LnRgKpBugq6L8CuxSkQde6kPcAsWqN7Ao1+yzaUacdAsckI0jwDPJPU5TBmbOxi/UW64pQOrjc+5/1V/dtJfRIbrw0KWFVWV+Hw6GNDZE6aHp7e0OUQ5qTrmY48rw/4sRWW3ojSpk36I+Wzo7Y/7hyl+ZJtXVI7WJ+45hrgacz29A32QTISrCDpiJLbuWp8Oiuh8jGYiof8eTHqDEtVKkCGmZVZqzI9scsuSIZkZXTfKnYHt8NNmLK3FaQxpb9GJz5jVcHMclWhrD+VeHfQsJLkWqohTGrlqnFZ9LrukSl97YIXpU5kVcHMSvDKTppnhNmY8WkJXXcFnSMZSY6e3cO1ruKxU/7+CGUSnbnCti4bWjHbOAvlGOApdPrJ9beDjtE5khFsaOaq8dHzMaW/vC/e6KGMWm4flYMku4cNnVmpPej8udtA1aBzrll47RGjs/aG+vX75tUkyihl1lKVZnDFrIuy+2AaOv9EvAX0nY7ROZeEJq4aF+g3zPvqHStejOYvlvGuA1FmNxtCM1P18AcMgjALv9MxYWaX9WcBktWuuu9eFqPM4mbvAzbEEg5h9tHpLIOtP+g7HeMnNHLVeG/JkvF7YWxc33jDqqy0ZhoEKovzM1P0DPSdjtFvG5ZVXLP0vn19z3KrVTvIHF3fYHHeCvruHN/AbdNN3PO69+17iLgzjrRux8El/SwIMg0M9P3HG9HqsPv+hUrrJXEvczj+AAbRx+AcX88F0v1AvBnKAnlTG8Rln5/6LuLHW5/zorT+D0wg1qq8y5xfu88CSyCnH5h3dW/ZGXve8uOMZRWP0no8cIFY7+YfswURrT36QL09ffsMppHYegW/P7CBWHvlMOGBe5/9jtdjY7R8wkTb+R9meZA6n2oJWAAAAABJRU5ErkJggg=="; } else { L.Icon.Default.prototype.options.iconUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAApCAYAAADAk4LOAAAGmklEQVRYw7VXeUyTZxjvNnfELFuyIzOabermMZEeQC/OclkO49CpOHXOLJl/CAURuYbQi3KLgEhbrhZ1aDwmaoGqKII6odATmH/scDFbdC7LvFqOCc+e95s2VG50X/LLm/f4/Z7neY/ne18aANCmAr5E/xZf1uDOkTcGcWR6hl9247tT5U7Y6SNvWsKT63P58qbfeLJG8M5qcgTknrvvrdDbsT7Ml+tv82X6vVxJE33aRmgSyYtcWVMqX97Yv2JvW39UhRE2HuyBL+t+gK1116ly06EeWFNlAmHxlQE0OMiV6mQCScusKRlhS3QLeVJdl1+23h5dY4FNB3thrbYboqptEFlphTC1hSpJnbRvxP4NWgsE5Jyz86QNNi/5qSUTGuFk1gu54tN9wuK2wc3o+Wc13RCmsoBwEqzGcZsxsvCSy/9wJKf7UWf1mEY8JWfewc67UUoDbDjQC+FqK4QqLVMGGR9d2wurKzqBk3nqIT/9zLxRRjgZ9bqQgub+DdoeCC03Q8j+0QhFhBHR/eP3U/zCln7Uu+hihJ1+bBNffLIvmkyP0gpBZWYXhKussK6mBz5HT6M1Nqpcp+mBCPXosYQfrekGvrjewd59/GvKCE7TbK/04/ZV5QZYVWmDwH1mF3xa2Q3ra3DBC5vBT1oP7PTj4C0+CcL8c7C2CtejqhuCnuIQHaKHzvcRfZpnylFfXsYJx3pNLwhKzRAwAhEqG0SpusBHfAKkxw3w4627MPhoCH798z7s0ZnBJ/MEJbZSbXPhER2ih7p2ok/zSj2cEJDd4CAe+5WYnBCgR2uruyEw6zRoW6/DWJ/OeAP8pd/BGtzOZKpG8oke0SX6GMmRk6GFlyAc59K32OTEinILRJRchah8HQwND8N435Z9Z0FY1EqtxUg+0SO6RJ/mmXz4VuS+DpxXC3gXmZwIL7dBSH4zKE50wESf8qwVgrP1EIlTO5JP9Igu0aexdh28F1lmAEGJGfh7jE6ElyM5Rw/FDcYJjWhbeiBYoYNIpc2FT/SILivp0F1ipDWk4BIEo2VuodEJUifhbiltnNBIXPUFCMpthtAyqws/BPlEF/VbaIxErdxPphsU7rcCp8DohC+GvBIPJS/tW2jtvTmmAeuNO8BNOYQeG8G/2OzCJ3q+soYB5i6NhMaKr17FSal7GIHheuV3uSCY8qYVuEm1cOzqdWr7ku/R0BDoTT+DT+ohCM6/CCvKLKO4RI+dXPeAuaMqksaKrZ7L3FE5FIFbkIceeOZ2OcHO6wIhTkNo0ffgjRGxEqogXHYUPHfWAC/lADpwGcLRY3aeK4/oRGCKYcZXPVoeX/kelVYY8dUGf8V5EBRbgJXT5QIPhP9ePJi428JKOiEYhYXFBqou2Guh+p/mEB1/RfMw6rY7cxcjTrneI1FrDyuzUSRm9miwEJx8E/gUmqlyvHGkneiwErR21F3tNOK5Tf0yXaT+O7DgCvALTUBXdM4YhC/IawPU+2PduqMvuaR6eoxSwUk75ggqsYJ7VicsnwGIkZBSXKOUww73WGXyqP+J2/b9c+gi1YAg/xpwck3gJuucNrh5JvDPvQr0WFXf0piyt8f8/WI0hV4pRxxkQZdJDfDJNOAmM0Ag8jyT6hz0WGXWuP94Yh2jcfjmXAGvHCMslRimDHYuHuDsy2QtHuIavznhbYURq5R57KpzBBRZKPJi8eQg48h4j8SDdowifdIrEVdU+gbO6QNvRRt4ZBthUaZhUnjlYObNagV3keoeru3rU7rcuceqU1mJBxy+BWZYlNEBH+0eH4vRiB+OYybU2hnblYlTvkHinM4m54YnxSyaZYSF6R3jwgP7udKLGIX6r/lbNa9N6y5MFynjWDtrHd75ZvTYAPO/6RgF0k76mQla3FGq7dO+cH8sKn0Vo7nDllwAhqwLPkxrHwWmHJOo+AKJ4rab5OgrM7rVu8eWb2Pu0Dh4eDgXoOfvp7Y7QeqknRmvcTBEyq9m/HQQSCSz6LHq3z0yzsNySRfMS253wl2KyRDbcZPcfJKjZmSEOjcxyi+Y8dUOtsIEH6R2wNykdqrkYJ0RV92H0W58pkfQk7cKevsLK10Py8SdMGfXNXATY+pPbyJR/ET6n9nIfztNtZYRV9XniQu9IA2vOVgy4ir7GCLVmmd+zjkH0eAF9Po6K61pmCXHxU5rHMYd1ftc3owjwRSVRzLjKvqZEty6cRUD7jGqiOdu5HG6MdHjNcNYGqfDm5YRzLBBCCDl/2bk8a8gdbqcfwECu62Fg/HrggAAAABJRU5ErkJggg=="; } }
ajax/libs/cyclejs-dom/8.0.0-rc4/cycle-dom.js
redmunds/cdnjs
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.CycleDOM = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ },{}],2:[function(require,module,exports){ 'use strict'; var isValidString = function isValidString(param) { return typeof param === 'string' && param.length > 0; }; var startsWith = function startsWith(string, start) { return string.indexOf(start) === 0; }; var isSelector = function isSelector(param) { return isValidString(param) && (startsWith(param, '.') || startsWith(param, '#')); }; var node = function node(h) { return function (tagName) { return function (first) { for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { rest[_key - 1] = arguments[_key]; } if (isSelector(first)) { return h.apply(undefined, [tagName + first].concat(rest)); } else { return h.apply(undefined, [tagName, first].concat(rest)); } }; }; }; var TAG_NAMES = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'map', 'mark', 'menu', 'meta', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'p', 'param', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'u', 'ul', 'video']; module.exports = function (h) { var exported = { TAG_NAMES: TAG_NAMES, isSelector: isSelector }; var appliedNode = node(h); TAG_NAMES.forEach(function (n) { exported[n] = appliedNode(n); }); return exported; }; },{}],3:[function(require,module,exports){ 'use strict'; var proto = Element.prototype; var vendor = proto.matches || proto.matchesSelector || proto.webkitMatchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector; module.exports = match; /** * Match `el` to `selector`. * * @param {Element} el * @param {String} selector * @return {Boolean} * @api public */ function match(el, selector) { if (vendor) return vendor.call(el, selector); var nodes = el.parentNode.querySelectorAll(selector); for (var i = 0; i < nodes.length; i++) { if (nodes[i] == el) return true; } return false; } },{}],4:[function(require,module,exports){ /** * index.js * * A client-side DOM to vdom parser based on DOMParser API */ 'use strict'; var VNode = require('virtual-dom/vnode/vnode'); var VText = require('virtual-dom/vnode/vtext'); var domParser = new DOMParser(); var propertyMap = require('./property-map'); var namespaceMap = require('./namespace-map'); var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; module.exports = parser; /** * DOM/html string to vdom parser * * @param Mixed el DOM element or html string * @param String attr Attribute name that contains vdom key * @return Object VNode or VText */ function parser(el, attr) { // empty input fallback to empty text node if (!el) { return createNode(document.createTextNode('')); } if (typeof el === 'string') { var doc = domParser.parseFromString(el, 'text/html'); // most tags default to body if (doc.body.firstChild) { el = doc.body.firstChild; // some tags, like script and style, default to head } else if (doc.head.firstChild && (doc.head.firstChild.tagName !== 'TITLE' || doc.title)) { el = doc.head.firstChild; // special case for html comment, cdata, doctype } else if (doc.firstChild && doc.firstChild.tagName !== 'HTML') { el = doc.firstChild; // other element, such as whitespace, or html/body/head tag, fallback to empty text node } else { el = document.createTextNode(''); } } if (typeof el !== 'object' || !el || !el.nodeType) { throw new Error('invalid dom node', el); } return createNode(el, attr); } /** * Create vdom from dom node * * @param Object el DOM element * @param String attr Attribute name that contains vdom key * @return Object VNode or VText */ function createNode(el, attr) { // html comment is not currently supported by virtual-dom if (el.nodeType === 3) { return createVirtualTextNode(el); // cdata or doctype is not currently supported by virtual-dom } else if (el.nodeType === 1 || el.nodeType === 9) { return createVirtualDomNode(el, attr); } // default to empty text node return new VText(''); } /** * Create vtext from dom node * * @param Object el Text node * @return Object VText */ function createVirtualTextNode(el) { return new VText(el.nodeValue); } /** * Create vnode from dom node * * @param Object el DOM element * @param String attr Attribute name that contains vdom key * @return Object VNode */ function createVirtualDomNode(el, attr) { var ns = el.namespaceURI !== HTML_NAMESPACE ? el.namespaceURI : null; var key = attr && el.getAttribute(attr) ? el.getAttribute(attr) : null; return new VNode( el.tagName , createProperties(el) , createChildren(el, attr) , key , ns ); } /** * Recursively create vdom * * @param Object el Parent element * @param String attr Attribute name that contains vdom key * @return Array Child vnode or vtext */ function createChildren(el, attr) { var children = []; for (var i = 0; i < el.childNodes.length; i++) { children.push(createNode(el.childNodes[i], attr)); }; return children; } /** * Create properties from dom node * * @param Object el DOM element * @return Object Node properties and attributes */ function createProperties(el) { var properties = {}; if (!el.hasAttributes()) { return properties; } var ns; if (el.namespaceURI && el.namespaceURI !== HTML_NAMESPACE) { ns = el.namespaceURI; } var attr; for (var i = 0; i < el.attributes.length; i++) { if (ns) { attr = createPropertyNS(el.attributes[i]); } else { attr = createProperty(el.attributes[i]); } // special case, namespaced attribute, use properties.foobar if (attr.ns) { properties[attr.name] = { namespace: attr.ns , value: attr.value }; // special case, use properties.attributes.foobar } else if (attr.isAttr) { // init attributes object only when necessary if (!properties.attributes) { properties.attributes = {} } properties.attributes[attr.name] = attr.value; // default case, use properties.foobar } else { properties[attr.name] = attr.value; } }; return properties; } /** * Create property from dom attribute * * @param Object attr DOM attribute * @return Object Normalized attribute */ function createProperty(attr) { var name, value, isAttr; // using a map to find the correct case of property name if (propertyMap[attr.name]) { name = propertyMap[attr.name]; } else { name = attr.name; } // special cases for style attribute, we default to properties.style if (name === 'style') { var style = {}; attr.value.split(';').forEach(function (s) { var pos = s.indexOf(':'); if (pos < 0) { return; } style[s.substr(0, pos).trim()] = s.substr(pos + 1).trim(); }); value = style; // special cases for data attribute, we default to properties.attributes.data } else if (name.indexOf('data-') === 0) { value = attr.value; isAttr = true; } else { value = attr.value; } return { name: name , value: value , isAttr: isAttr || false }; } /** * Create namespaced property from dom attribute * * @param Object attr DOM attribute * @return Object Normalized attribute */ function createPropertyNS(attr) { var name, value; return { name: attr.name , value: attr.value , ns: namespaceMap[attr.name] || '' }; } },{"./namespace-map":5,"./property-map":6,"virtual-dom/vnode/vnode":47,"virtual-dom/vnode/vtext":49}],5:[function(require,module,exports){ /** * namespace-map.js * * Necessary to map svg attributes back to their namespace */ 'use strict'; // extracted from https://github.com/Matt-Esch/virtual-dom/blob/master/virtual-hyperscript/svg-attribute-namespace.js var DEFAULT_NAMESPACE = null; var EV_NAMESPACE = 'http://www.w3.org/2001/xml-events'; var XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink'; var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'; var namespaces = { 'about': DEFAULT_NAMESPACE , 'accent-height': DEFAULT_NAMESPACE , 'accumulate': DEFAULT_NAMESPACE , 'additive': DEFAULT_NAMESPACE , 'alignment-baseline': DEFAULT_NAMESPACE , 'alphabetic': DEFAULT_NAMESPACE , 'amplitude': DEFAULT_NAMESPACE , 'arabic-form': DEFAULT_NAMESPACE , 'ascent': DEFAULT_NAMESPACE , 'attributeName': DEFAULT_NAMESPACE , 'attributeType': DEFAULT_NAMESPACE , 'azimuth': DEFAULT_NAMESPACE , 'bandwidth': DEFAULT_NAMESPACE , 'baseFrequency': DEFAULT_NAMESPACE , 'baseProfile': DEFAULT_NAMESPACE , 'baseline-shift': DEFAULT_NAMESPACE , 'bbox': DEFAULT_NAMESPACE , 'begin': DEFAULT_NAMESPACE , 'bias': DEFAULT_NAMESPACE , 'by': DEFAULT_NAMESPACE , 'calcMode': DEFAULT_NAMESPACE , 'cap-height': DEFAULT_NAMESPACE , 'class': DEFAULT_NAMESPACE , 'clip': DEFAULT_NAMESPACE , 'clip-path': DEFAULT_NAMESPACE , 'clip-rule': DEFAULT_NAMESPACE , 'clipPathUnits': DEFAULT_NAMESPACE , 'color': DEFAULT_NAMESPACE , 'color-interpolation': DEFAULT_NAMESPACE , 'color-interpolation-filters': DEFAULT_NAMESPACE , 'color-profile': DEFAULT_NAMESPACE , 'color-rendering': DEFAULT_NAMESPACE , 'content': DEFAULT_NAMESPACE , 'contentScriptType': DEFAULT_NAMESPACE , 'contentStyleType': DEFAULT_NAMESPACE , 'cursor': DEFAULT_NAMESPACE , 'cx': DEFAULT_NAMESPACE , 'cy': DEFAULT_NAMESPACE , 'd': DEFAULT_NAMESPACE , 'datatype': DEFAULT_NAMESPACE , 'defaultAction': DEFAULT_NAMESPACE , 'descent': DEFAULT_NAMESPACE , 'diffuseConstant': DEFAULT_NAMESPACE , 'direction': DEFAULT_NAMESPACE , 'display': DEFAULT_NAMESPACE , 'divisor': DEFAULT_NAMESPACE , 'dominant-baseline': DEFAULT_NAMESPACE , 'dur': DEFAULT_NAMESPACE , 'dx': DEFAULT_NAMESPACE , 'dy': DEFAULT_NAMESPACE , 'edgeMode': DEFAULT_NAMESPACE , 'editable': DEFAULT_NAMESPACE , 'elevation': DEFAULT_NAMESPACE , 'enable-background': DEFAULT_NAMESPACE , 'end': DEFAULT_NAMESPACE , 'ev:event': EV_NAMESPACE , 'event': DEFAULT_NAMESPACE , 'exponent': DEFAULT_NAMESPACE , 'externalResourcesRequired': DEFAULT_NAMESPACE , 'fill': DEFAULT_NAMESPACE , 'fill-opacity': DEFAULT_NAMESPACE , 'fill-rule': DEFAULT_NAMESPACE , 'filter': DEFAULT_NAMESPACE , 'filterRes': DEFAULT_NAMESPACE , 'filterUnits': DEFAULT_NAMESPACE , 'flood-color': DEFAULT_NAMESPACE , 'flood-opacity': DEFAULT_NAMESPACE , 'focusHighlight': DEFAULT_NAMESPACE , 'focusable': DEFAULT_NAMESPACE , 'font-family': DEFAULT_NAMESPACE , 'font-size': DEFAULT_NAMESPACE , 'font-size-adjust': DEFAULT_NAMESPACE , 'font-stretch': DEFAULT_NAMESPACE , 'font-style': DEFAULT_NAMESPACE , 'font-variant': DEFAULT_NAMESPACE , 'font-weight': DEFAULT_NAMESPACE , 'format': DEFAULT_NAMESPACE , 'from': DEFAULT_NAMESPACE , 'fx': DEFAULT_NAMESPACE , 'fy': DEFAULT_NAMESPACE , 'g1': DEFAULT_NAMESPACE , 'g2': DEFAULT_NAMESPACE , 'glyph-name': DEFAULT_NAMESPACE , 'glyph-orientation-horizontal': DEFAULT_NAMESPACE , 'glyph-orientation-vertical': DEFAULT_NAMESPACE , 'glyphRef': DEFAULT_NAMESPACE , 'gradientTransform': DEFAULT_NAMESPACE , 'gradientUnits': DEFAULT_NAMESPACE , 'handler': DEFAULT_NAMESPACE , 'hanging': DEFAULT_NAMESPACE , 'height': DEFAULT_NAMESPACE , 'horiz-adv-x': DEFAULT_NAMESPACE , 'horiz-origin-x': DEFAULT_NAMESPACE , 'horiz-origin-y': DEFAULT_NAMESPACE , 'id': DEFAULT_NAMESPACE , 'ideographic': DEFAULT_NAMESPACE , 'image-rendering': DEFAULT_NAMESPACE , 'in': DEFAULT_NAMESPACE , 'in2': DEFAULT_NAMESPACE , 'initialVisibility': DEFAULT_NAMESPACE , 'intercept': DEFAULT_NAMESPACE , 'k': DEFAULT_NAMESPACE , 'k1': DEFAULT_NAMESPACE , 'k2': DEFAULT_NAMESPACE , 'k3': DEFAULT_NAMESPACE , 'k4': DEFAULT_NAMESPACE , 'kernelMatrix': DEFAULT_NAMESPACE , 'kernelUnitLength': DEFAULT_NAMESPACE , 'kerning': DEFAULT_NAMESPACE , 'keyPoints': DEFAULT_NAMESPACE , 'keySplines': DEFAULT_NAMESPACE , 'keyTimes': DEFAULT_NAMESPACE , 'lang': DEFAULT_NAMESPACE , 'lengthAdjust': DEFAULT_NAMESPACE , 'letter-spacing': DEFAULT_NAMESPACE , 'lighting-color': DEFAULT_NAMESPACE , 'limitingConeAngle': DEFAULT_NAMESPACE , 'local': DEFAULT_NAMESPACE , 'marker-end': DEFAULT_NAMESPACE , 'marker-mid': DEFAULT_NAMESPACE , 'marker-start': DEFAULT_NAMESPACE , 'markerHeight': DEFAULT_NAMESPACE , 'markerUnits': DEFAULT_NAMESPACE , 'markerWidth': DEFAULT_NAMESPACE , 'mask': DEFAULT_NAMESPACE , 'maskContentUnits': DEFAULT_NAMESPACE , 'maskUnits': DEFAULT_NAMESPACE , 'mathematical': DEFAULT_NAMESPACE , 'max': DEFAULT_NAMESPACE , 'media': DEFAULT_NAMESPACE , 'mediaCharacterEncoding': DEFAULT_NAMESPACE , 'mediaContentEncodings': DEFAULT_NAMESPACE , 'mediaSize': DEFAULT_NAMESPACE , 'mediaTime': DEFAULT_NAMESPACE , 'method': DEFAULT_NAMESPACE , 'min': DEFAULT_NAMESPACE , 'mode': DEFAULT_NAMESPACE , 'name': DEFAULT_NAMESPACE , 'nav-down': DEFAULT_NAMESPACE , 'nav-down-left': DEFAULT_NAMESPACE , 'nav-down-right': DEFAULT_NAMESPACE , 'nav-left': DEFAULT_NAMESPACE , 'nav-next': DEFAULT_NAMESPACE , 'nav-prev': DEFAULT_NAMESPACE , 'nav-right': DEFAULT_NAMESPACE , 'nav-up': DEFAULT_NAMESPACE , 'nav-up-left': DEFAULT_NAMESPACE , 'nav-up-right': DEFAULT_NAMESPACE , 'numOctaves': DEFAULT_NAMESPACE , 'observer': DEFAULT_NAMESPACE , 'offset': DEFAULT_NAMESPACE , 'opacity': DEFAULT_NAMESPACE , 'operator': DEFAULT_NAMESPACE , 'order': DEFAULT_NAMESPACE , 'orient': DEFAULT_NAMESPACE , 'orientation': DEFAULT_NAMESPACE , 'origin': DEFAULT_NAMESPACE , 'overflow': DEFAULT_NAMESPACE , 'overlay': DEFAULT_NAMESPACE , 'overline-position': DEFAULT_NAMESPACE , 'overline-thickness': DEFAULT_NAMESPACE , 'panose-1': DEFAULT_NAMESPACE , 'path': DEFAULT_NAMESPACE , 'pathLength': DEFAULT_NAMESPACE , 'patternContentUnits': DEFAULT_NAMESPACE , 'patternTransform': DEFAULT_NAMESPACE , 'patternUnits': DEFAULT_NAMESPACE , 'phase': DEFAULT_NAMESPACE , 'playbackOrder': DEFAULT_NAMESPACE , 'pointer-events': DEFAULT_NAMESPACE , 'points': DEFAULT_NAMESPACE , 'pointsAtX': DEFAULT_NAMESPACE , 'pointsAtY': DEFAULT_NAMESPACE , 'pointsAtZ': DEFAULT_NAMESPACE , 'preserveAlpha': DEFAULT_NAMESPACE , 'preserveAspectRatio': DEFAULT_NAMESPACE , 'primitiveUnits': DEFAULT_NAMESPACE , 'propagate': DEFAULT_NAMESPACE , 'property': DEFAULT_NAMESPACE , 'r': DEFAULT_NAMESPACE , 'radius': DEFAULT_NAMESPACE , 'refX': DEFAULT_NAMESPACE , 'refY': DEFAULT_NAMESPACE , 'rel': DEFAULT_NAMESPACE , 'rendering-intent': DEFAULT_NAMESPACE , 'repeatCount': DEFAULT_NAMESPACE , 'repeatDur': DEFAULT_NAMESPACE , 'requiredExtensions': DEFAULT_NAMESPACE , 'requiredFeatures': DEFAULT_NAMESPACE , 'requiredFonts': DEFAULT_NAMESPACE , 'requiredFormats': DEFAULT_NAMESPACE , 'resource': DEFAULT_NAMESPACE , 'restart': DEFAULT_NAMESPACE , 'result': DEFAULT_NAMESPACE , 'rev': DEFAULT_NAMESPACE , 'role': DEFAULT_NAMESPACE , 'rotate': DEFAULT_NAMESPACE , 'rx': DEFAULT_NAMESPACE , 'ry': DEFAULT_NAMESPACE , 'scale': DEFAULT_NAMESPACE , 'seed': DEFAULT_NAMESPACE , 'shape-rendering': DEFAULT_NAMESPACE , 'slope': DEFAULT_NAMESPACE , 'snapshotTime': DEFAULT_NAMESPACE , 'spacing': DEFAULT_NAMESPACE , 'specularConstant': DEFAULT_NAMESPACE , 'specularExponent': DEFAULT_NAMESPACE , 'spreadMethod': DEFAULT_NAMESPACE , 'startOffset': DEFAULT_NAMESPACE , 'stdDeviation': DEFAULT_NAMESPACE , 'stemh': DEFAULT_NAMESPACE , 'stemv': DEFAULT_NAMESPACE , 'stitchTiles': DEFAULT_NAMESPACE , 'stop-color': DEFAULT_NAMESPACE , 'stop-opacity': DEFAULT_NAMESPACE , 'strikethrough-position': DEFAULT_NAMESPACE , 'strikethrough-thickness': DEFAULT_NAMESPACE , 'string': DEFAULT_NAMESPACE , 'stroke': DEFAULT_NAMESPACE , 'stroke-dasharray': DEFAULT_NAMESPACE , 'stroke-dashoffset': DEFAULT_NAMESPACE , 'stroke-linecap': DEFAULT_NAMESPACE , 'stroke-linejoin': DEFAULT_NAMESPACE , 'stroke-miterlimit': DEFAULT_NAMESPACE , 'stroke-opacity': DEFAULT_NAMESPACE , 'stroke-width': DEFAULT_NAMESPACE , 'surfaceScale': DEFAULT_NAMESPACE , 'syncBehavior': DEFAULT_NAMESPACE , 'syncBehaviorDefault': DEFAULT_NAMESPACE , 'syncMaster': DEFAULT_NAMESPACE , 'syncTolerance': DEFAULT_NAMESPACE , 'syncToleranceDefault': DEFAULT_NAMESPACE , 'systemLanguage': DEFAULT_NAMESPACE , 'tableValues': DEFAULT_NAMESPACE , 'target': DEFAULT_NAMESPACE , 'targetX': DEFAULT_NAMESPACE , 'targetY': DEFAULT_NAMESPACE , 'text-anchor': DEFAULT_NAMESPACE , 'text-decoration': DEFAULT_NAMESPACE , 'text-rendering': DEFAULT_NAMESPACE , 'textLength': DEFAULT_NAMESPACE , 'timelineBegin': DEFAULT_NAMESPACE , 'title': DEFAULT_NAMESPACE , 'to': DEFAULT_NAMESPACE , 'transform': DEFAULT_NAMESPACE , 'transformBehavior': DEFAULT_NAMESPACE , 'type': DEFAULT_NAMESPACE , 'typeof': DEFAULT_NAMESPACE , 'u1': DEFAULT_NAMESPACE , 'u2': DEFAULT_NAMESPACE , 'underline-position': DEFAULT_NAMESPACE , 'underline-thickness': DEFAULT_NAMESPACE , 'unicode': DEFAULT_NAMESPACE , 'unicode-bidi': DEFAULT_NAMESPACE , 'unicode-range': DEFAULT_NAMESPACE , 'units-per-em': DEFAULT_NAMESPACE , 'v-alphabetic': DEFAULT_NAMESPACE , 'v-hanging': DEFAULT_NAMESPACE , 'v-ideographic': DEFAULT_NAMESPACE , 'v-mathematical': DEFAULT_NAMESPACE , 'values': DEFAULT_NAMESPACE , 'version': DEFAULT_NAMESPACE , 'vert-adv-y': DEFAULT_NAMESPACE , 'vert-origin-x': DEFAULT_NAMESPACE , 'vert-origin-y': DEFAULT_NAMESPACE , 'viewBox': DEFAULT_NAMESPACE , 'viewTarget': DEFAULT_NAMESPACE , 'visibility': DEFAULT_NAMESPACE , 'width': DEFAULT_NAMESPACE , 'widths': DEFAULT_NAMESPACE , 'word-spacing': DEFAULT_NAMESPACE , 'writing-mode': DEFAULT_NAMESPACE , 'x': DEFAULT_NAMESPACE , 'x-height': DEFAULT_NAMESPACE , 'x1': DEFAULT_NAMESPACE , 'x2': DEFAULT_NAMESPACE , 'xChannelSelector': DEFAULT_NAMESPACE , 'xlink:actuate': XLINK_NAMESPACE , 'xlink:arcrole': XLINK_NAMESPACE , 'xlink:href': XLINK_NAMESPACE , 'xlink:role': XLINK_NAMESPACE , 'xlink:show': XLINK_NAMESPACE , 'xlink:title': XLINK_NAMESPACE , 'xlink:type': XLINK_NAMESPACE , 'xml:base': XML_NAMESPACE , 'xml:id': XML_NAMESPACE , 'xml:lang': XML_NAMESPACE , 'xml:space': XML_NAMESPACE , 'y': DEFAULT_NAMESPACE , 'y1': DEFAULT_NAMESPACE , 'y2': DEFAULT_NAMESPACE , 'yChannelSelector': DEFAULT_NAMESPACE , 'z': DEFAULT_NAMESPACE , 'zoomAndPan': DEFAULT_NAMESPACE }; module.exports = namespaces; },{}],6:[function(require,module,exports){ /** * property-map.js * * Necessary to map dom attributes back to vdom properties */ 'use strict'; // invert of https://www.npmjs.com/package/html-attributes var properties = { 'abbr': 'abbr' , 'accept': 'accept' , 'accept-charset': 'acceptCharset' , 'accesskey': 'accessKey' , 'action': 'action' , 'allowfullscreen': 'allowFullScreen' , 'allowtransparency': 'allowTransparency' , 'alt': 'alt' , 'async': 'async' , 'autocomplete': 'autoComplete' , 'autofocus': 'autoFocus' , 'autoplay': 'autoPlay' , 'cellpadding': 'cellPadding' , 'cellspacing': 'cellSpacing' , 'challenge': 'challenge' , 'charset': 'charset' , 'checked': 'checked' , 'cite': 'cite' , 'class': 'className' , 'cols': 'cols' , 'colspan': 'colSpan' , 'command': 'command' , 'content': 'content' , 'contenteditable': 'contentEditable' , 'contextmenu': 'contextMenu' , 'controls': 'controls' , 'coords': 'coords' , 'crossorigin': 'crossOrigin' , 'data': 'data' , 'datetime': 'dateTime' , 'default': 'default' , 'defer': 'defer' , 'dir': 'dir' , 'disabled': 'disabled' , 'download': 'download' , 'draggable': 'draggable' , 'dropzone': 'dropzone' , 'enctype': 'encType' , 'for': 'htmlFor' , 'form': 'form' , 'formaction': 'formAction' , 'formenctype': 'formEncType' , 'formmethod': 'formMethod' , 'formnovalidate': 'formNoValidate' , 'formtarget': 'formTarget' , 'frameBorder': 'frameBorder' , 'headers': 'headers' , 'height': 'height' , 'hidden': 'hidden' , 'high': 'high' , 'href': 'href' , 'hreflang': 'hrefLang' , 'http-equiv': 'httpEquiv' , 'icon': 'icon' , 'id': 'id' , 'inputmode': 'inputMode' , 'ismap': 'isMap' , 'itemid': 'itemId' , 'itemprop': 'itemProp' , 'itemref': 'itemRef' , 'itemscope': 'itemScope' , 'itemtype': 'itemType' , 'kind': 'kind' , 'label': 'label' , 'lang': 'lang' , 'list': 'list' , 'loop': 'loop' , 'manifest': 'manifest' , 'max': 'max' , 'maxlength': 'maxLength' , 'media': 'media' , 'mediagroup': 'mediaGroup' , 'method': 'method' , 'min': 'min' , 'minlength': 'minLength' , 'multiple': 'multiple' , 'muted': 'muted' , 'name': 'name' , 'novalidate': 'noValidate' , 'open': 'open' , 'optimum': 'optimum' , 'pattern': 'pattern' , 'ping': 'ping' , 'placeholder': 'placeholder' , 'poster': 'poster' , 'preload': 'preload' , 'radiogroup': 'radioGroup' , 'readonly': 'readOnly' , 'rel': 'rel' , 'required': 'required' , 'role': 'role' , 'rows': 'rows' , 'rowspan': 'rowSpan' , 'sandbox': 'sandbox' , 'scope': 'scope' , 'scoped': 'scoped' , 'scrolling': 'scrolling' , 'seamless': 'seamless' , 'selected': 'selected' , 'shape': 'shape' , 'size': 'size' , 'sizes': 'sizes' , 'sortable': 'sortable' , 'span': 'span' , 'spellcheck': 'spellCheck' , 'src': 'src' , 'srcdoc': 'srcDoc' , 'srcset': 'srcSet' , 'start': 'start' , 'step': 'step' , 'style': 'style' , 'tabindex': 'tabIndex' , 'target': 'target' , 'title': 'title' , 'translate': 'translate' , 'type': 'type' , 'typemustmatch': 'typeMustMatch' , 'usemap': 'useMap' , 'value': 'value' , 'width': 'width' , 'wmode': 'wmode' , 'wrap': 'wrap' }; module.exports = properties; },{}],7:[function(require,module,exports){ var escape = require('escape-html'); var propConfig = require('./property-config'); var types = propConfig.attributeTypes; var properties = propConfig.properties; var attributeNames = propConfig.attributeNames; var prefixAttribute = memoizeString(function (name) { return escape(name) + '="'; }); module.exports = createAttribute; /** * Create attribute string. * * @param {String} name The name of the property or attribute * @param {*} value The value * @param {Boolean} [isAttribute] Denotes whether `name` is an attribute. * @return {?String} Attribute string || null if not a valid property or custom attribute. */ function createAttribute(name, value, isAttribute) { if (properties.hasOwnProperty(name)) { if (shouldSkip(name, value)) return ''; name = (attributeNames[name] || name).toLowerCase(); var attrType = properties[name]; // for BOOLEAN `value` only has to be truthy // for OVERLOADED_BOOLEAN `value` has to be === true if ((attrType === types.BOOLEAN) || (attrType === types.OVERLOADED_BOOLEAN && value === true)) { return escape(name); } return prefixAttribute(name) + escape(value) + '"'; } else if (isAttribute) { if (value == null) return ''; return prefixAttribute(name) + escape(value) + '"'; } // return null if `name` is neither a valid property nor an attribute return null; } /** * Should skip false boolean attributes. */ function shouldSkip(name, value) { var attrType = properties[name]; return value == null || (attrType === types.BOOLEAN && !value) || (attrType === types.OVERLOADED_BOOLEAN && value === false); } /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeString(callback) { var cache = {}; return function(string) { if (cache.hasOwnProperty(string)) { return cache[string]; } else { return cache[string] = callback.call(this, string); } }; } },{"./property-config":17,"escape-html":9}],8:[function(require,module,exports){ var escape = require('escape-html'); var extend = require('xtend'); var isVNode = require('virtual-dom/vnode/is-vnode'); var isVText = require('virtual-dom/vnode/is-vtext'); var isThunk = require('virtual-dom/vnode/is-thunk'); var isWidget = require('virtual-dom/vnode/is-widget'); var softHook = require('virtual-dom/virtual-hyperscript/hooks/soft-set-hook'); var attrHook = require('virtual-dom/virtual-hyperscript/hooks/attribute-hook'); var paramCase = require('param-case'); var createAttribute = require('./create-attribute'); var voidElements = require('./void-elements'); module.exports = toHTML; function toHTML(node, parent) { if (!node) return ''; if (isThunk(node)) { node = node.render(); } if (isWidget(node) && node.render) { node = node.render(); } if (isVNode(node)) { return openTag(node) + tagContent(node) + closeTag(node); } else if (isVText(node)) { if (parent && parent.tagName.toLowerCase() === 'script') return String(node.text); return escape(String(node.text)); } return ''; } function openTag(node) { var props = node.properties; var ret = '<' + node.tagName.toLowerCase(); for (var name in props) { var value = props[name]; if (value == null) continue; if (name == 'attributes') { value = extend({}, value); for (var attrProp in value) { ret += ' ' + createAttribute(attrProp, value[attrProp], true); } continue; } if (name == 'style') { var css = ''; value = extend({}, value); for (var styleProp in value) { css += paramCase(styleProp) + ': ' + value[styleProp] + '; '; } value = css.trim(); } if (value instanceof softHook || value instanceof attrHook) { ret += ' ' + createAttribute(name, value.value, true); continue; } var attr = createAttribute(name, value); if (attr) ret += ' ' + attr; } return ret + '>'; } function tagContent(node) { var innerHTML = node.properties.innerHTML; if (innerHTML != null) return innerHTML; else { var ret = ''; if (node.children && node.children.length) { for (var i = 0, l = node.children.length; i<l; i++) { var child = node.children[i]; ret += toHTML(child, node); } } return ret; } } function closeTag(node) { var tag = node.tagName.toLowerCase(); return voidElements[tag] ? '' : '</' + tag + '>'; } },{"./create-attribute":7,"./void-elements":18,"escape-html":9,"param-case":15,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":33,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":35,"virtual-dom/vnode/is-thunk":41,"virtual-dom/vnode/is-vnode":43,"virtual-dom/vnode/is-vtext":44,"virtual-dom/vnode/is-widget":45,"xtend":16}],9:[function(require,module,exports){ /*! * escape-html * Copyright(c) 2012-2013 TJ Holowaychuk * Copyright(c) 2015 Andreas Lubbe * Copyright(c) 2015 Tiancheng "Timothy" Gu * MIT Licensed */ 'use strict'; /** * Module variables. * @private */ var matchHtmlRegExp = /["'&<>]/; /** * Module exports. * @public */ module.exports = escapeHtml; /** * Escape special characters in the given string of html. * * @param {string} string The string to escape for inserting into HTML * @return {string} * @public */ function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '&quot;'; break; case 38: // & escape = '&amp;'; break; case 39: // ' escape = '&#39;'; break; case 60: // < escape = '&lt;'; break; case 62: // > escape = '&gt;'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } },{}],10:[function(require,module,exports){ /** * Special language-specific overrides. * * Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt * * @type {Object} */ var LANGUAGES = { tr: { regexp: /\u0130|\u0049|\u0049\u0307/g, map: { '\u0130': '\u0069', '\u0049': '\u0131', '\u0049\u0307': '\u0069' } }, az: { regexp: /[\u0130]/g, map: { '\u0130': '\u0069', '\u0049': '\u0131', '\u0049\u0307': '\u0069' } }, lt: { regexp: /[\u0049\u004A\u012E\u00CC\u00CD\u0128]/g, map: { '\u0049': '\u0069\u0307', '\u004A': '\u006A\u0307', '\u012E': '\u012F\u0307', '\u00CC': '\u0069\u0307\u0300', '\u00CD': '\u0069\u0307\u0301', '\u0128': '\u0069\u0307\u0303' } } } /** * Lowercase a string. * * @param {String} str * @return {String} */ module.exports = function (str, locale) { var lang = LANGUAGES[locale] str = str == null ? '' : String(str) if (lang) { str = str.replace(lang.regexp, function (m) { return lang.map[m] }) } return str.toLowerCase() } },{}],11:[function(require,module,exports){ var lowerCase = require('lower-case') var NON_WORD_REGEXP = require('./vendor/non-word-regexp') var CAMEL_CASE_REGEXP = require('./vendor/camel-case-regexp') var TRAILING_DIGIT_REGEXP = require('./vendor/trailing-digit-regexp') /** * Sentence case a string. * * @param {String} str * @param {String} locale * @param {String} replacement * @return {String} */ module.exports = function (str, locale, replacement) { if (str == null) { return '' } replacement = replacement || ' ' function replace (match, index, string) { if (index === 0 || index === (string.length - match.length)) { return '' } return replacement } str = String(str) // Support camel case ("camelCase" -> "camel Case"). .replace(CAMEL_CASE_REGEXP, '$1 $2') // Support digit groups ("test2012" -> "test 2012"). .replace(TRAILING_DIGIT_REGEXP, '$1 $2') // Remove all non-word characters and replace with a single space. .replace(NON_WORD_REGEXP, replace) // Lower case the entire string. return lowerCase(str, locale) } },{"./vendor/camel-case-regexp":12,"./vendor/non-word-regexp":13,"./vendor/trailing-digit-regexp":14,"lower-case":10}],12:[function(require,module,exports){ module.exports = /([\u0061-\u007A\u00B5\u00DF-\u00F6\u00F8-\u00FF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E-\u0180\u0183\u0185\u0188\u018C\u018D\u0192\u0195\u0199-\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9\u01BA\u01BD-\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233-\u0239\u023C\u023F\u0240\u0242\u0247\u0249\u024B\u024D\u024F-\u0293\u0295-\u02AF\u0371\u0373\u0377\u037B-\u037D\u0390\u03AC-\u03CE\u03D0\u03D1\u03D5-\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF-\u03F3\u03F5\u03F8\u03FB\u03FC\u0430-\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0525\u0527\u0561-\u0587\u1D00-\u1D2B\u1D6B-\u1D77\u1D79-\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95-\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB0-\u1FB4\u1FB6\u1FB7\u1FBE\u1FC2-\u1FC4\u1FC6\u1FC7\u1FD0-\u1FD3\u1FD6\u1FD7\u1FE0-\u1FE7\u1FF2-\u1FF4\u1FF6\u1FF7\u210A\u210E\u210F\u2113\u212F\u2134\u2139\u213C\u213D\u2146-\u2149\u214E\u2184\u2C30-\u2C5E\u2C61\u2C65\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73\u2C74\u2C76-\u2C7B\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3\u2CE4\u2CEC\u2CEE\u2CF3\u2D00-\u2D25\u2D27\u2D2D\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA661\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F-\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771-\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uA78E\uA791\uA793\uA7A1\uA7A3\uA7A5\uA7A7\uA7A9\uA7FA\uFB00-\uFB06\uFB13-\uFB17\uFF41-\uFF5A])([\u0041-\u005A\u00C0-\u00D6\u00D8-\u00DE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178\u0179\u017B\u017D\u0181\u0182\u0184\u0186\u0187\u0189-\u018B\u018E-\u0191\u0193\u0194\u0196-\u0198\u019C\u019D\u019F\u01A0\u01A2\u01A4\u01A6\u01A7\u01A9\u01AC\u01AE\u01AF\u01B1-\u01B3\u01B5\u01B7\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A\u023B\u023D\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u0386\u0388-\u038A\u038C\u038E\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0531-\u0556\u10A0-\u10C5\u10C7\u10CD\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA\uFF21-\uFF3A\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])/g },{}],13:[function(require,module,exports){ module.exports = /[^\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19]+/g },{}],14:[function(require,module,exports){ module.exports = /([\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])([^\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])/g },{}],15:[function(require,module,exports){ var sentenceCase = require('sentence-case'); /** * Param case a string. * * @param {String} string * @param {String} [locale] * @return {String} */ module.exports = function (string, locale) { return sentenceCase(string, locale, '-'); }; },{"sentence-case":11}],16:[function(require,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } },{}],17:[function(require,module,exports){ /** * Attribute types. */ var types = { BOOLEAN: 1, OVERLOADED_BOOLEAN: 2 }; /** * Properties. * * Taken from https://github.com/facebook/react/blob/847357e42e5267b04dd6e297219eaa125ab2f9f4/src/browser/ui/dom/HTMLDOMPropertyConfig.js * */ var properties = { /** * Standard Properties */ accept: true, acceptCharset: true, accessKey: true, action: true, allowFullScreen: types.BOOLEAN, allowTransparency: true, alt: true, async: types.BOOLEAN, autocomplete: true, autofocus: types.BOOLEAN, autoplay: types.BOOLEAN, cellPadding: true, cellSpacing: true, charset: true, checked: types.BOOLEAN, classID: true, className: true, cols: true, colSpan: true, content: true, contentEditable: true, contextMenu: true, controls: types.BOOLEAN, coords: true, crossOrigin: true, data: true, // For `<object />` acts as `src`. dateTime: true, defer: types.BOOLEAN, dir: true, disabled: types.BOOLEAN, download: types.OVERLOADED_BOOLEAN, draggable: true, enctype: true, form: true, formAction: true, formEncType: true, formMethod: true, formNoValidate: types.BOOLEAN, formTarget: true, frameBorder: true, headers: true, height: true, hidden: types.BOOLEAN, href: true, hreflang: true, htmlFor: true, httpEquiv: true, icon: true, id: true, label: true, lang: true, list: true, loop: types.BOOLEAN, manifest: true, marginHeight: true, marginWidth: true, max: true, maxLength: true, media: true, mediaGroup: true, method: true, min: true, multiple: types.BOOLEAN, muted: types.BOOLEAN, name: true, noValidate: types.BOOLEAN, open: true, pattern: true, placeholder: true, poster: true, preload: true, radiogroup: true, readOnly: types.BOOLEAN, rel: true, required: types.BOOLEAN, role: true, rows: true, rowSpan: true, sandbox: true, scope: true, scrolling: true, seamless: types.BOOLEAN, selected: types.BOOLEAN, shape: true, size: true, sizes: true, span: true, spellcheck: true, src: true, srcdoc: true, srcset: true, start: true, step: true, style: true, tabIndex: true, target: true, title: true, type: true, useMap: true, value: true, width: true, wmode: true, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autocapitalize: true, autocorrect: true, // itemProp, itemScope, itemType are for Microdata support. See // http://schema.org/docs/gs.html itemProp: true, itemScope: types.BOOLEAN, itemType: true, // property is supported for OpenGraph in meta tags. property: true }; /** * Properties to attributes mapping. * * The ones not here are simply converted to lower case. */ var attributeNames = { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }; /** * Exports. */ module.exports = { attributeTypes: types, properties: properties, attributeNames: attributeNames }; },{}],18:[function(require,module,exports){ /** * Void elements. * * https://github.com/facebook/react/blob/v0.12.0/src/browser/ui/ReactDOMComponent.js#L99 */ module.exports = { '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 }; },{}],19:[function(require,module,exports){ var diff = require("./vtree/diff.js") module.exports = diff },{"./vtree/diff.js":51}],20:[function(require,module,exports){ /*! * Cross-Browser Split 1.1.1 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com> * Available under the MIT License * ECMAScript compliant, uniform cross-browser split method */ /** * Splits a string into an array of strings using a regex or string separator. Matches of the * separator are not included in the result array. However, if `separator` is a regex that contains * capturing groups, backreferences are spliced into the result each time `separator` is matched. * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably * cross-browser. * @param {String} str String to split. * @param {RegExp|String} separator Regex or string to use for separating the string. * @param {Number} [limit] Maximum number of items to include in the result array. * @returns {Array} Array of substrings. * @example * * // Basic use * split('a b c d', ' '); * // -> ['a', 'b', 'c', 'd'] * * // With limit * split('a b c d', ' ', 2); * // -> ['a', 'b'] * * // Backreferences in result array * split('..word1 word2..', /([a-z]+)(\d+)/i); * // -> ['..', 'word', '1', ' ', 'word', '2', '..'] */ module.exports = (function split(undef) { var nativeSplit = String.prototype.split, compliantExecNpcg = /()??/.exec("")[1] === undef, // NPCG: nonparticipating capturing group self; self = function(str, separator, limit) { // If `separator` is not a regex, use `nativeSplit` if (Object.prototype.toString.call(separator) !== "[object RegExp]") { return nativeSplit.call(str, separator, limit); } var output = [], flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6 (separator.sticky ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator = new RegExp(separator.source, flags + "g"), separator2, match, lastIndex, lastLength; str += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1 limit >>> 0; // ToUint32(limit) while (match = separator.exec(str)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(str.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function() { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undef) { match[i] = undef; } } }); } if (match.length > 1 && match.index < str.length) { Array.prototype.push.apply(output, match.slice(1)); } lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= limit) { break; } } if (separator.lastIndex === match.index) { separator.lastIndex++; // Avoid an infinite loop } } if (lastLastIndex === str.length) { if (lastLength || !separator.test("")) { output.push(""); } } else { output.push(str.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; return self; })(); },{}],21:[function(require,module,exports){ 'use strict'; var OneVersionConstraint = require('individual/one-version'); var MY_VERSION = '7'; OneVersionConstraint('ev-store', MY_VERSION); var hashKey = '__EV_STORE_KEY@' + MY_VERSION; module.exports = EvStore; function EvStore(elem) { var hash = elem[hashKey]; if (!hash) { hash = elem[hashKey] = {}; } return hash; } },{"individual/one-version":23}],22:[function(require,module,exports){ (function (global){ 'use strict'; /*global window, global*/ var root = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}; module.exports = Individual; function Individual(key, value) { if (key in root) { return root[key]; } root[key] = value; return value; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],23:[function(require,module,exports){ 'use strict'; var Individual = require('./index.js'); module.exports = OneVersion; function OneVersion(moduleName, version, defaultValue) { var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName; var enforceKey = key + '_ENFORCE_SINGLETON'; var versionValue = Individual(enforceKey, version); if (versionValue !== version) { throw new Error('Can only have one copy of ' + moduleName + '.\n' + 'You already have version ' + versionValue + ' installed.\n' + 'This means you cannot install version ' + version); } return Individual(key, defaultValue); } },{"./index.js":22}],24:[function(require,module,exports){ (function (global){ var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = require('min-document'); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"min-document":1}],25:[function(require,module,exports){ "use strict"; module.exports = function isObject(x) { return typeof x === "object" && x !== null; }; },{}],26:[function(require,module,exports){ var patch = require("./vdom/patch.js") module.exports = patch },{"./vdom/patch.js":31}],27:[function(require,module,exports){ var isObject = require("is-object") var isHook = require("../vnode/is-vhook.js") module.exports = applyProperties function applyProperties(node, props, previous) { for (var propName in props) { var propValue = props[propName] if (propValue === undefined) { removeProperty(node, propName, propValue, previous); } else if (isHook(propValue)) { removeProperty(node, propName, propValue, previous) if (propValue.hook) { propValue.hook(node, propName, previous ? previous[propName] : undefined) } } else { if (isObject(propValue)) { patchObject(node, props, previous, propName, propValue); } else { node[propName] = propValue } } } } function removeProperty(node, propName, propValue, previous) { if (previous) { var previousValue = previous[propName] if (!isHook(previousValue)) { if (propName === "attributes") { for (var attrName in previousValue) { node.removeAttribute(attrName) } } else if (propName === "style") { for (var i in previousValue) { node.style[i] = "" } } else if (typeof previousValue === "string") { node[propName] = "" } else { node[propName] = null } } else if (previousValue.unhook) { previousValue.unhook(node, propName, propValue) } } } function patchObject(node, props, previous, propName, propValue) { var previousValue = previous ? previous[propName] : undefined // Set attributes if (propName === "attributes") { for (var attrName in propValue) { var attrValue = propValue[attrName] if (attrValue === undefined) { node.removeAttribute(attrName) } else { node.setAttribute(attrName, attrValue) } } return } if(previousValue && isObject(previousValue) && getPrototype(previousValue) !== getPrototype(propValue)) { node[propName] = propValue return } if (!isObject(node[propName])) { node[propName] = {} } var replacer = propName === "style" ? "" : undefined for (var k in propValue) { var value = propValue[k] node[propName][k] = (value === undefined) ? replacer : value } } function getPrototype(value) { if (Object.getPrototypeOf) { return Object.getPrototypeOf(value) } else if (value.__proto__) { return value.__proto__ } else if (value.constructor) { return value.constructor.prototype } } },{"../vnode/is-vhook.js":42,"is-object":25}],28:[function(require,module,exports){ var document = require("global/document") var applyProperties = require("./apply-properties") var isVNode = require("../vnode/is-vnode.js") var isVText = require("../vnode/is-vtext.js") var isWidget = require("../vnode/is-widget.js") var handleThunk = require("../vnode/handle-thunk.js") module.exports = createElement function createElement(vnode, opts) { var doc = opts ? opts.document || document : document var warn = opts ? opts.warn : null vnode = handleThunk(vnode).a if (isWidget(vnode)) { return vnode.init() } else if (isVText(vnode)) { return doc.createTextNode(vnode.text) } else if (!isVNode(vnode)) { if (warn) { warn("Item is not a valid virtual dom node", vnode) } return null } var node = (vnode.namespace === null) ? doc.createElement(vnode.tagName) : doc.createElementNS(vnode.namespace, vnode.tagName) var props = vnode.properties applyProperties(node, props) var children = vnode.children for (var i = 0; i < children.length; i++) { var childNode = createElement(children[i], opts) if (childNode) { node.appendChild(childNode) } } return node } },{"../vnode/handle-thunk.js":40,"../vnode/is-vnode.js":43,"../vnode/is-vtext.js":44,"../vnode/is-widget.js":45,"./apply-properties":27,"global/document":24}],29:[function(require,module,exports){ // Maps a virtual DOM tree onto a real DOM tree in an efficient manner. // We don't want to read all of the DOM nodes in the tree so we use // the in-order tree indexing to eliminate recursion down certain branches. // We only recurse into a DOM node if we know that it contains a child of // interest. var noChild = {} module.exports = domIndex function domIndex(rootNode, tree, indices, nodes) { if (!indices || indices.length === 0) { return {} } else { indices.sort(ascending) return recurse(rootNode, tree, indices, nodes, 0) } } function recurse(rootNode, tree, indices, nodes, rootIndex) { nodes = nodes || {} if (rootNode) { if (indexInRange(indices, rootIndex, rootIndex)) { nodes[rootIndex] = rootNode } var vChildren = tree.children if (vChildren) { var childNodes = rootNode.childNodes for (var i = 0; i < tree.children.length; i++) { rootIndex += 1 var vChild = vChildren[i] || noChild var nextIndex = rootIndex + (vChild.count || 0) // skip recursion down the tree if there are no nodes down here if (indexInRange(indices, rootIndex, nextIndex)) { recurse(childNodes[i], vChild, indices, nodes, rootIndex) } rootIndex = nextIndex } } } return nodes } // Binary search for an index in the interval [left, right] function indexInRange(indices, left, right) { if (indices.length === 0) { return false } var minIndex = 0 var maxIndex = indices.length - 1 var currentIndex var currentItem while (minIndex <= maxIndex) { currentIndex = ((maxIndex + minIndex) / 2) >> 0 currentItem = indices[currentIndex] if (minIndex === maxIndex) { return currentItem >= left && currentItem <= right } else if (currentItem < left) { minIndex = currentIndex + 1 } else if (currentItem > right) { maxIndex = currentIndex - 1 } else { return true } } return false; } function ascending(a, b) { return a > b ? 1 : -1 } },{}],30:[function(require,module,exports){ var applyProperties = require("./apply-properties") var isWidget = require("../vnode/is-widget.js") var VPatch = require("../vnode/vpatch.js") var updateWidget = require("./update-widget") module.exports = applyPatch function applyPatch(vpatch, domNode, renderOptions) { var type = vpatch.type var vNode = vpatch.vNode var patch = vpatch.patch switch (type) { case VPatch.REMOVE: return removeNode(domNode, vNode) case VPatch.INSERT: return insertNode(domNode, patch, renderOptions) case VPatch.VTEXT: return stringPatch(domNode, vNode, patch, renderOptions) case VPatch.WIDGET: return widgetPatch(domNode, vNode, patch, renderOptions) case VPatch.VNODE: return vNodePatch(domNode, vNode, patch, renderOptions) case VPatch.ORDER: reorderChildren(domNode, patch) return domNode case VPatch.PROPS: applyProperties(domNode, patch, vNode.properties) return domNode case VPatch.THUNK: return replaceRoot(domNode, renderOptions.patch(domNode, patch, renderOptions)) default: return domNode } } function removeNode(domNode, vNode) { var parentNode = domNode.parentNode if (parentNode) { parentNode.removeChild(domNode) } destroyWidget(domNode, vNode); return null } function insertNode(parentNode, vNode, renderOptions) { var newNode = renderOptions.render(vNode, renderOptions) if (parentNode) { parentNode.appendChild(newNode) } return parentNode } function stringPatch(domNode, leftVNode, vText, renderOptions) { var newNode if (domNode.nodeType === 3) { domNode.replaceData(0, domNode.length, vText.text) newNode = domNode } else { var parentNode = domNode.parentNode newNode = renderOptions.render(vText, renderOptions) if (parentNode && newNode !== domNode) { parentNode.replaceChild(newNode, domNode) } } return newNode } function widgetPatch(domNode, leftVNode, widget, renderOptions) { var updating = updateWidget(leftVNode, widget) var newNode if (updating) { newNode = widget.update(leftVNode, domNode) || domNode } else { newNode = renderOptions.render(widget, renderOptions) } var parentNode = domNode.parentNode if (parentNode && newNode !== domNode) { parentNode.replaceChild(newNode, domNode) } if (!updating) { destroyWidget(domNode, leftVNode) } return newNode } function vNodePatch(domNode, leftVNode, vNode, renderOptions) { var parentNode = domNode.parentNode var newNode = renderOptions.render(vNode, renderOptions) if (parentNode && newNode !== domNode) { parentNode.replaceChild(newNode, domNode) } return newNode } function destroyWidget(domNode, w) { if (typeof w.destroy === "function" && isWidget(w)) { w.destroy(domNode) } } function reorderChildren(domNode, moves) { var childNodes = domNode.childNodes var keyMap = {} var node var remove var insert for (var i = 0; i < moves.removes.length; i++) { remove = moves.removes[i] node = childNodes[remove.from] if (remove.key) { keyMap[remove.key] = node } domNode.removeChild(node) } var length = childNodes.length for (var j = 0; j < moves.inserts.length; j++) { insert = moves.inserts[j] node = keyMap[insert.key] // this is the weirdest bug i've ever seen in webkit domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to]) } } function replaceRoot(oldRoot, newRoot) { if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) { oldRoot.parentNode.replaceChild(newRoot, oldRoot) } return newRoot; } },{"../vnode/is-widget.js":45,"../vnode/vpatch.js":48,"./apply-properties":27,"./update-widget":32}],31:[function(require,module,exports){ var document = require("global/document") var isArray = require("x-is-array") var render = require("./create-element") var domIndex = require("./dom-index") var patchOp = require("./patch-op") module.exports = patch function patch(rootNode, patches, renderOptions) { renderOptions = renderOptions || {} renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch ? renderOptions.patch : patchRecursive renderOptions.render = renderOptions.render || render return renderOptions.patch(rootNode, patches, renderOptions) } function patchRecursive(rootNode, patches, renderOptions) { var indices = patchIndices(patches) if (indices.length === 0) { return rootNode } var index = domIndex(rootNode, patches.a, indices) var ownerDocument = rootNode.ownerDocument if (!renderOptions.document && ownerDocument !== document) { renderOptions.document = ownerDocument } for (var i = 0; i < indices.length; i++) { var nodeIndex = indices[i] rootNode = applyPatch(rootNode, index[nodeIndex], patches[nodeIndex], renderOptions) } return rootNode } function applyPatch(rootNode, domNode, patchList, renderOptions) { if (!domNode) { return rootNode } var newNode if (isArray(patchList)) { for (var i = 0; i < patchList.length; i++) { newNode = patchOp(patchList[i], domNode, renderOptions) if (domNode === rootNode) { rootNode = newNode } } } else { newNode = patchOp(patchList, domNode, renderOptions) if (domNode === rootNode) { rootNode = newNode } } return rootNode } function patchIndices(patches) { var indices = [] for (var key in patches) { if (key !== "a") { indices.push(Number(key)) } } return indices } },{"./create-element":28,"./dom-index":29,"./patch-op":30,"global/document":24,"x-is-array":52}],32:[function(require,module,exports){ var isWidget = require("../vnode/is-widget.js") module.exports = updateWidget function updateWidget(a, b) { if (isWidget(a) && isWidget(b)) { if ("name" in a && "name" in b) { return a.id === b.id } else { return a.init === b.init } } return false } },{"../vnode/is-widget.js":45}],33:[function(require,module,exports){ 'use strict'; module.exports = AttributeHook; function AttributeHook(namespace, value) { if (!(this instanceof AttributeHook)) { return new AttributeHook(namespace, value); } this.namespace = namespace; this.value = value; } AttributeHook.prototype.hook = function (node, prop, prev) { if (prev && prev.type === 'AttributeHook' && prev.value === this.value && prev.namespace === this.namespace) { return; } node.setAttributeNS(this.namespace, prop, this.value); }; AttributeHook.prototype.unhook = function (node, prop, next) { if (next && next.type === 'AttributeHook' && next.namespace === this.namespace) { return; } var colonPosition = prop.indexOf(':'); var localName = colonPosition > -1 ? prop.substr(colonPosition + 1) : prop; node.removeAttributeNS(this.namespace, localName); }; AttributeHook.prototype.type = 'AttributeHook'; },{}],34:[function(require,module,exports){ 'use strict'; var EvStore = require('ev-store'); module.exports = EvHook; function EvHook(value) { if (!(this instanceof EvHook)) { return new EvHook(value); } this.value = value; } EvHook.prototype.hook = function (node, propertyName) { var es = EvStore(node); var propName = propertyName.substr(3); es[propName] = this.value; }; EvHook.prototype.unhook = function(node, propertyName) { var es = EvStore(node); var propName = propertyName.substr(3); es[propName] = undefined; }; },{"ev-store":21}],35:[function(require,module,exports){ 'use strict'; module.exports = SoftSetHook; function SoftSetHook(value) { if (!(this instanceof SoftSetHook)) { return new SoftSetHook(value); } this.value = value; } SoftSetHook.prototype.hook = function (node, propertyName) { if (node[propertyName] !== this.value) { node[propertyName] = this.value; } }; },{}],36:[function(require,module,exports){ 'use strict'; var isArray = require('x-is-array'); var VNode = require('../vnode/vnode.js'); var VText = require('../vnode/vtext.js'); var isVNode = require('../vnode/is-vnode'); var isVText = require('../vnode/is-vtext'); var isWidget = require('../vnode/is-widget'); var isHook = require('../vnode/is-vhook'); var isVThunk = require('../vnode/is-thunk'); var parseTag = require('./parse-tag.js'); var softSetHook = require('./hooks/soft-set-hook.js'); var evHook = require('./hooks/ev-hook.js'); module.exports = h; function h(tagName, properties, children) { var childNodes = []; var tag, props, key, namespace; if (!children && isChildren(properties)) { children = properties; props = {}; } props = props || properties || {}; tag = parseTag(tagName, props); // support keys if (props.hasOwnProperty('key')) { key = props.key; props.key = undefined; } // support namespace if (props.hasOwnProperty('namespace')) { namespace = props.namespace; props.namespace = undefined; } // fix cursor bug if (tag === 'INPUT' && !namespace && props.hasOwnProperty('value') && props.value !== undefined && !isHook(props.value) ) { props.value = softSetHook(props.value); } transformProperties(props); if (children !== undefined && children !== null) { addChild(children, childNodes, tag, props); } return new VNode(tag, props, childNodes, key, namespace); } function addChild(c, childNodes, tag, props) { if (typeof c === 'string') { childNodes.push(new VText(c)); } else if (typeof c === 'number') { childNodes.push(new VText(String(c))); } else if (isChild(c)) { childNodes.push(c); } else if (isArray(c)) { for (var i = 0; i < c.length; i++) { addChild(c[i], childNodes, tag, props); } } else if (c === null || c === undefined) { return; } else { throw UnexpectedVirtualElement({ foreignObject: c, parentVnode: { tagName: tag, properties: props } }); } } function transformProperties(props) { for (var propName in props) { if (props.hasOwnProperty(propName)) { var value = props[propName]; if (isHook(value)) { continue; } if (propName.substr(0, 3) === 'ev-') { // add ev-foo support props[propName] = evHook(value); } } } } function isChild(x) { return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x); } function isChildren(x) { return typeof x === 'string' || isArray(x) || isChild(x); } function UnexpectedVirtualElement(data) { var err = new Error(); err.type = 'virtual-hyperscript.unexpected.virtual-element'; err.message = 'Unexpected virtual child passed to h().\n' + 'Expected a VNode / Vthunk / VWidget / string but:\n' + 'got:\n' + errorString(data.foreignObject) + '.\n' + 'The parent vnode is:\n' + errorString(data.parentVnode) '\n' + 'Suggested fix: change your `h(..., [ ... ])` callsite.'; err.foreignObject = data.foreignObject; err.parentVnode = data.parentVnode; return err; } function errorString(obj) { try { return JSON.stringify(obj, null, ' '); } catch (e) { return String(obj); } } },{"../vnode/is-thunk":41,"../vnode/is-vhook":42,"../vnode/is-vnode":43,"../vnode/is-vtext":44,"../vnode/is-widget":45,"../vnode/vnode.js":47,"../vnode/vtext.js":49,"./hooks/ev-hook.js":34,"./hooks/soft-set-hook.js":35,"./parse-tag.js":37,"x-is-array":52}],37:[function(require,module,exports){ 'use strict'; var split = require('browser-split'); var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/; var notClassId = /^\.|#/; module.exports = parseTag; function parseTag(tag, props) { if (!tag) { return 'DIV'; } var noId = !(props.hasOwnProperty('id')); var tagParts = split(tag, classIdSplit); var tagName = null; if (notClassId.test(tagParts[1])) { tagName = 'DIV'; } var classes, part, type, i; for (i = 0; i < tagParts.length; i++) { part = tagParts[i]; if (!part) { continue; } type = part.charAt(0); if (!tagName) { tagName = part; } else if (type === '.') { classes = classes || []; classes.push(part.substring(1, part.length)); } else if (type === '#' && noId) { props.id = part.substring(1, part.length); } } if (classes) { if (props.className) { classes.push(props.className); } props.className = classes.join(' '); } return props.namespace ? tagName : tagName.toUpperCase(); } },{"browser-split":20}],38:[function(require,module,exports){ 'use strict'; var DEFAULT_NAMESPACE = null; var EV_NAMESPACE = 'http://www.w3.org/2001/xml-events'; var XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink'; var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'; // http://www.w3.org/TR/SVGTiny12/attributeTable.html // http://www.w3.org/TR/SVG/attindex.html var SVG_PROPERTIES = { 'about': DEFAULT_NAMESPACE, 'accent-height': DEFAULT_NAMESPACE, 'accumulate': DEFAULT_NAMESPACE, 'additive': DEFAULT_NAMESPACE, 'alignment-baseline': DEFAULT_NAMESPACE, 'alphabetic': DEFAULT_NAMESPACE, 'amplitude': DEFAULT_NAMESPACE, 'arabic-form': DEFAULT_NAMESPACE, 'ascent': DEFAULT_NAMESPACE, 'attributeName': DEFAULT_NAMESPACE, 'attributeType': DEFAULT_NAMESPACE, 'azimuth': DEFAULT_NAMESPACE, 'bandwidth': DEFAULT_NAMESPACE, 'baseFrequency': DEFAULT_NAMESPACE, 'baseProfile': DEFAULT_NAMESPACE, 'baseline-shift': DEFAULT_NAMESPACE, 'bbox': DEFAULT_NAMESPACE, 'begin': DEFAULT_NAMESPACE, 'bias': DEFAULT_NAMESPACE, 'by': DEFAULT_NAMESPACE, 'calcMode': DEFAULT_NAMESPACE, 'cap-height': DEFAULT_NAMESPACE, 'class': DEFAULT_NAMESPACE, 'clip': DEFAULT_NAMESPACE, 'clip-path': DEFAULT_NAMESPACE, 'clip-rule': DEFAULT_NAMESPACE, 'clipPathUnits': DEFAULT_NAMESPACE, 'color': DEFAULT_NAMESPACE, 'color-interpolation': DEFAULT_NAMESPACE, 'color-interpolation-filters': DEFAULT_NAMESPACE, 'color-profile': DEFAULT_NAMESPACE, 'color-rendering': DEFAULT_NAMESPACE, 'content': DEFAULT_NAMESPACE, 'contentScriptType': DEFAULT_NAMESPACE, 'contentStyleType': DEFAULT_NAMESPACE, 'cursor': DEFAULT_NAMESPACE, 'cx': DEFAULT_NAMESPACE, 'cy': DEFAULT_NAMESPACE, 'd': DEFAULT_NAMESPACE, 'datatype': DEFAULT_NAMESPACE, 'defaultAction': DEFAULT_NAMESPACE, 'descent': DEFAULT_NAMESPACE, 'diffuseConstant': DEFAULT_NAMESPACE, 'direction': DEFAULT_NAMESPACE, 'display': DEFAULT_NAMESPACE, 'divisor': DEFAULT_NAMESPACE, 'dominant-baseline': DEFAULT_NAMESPACE, 'dur': DEFAULT_NAMESPACE, 'dx': DEFAULT_NAMESPACE, 'dy': DEFAULT_NAMESPACE, 'edgeMode': DEFAULT_NAMESPACE, 'editable': DEFAULT_NAMESPACE, 'elevation': DEFAULT_NAMESPACE, 'enable-background': DEFAULT_NAMESPACE, 'end': DEFAULT_NAMESPACE, 'ev:event': EV_NAMESPACE, 'event': DEFAULT_NAMESPACE, 'exponent': DEFAULT_NAMESPACE, 'externalResourcesRequired': DEFAULT_NAMESPACE, 'fill': DEFAULT_NAMESPACE, 'fill-opacity': DEFAULT_NAMESPACE, 'fill-rule': DEFAULT_NAMESPACE, 'filter': DEFAULT_NAMESPACE, 'filterRes': DEFAULT_NAMESPACE, 'filterUnits': DEFAULT_NAMESPACE, 'flood-color': DEFAULT_NAMESPACE, 'flood-opacity': DEFAULT_NAMESPACE, 'focusHighlight': DEFAULT_NAMESPACE, 'focusable': DEFAULT_NAMESPACE, 'font-family': DEFAULT_NAMESPACE, 'font-size': DEFAULT_NAMESPACE, 'font-size-adjust': DEFAULT_NAMESPACE, 'font-stretch': DEFAULT_NAMESPACE, 'font-style': DEFAULT_NAMESPACE, 'font-variant': DEFAULT_NAMESPACE, 'font-weight': DEFAULT_NAMESPACE, 'format': DEFAULT_NAMESPACE, 'from': DEFAULT_NAMESPACE, 'fx': DEFAULT_NAMESPACE, 'fy': DEFAULT_NAMESPACE, 'g1': DEFAULT_NAMESPACE, 'g2': DEFAULT_NAMESPACE, 'glyph-name': DEFAULT_NAMESPACE, 'glyph-orientation-horizontal': DEFAULT_NAMESPACE, 'glyph-orientation-vertical': DEFAULT_NAMESPACE, 'glyphRef': DEFAULT_NAMESPACE, 'gradientTransform': DEFAULT_NAMESPACE, 'gradientUnits': DEFAULT_NAMESPACE, 'handler': DEFAULT_NAMESPACE, 'hanging': DEFAULT_NAMESPACE, 'height': DEFAULT_NAMESPACE, 'horiz-adv-x': DEFAULT_NAMESPACE, 'horiz-origin-x': DEFAULT_NAMESPACE, 'horiz-origin-y': DEFAULT_NAMESPACE, 'id': DEFAULT_NAMESPACE, 'ideographic': DEFAULT_NAMESPACE, 'image-rendering': DEFAULT_NAMESPACE, 'in': DEFAULT_NAMESPACE, 'in2': DEFAULT_NAMESPACE, 'initialVisibility': DEFAULT_NAMESPACE, 'intercept': DEFAULT_NAMESPACE, 'k': DEFAULT_NAMESPACE, 'k1': DEFAULT_NAMESPACE, 'k2': DEFAULT_NAMESPACE, 'k3': DEFAULT_NAMESPACE, 'k4': DEFAULT_NAMESPACE, 'kernelMatrix': DEFAULT_NAMESPACE, 'kernelUnitLength': DEFAULT_NAMESPACE, 'kerning': DEFAULT_NAMESPACE, 'keyPoints': DEFAULT_NAMESPACE, 'keySplines': DEFAULT_NAMESPACE, 'keyTimes': DEFAULT_NAMESPACE, 'lang': DEFAULT_NAMESPACE, 'lengthAdjust': DEFAULT_NAMESPACE, 'letter-spacing': DEFAULT_NAMESPACE, 'lighting-color': DEFAULT_NAMESPACE, 'limitingConeAngle': DEFAULT_NAMESPACE, 'local': DEFAULT_NAMESPACE, 'marker-end': DEFAULT_NAMESPACE, 'marker-mid': DEFAULT_NAMESPACE, 'marker-start': DEFAULT_NAMESPACE, 'markerHeight': DEFAULT_NAMESPACE, 'markerUnits': DEFAULT_NAMESPACE, 'markerWidth': DEFAULT_NAMESPACE, 'mask': DEFAULT_NAMESPACE, 'maskContentUnits': DEFAULT_NAMESPACE, 'maskUnits': DEFAULT_NAMESPACE, 'mathematical': DEFAULT_NAMESPACE, 'max': DEFAULT_NAMESPACE, 'media': DEFAULT_NAMESPACE, 'mediaCharacterEncoding': DEFAULT_NAMESPACE, 'mediaContentEncodings': DEFAULT_NAMESPACE, 'mediaSize': DEFAULT_NAMESPACE, 'mediaTime': DEFAULT_NAMESPACE, 'method': DEFAULT_NAMESPACE, 'min': DEFAULT_NAMESPACE, 'mode': DEFAULT_NAMESPACE, 'name': DEFAULT_NAMESPACE, 'nav-down': DEFAULT_NAMESPACE, 'nav-down-left': DEFAULT_NAMESPACE, 'nav-down-right': DEFAULT_NAMESPACE, 'nav-left': DEFAULT_NAMESPACE, 'nav-next': DEFAULT_NAMESPACE, 'nav-prev': DEFAULT_NAMESPACE, 'nav-right': DEFAULT_NAMESPACE, 'nav-up': DEFAULT_NAMESPACE, 'nav-up-left': DEFAULT_NAMESPACE, 'nav-up-right': DEFAULT_NAMESPACE, 'numOctaves': DEFAULT_NAMESPACE, 'observer': DEFAULT_NAMESPACE, 'offset': DEFAULT_NAMESPACE, 'opacity': DEFAULT_NAMESPACE, 'operator': DEFAULT_NAMESPACE, 'order': DEFAULT_NAMESPACE, 'orient': DEFAULT_NAMESPACE, 'orientation': DEFAULT_NAMESPACE, 'origin': DEFAULT_NAMESPACE, 'overflow': DEFAULT_NAMESPACE, 'overlay': DEFAULT_NAMESPACE, 'overline-position': DEFAULT_NAMESPACE, 'overline-thickness': DEFAULT_NAMESPACE, 'panose-1': DEFAULT_NAMESPACE, 'path': DEFAULT_NAMESPACE, 'pathLength': DEFAULT_NAMESPACE, 'patternContentUnits': DEFAULT_NAMESPACE, 'patternTransform': DEFAULT_NAMESPACE, 'patternUnits': DEFAULT_NAMESPACE, 'phase': DEFAULT_NAMESPACE, 'playbackOrder': DEFAULT_NAMESPACE, 'pointer-events': DEFAULT_NAMESPACE, 'points': DEFAULT_NAMESPACE, 'pointsAtX': DEFAULT_NAMESPACE, 'pointsAtY': DEFAULT_NAMESPACE, 'pointsAtZ': DEFAULT_NAMESPACE, 'preserveAlpha': DEFAULT_NAMESPACE, 'preserveAspectRatio': DEFAULT_NAMESPACE, 'primitiveUnits': DEFAULT_NAMESPACE, 'propagate': DEFAULT_NAMESPACE, 'property': DEFAULT_NAMESPACE, 'r': DEFAULT_NAMESPACE, 'radius': DEFAULT_NAMESPACE, 'refX': DEFAULT_NAMESPACE, 'refY': DEFAULT_NAMESPACE, 'rel': DEFAULT_NAMESPACE, 'rendering-intent': DEFAULT_NAMESPACE, 'repeatCount': DEFAULT_NAMESPACE, 'repeatDur': DEFAULT_NAMESPACE, 'requiredExtensions': DEFAULT_NAMESPACE, 'requiredFeatures': DEFAULT_NAMESPACE, 'requiredFonts': DEFAULT_NAMESPACE, 'requiredFormats': DEFAULT_NAMESPACE, 'resource': DEFAULT_NAMESPACE, 'restart': DEFAULT_NAMESPACE, 'result': DEFAULT_NAMESPACE, 'rev': DEFAULT_NAMESPACE, 'role': DEFAULT_NAMESPACE, 'rotate': DEFAULT_NAMESPACE, 'rx': DEFAULT_NAMESPACE, 'ry': DEFAULT_NAMESPACE, 'scale': DEFAULT_NAMESPACE, 'seed': DEFAULT_NAMESPACE, 'shape-rendering': DEFAULT_NAMESPACE, 'slope': DEFAULT_NAMESPACE, 'snapshotTime': DEFAULT_NAMESPACE, 'spacing': DEFAULT_NAMESPACE, 'specularConstant': DEFAULT_NAMESPACE, 'specularExponent': DEFAULT_NAMESPACE, 'spreadMethod': DEFAULT_NAMESPACE, 'startOffset': DEFAULT_NAMESPACE, 'stdDeviation': DEFAULT_NAMESPACE, 'stemh': DEFAULT_NAMESPACE, 'stemv': DEFAULT_NAMESPACE, 'stitchTiles': DEFAULT_NAMESPACE, 'stop-color': DEFAULT_NAMESPACE, 'stop-opacity': DEFAULT_NAMESPACE, 'strikethrough-position': DEFAULT_NAMESPACE, 'strikethrough-thickness': DEFAULT_NAMESPACE, 'string': DEFAULT_NAMESPACE, 'stroke': DEFAULT_NAMESPACE, 'stroke-dasharray': DEFAULT_NAMESPACE, 'stroke-dashoffset': DEFAULT_NAMESPACE, 'stroke-linecap': DEFAULT_NAMESPACE, 'stroke-linejoin': DEFAULT_NAMESPACE, 'stroke-miterlimit': DEFAULT_NAMESPACE, 'stroke-opacity': DEFAULT_NAMESPACE, 'stroke-width': DEFAULT_NAMESPACE, 'surfaceScale': DEFAULT_NAMESPACE, 'syncBehavior': DEFAULT_NAMESPACE, 'syncBehaviorDefault': DEFAULT_NAMESPACE, 'syncMaster': DEFAULT_NAMESPACE, 'syncTolerance': DEFAULT_NAMESPACE, 'syncToleranceDefault': DEFAULT_NAMESPACE, 'systemLanguage': DEFAULT_NAMESPACE, 'tableValues': DEFAULT_NAMESPACE, 'target': DEFAULT_NAMESPACE, 'targetX': DEFAULT_NAMESPACE, 'targetY': DEFAULT_NAMESPACE, 'text-anchor': DEFAULT_NAMESPACE, 'text-decoration': DEFAULT_NAMESPACE, 'text-rendering': DEFAULT_NAMESPACE, 'textLength': DEFAULT_NAMESPACE, 'timelineBegin': DEFAULT_NAMESPACE, 'title': DEFAULT_NAMESPACE, 'to': DEFAULT_NAMESPACE, 'transform': DEFAULT_NAMESPACE, 'transformBehavior': DEFAULT_NAMESPACE, 'type': DEFAULT_NAMESPACE, 'typeof': DEFAULT_NAMESPACE, 'u1': DEFAULT_NAMESPACE, 'u2': DEFAULT_NAMESPACE, 'underline-position': DEFAULT_NAMESPACE, 'underline-thickness': DEFAULT_NAMESPACE, 'unicode': DEFAULT_NAMESPACE, 'unicode-bidi': DEFAULT_NAMESPACE, 'unicode-range': DEFAULT_NAMESPACE, 'units-per-em': DEFAULT_NAMESPACE, 'v-alphabetic': DEFAULT_NAMESPACE, 'v-hanging': DEFAULT_NAMESPACE, 'v-ideographic': DEFAULT_NAMESPACE, 'v-mathematical': DEFAULT_NAMESPACE, 'values': DEFAULT_NAMESPACE, 'version': DEFAULT_NAMESPACE, 'vert-adv-y': DEFAULT_NAMESPACE, 'vert-origin-x': DEFAULT_NAMESPACE, 'vert-origin-y': DEFAULT_NAMESPACE, 'viewBox': DEFAULT_NAMESPACE, 'viewTarget': DEFAULT_NAMESPACE, 'visibility': DEFAULT_NAMESPACE, 'width': DEFAULT_NAMESPACE, 'widths': DEFAULT_NAMESPACE, 'word-spacing': DEFAULT_NAMESPACE, 'writing-mode': DEFAULT_NAMESPACE, 'x': DEFAULT_NAMESPACE, 'x-height': DEFAULT_NAMESPACE, 'x1': DEFAULT_NAMESPACE, 'x2': DEFAULT_NAMESPACE, 'xChannelSelector': DEFAULT_NAMESPACE, 'xlink:actuate': XLINK_NAMESPACE, 'xlink:arcrole': XLINK_NAMESPACE, 'xlink:href': XLINK_NAMESPACE, 'xlink:role': XLINK_NAMESPACE, 'xlink:show': XLINK_NAMESPACE, 'xlink:title': XLINK_NAMESPACE, 'xlink:type': XLINK_NAMESPACE, 'xml:base': XML_NAMESPACE, 'xml:id': XML_NAMESPACE, 'xml:lang': XML_NAMESPACE, 'xml:space': XML_NAMESPACE, 'y': DEFAULT_NAMESPACE, 'y1': DEFAULT_NAMESPACE, 'y2': DEFAULT_NAMESPACE, 'yChannelSelector': DEFAULT_NAMESPACE, 'z': DEFAULT_NAMESPACE, 'zoomAndPan': DEFAULT_NAMESPACE }; module.exports = SVGAttributeNamespace; function SVGAttributeNamespace(value) { if (SVG_PROPERTIES.hasOwnProperty(value)) { return SVG_PROPERTIES[value]; } } },{}],39:[function(require,module,exports){ 'use strict'; var isArray = require('x-is-array'); var h = require('./index.js'); var SVGAttributeNamespace = require('./svg-attribute-namespace'); var attributeHook = require('./hooks/attribute-hook'); var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; module.exports = svg; function svg(tagName, properties, children) { if (!children && isChildren(properties)) { children = properties; properties = {}; } properties = properties || {}; // set namespace for svg properties.namespace = SVG_NAMESPACE; var attributes = properties.attributes || (properties.attributes = {}); for (var key in properties) { if (!properties.hasOwnProperty(key)) { continue; } var namespace = SVGAttributeNamespace(key); if (namespace === undefined) { // not a svg attribute continue; } var value = properties[key]; if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { continue; } if (namespace !== null) { // namespaced attribute properties[key] = attributeHook(namespace, value); continue; } attributes[key] = value properties[key] = undefined } return h(tagName, properties, children); } function isChildren(x) { return typeof x === 'string' || isArray(x); } },{"./hooks/attribute-hook":33,"./index.js":36,"./svg-attribute-namespace":38,"x-is-array":52}],40:[function(require,module,exports){ var isVNode = require("./is-vnode") var isVText = require("./is-vtext") var isWidget = require("./is-widget") var isThunk = require("./is-thunk") module.exports = handleThunk function handleThunk(a, b) { var renderedA = a var renderedB = b if (isThunk(b)) { renderedB = renderThunk(b, a) } if (isThunk(a)) { renderedA = renderThunk(a, null) } return { a: renderedA, b: renderedB } } function renderThunk(thunk, previous) { var renderedThunk = thunk.vnode if (!renderedThunk) { renderedThunk = thunk.vnode = thunk.render(previous) } if (!(isVNode(renderedThunk) || isVText(renderedThunk) || isWidget(renderedThunk))) { throw new Error("thunk did not return a valid node"); } return renderedThunk } },{"./is-thunk":41,"./is-vnode":43,"./is-vtext":44,"./is-widget":45}],41:[function(require,module,exports){ module.exports = isThunk function isThunk(t) { return t && t.type === "Thunk" } },{}],42:[function(require,module,exports){ module.exports = isHook function isHook(hook) { return hook && (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") || typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook")) } },{}],43:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualNode function isVirtualNode(x) { return x && x.type === "VirtualNode" && x.version === version } },{"./version":46}],44:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualText function isVirtualText(x) { return x && x.type === "VirtualText" && x.version === version } },{"./version":46}],45:[function(require,module,exports){ module.exports = isWidget function isWidget(w) { return w && w.type === "Widget" } },{}],46:[function(require,module,exports){ module.exports = "2" },{}],47:[function(require,module,exports){ var version = require("./version") var isVNode = require("./is-vnode") var isWidget = require("./is-widget") var isThunk = require("./is-thunk") var isVHook = require("./is-vhook") module.exports = VirtualNode var noProperties = {} var noChildren = [] function VirtualNode(tagName, properties, children, key, namespace) { this.tagName = tagName this.properties = properties || noProperties this.children = children || noChildren this.key = key != null ? String(key) : undefined this.namespace = (typeof namespace === "string") ? namespace : null var count = (children && children.length) || 0 var descendants = 0 var hasWidgets = false var hasThunks = false var descendantHooks = false var hooks for (var propName in properties) { if (properties.hasOwnProperty(propName)) { var property = properties[propName] if (isVHook(property) && property.unhook) { if (!hooks) { hooks = {} } hooks[propName] = property } } } for (var i = 0; i < count; i++) { var child = children[i] if (isVNode(child)) { descendants += child.count || 0 if (!hasWidgets && child.hasWidgets) { hasWidgets = true } if (!hasThunks && child.hasThunks) { hasThunks = true } if (!descendantHooks && (child.hooks || child.descendantHooks)) { descendantHooks = true } } else if (!hasWidgets && isWidget(child)) { if (typeof child.destroy === "function") { hasWidgets = true } } else if (!hasThunks && isThunk(child)) { hasThunks = true; } } this.count = count + descendants this.hasWidgets = hasWidgets this.hasThunks = hasThunks this.hooks = hooks this.descendantHooks = descendantHooks } VirtualNode.prototype.version = version VirtualNode.prototype.type = "VirtualNode" },{"./is-thunk":41,"./is-vhook":42,"./is-vnode":43,"./is-widget":45,"./version":46}],48:[function(require,module,exports){ var version = require("./version") VirtualPatch.NONE = 0 VirtualPatch.VTEXT = 1 VirtualPatch.VNODE = 2 VirtualPatch.WIDGET = 3 VirtualPatch.PROPS = 4 VirtualPatch.ORDER = 5 VirtualPatch.INSERT = 6 VirtualPatch.REMOVE = 7 VirtualPatch.THUNK = 8 module.exports = VirtualPatch function VirtualPatch(type, vNode, patch) { this.type = Number(type) this.vNode = vNode this.patch = patch } VirtualPatch.prototype.version = version VirtualPatch.prototype.type = "VirtualPatch" },{"./version":46}],49:[function(require,module,exports){ var version = require("./version") module.exports = VirtualText function VirtualText(text) { this.text = String(text) } VirtualText.prototype.version = version VirtualText.prototype.type = "VirtualText" },{"./version":46}],50:[function(require,module,exports){ var isObject = require("is-object") var isHook = require("../vnode/is-vhook") module.exports = diffProps function diffProps(a, b) { var diff for (var aKey in a) { if (!(aKey in b)) { diff = diff || {} diff[aKey] = undefined } var aValue = a[aKey] var bValue = b[aKey] if (aValue === bValue) { continue } else if (isObject(aValue) && isObject(bValue)) { if (getPrototype(bValue) !== getPrototype(aValue)) { diff = diff || {} diff[aKey] = bValue } else if (isHook(bValue)) { diff = diff || {} diff[aKey] = bValue } else { var objectDiff = diffProps(aValue, bValue) if (objectDiff) { diff = diff || {} diff[aKey] = objectDiff } } } else { diff = diff || {} diff[aKey] = bValue } } for (var bKey in b) { if (!(bKey in a)) { diff = diff || {} diff[bKey] = b[bKey] } } return diff } function getPrototype(value) { if (Object.getPrototypeOf) { return Object.getPrototypeOf(value) } else if (value.__proto__) { return value.__proto__ } else if (value.constructor) { return value.constructor.prototype } } },{"../vnode/is-vhook":42,"is-object":25}],51:[function(require,module,exports){ var isArray = require("x-is-array") var VPatch = require("../vnode/vpatch") var isVNode = require("../vnode/is-vnode") var isVText = require("../vnode/is-vtext") var isWidget = require("../vnode/is-widget") var isThunk = require("../vnode/is-thunk") var handleThunk = require("../vnode/handle-thunk") var diffProps = require("./diff-props") module.exports = diff function diff(a, b) { var patch = { a: a } walk(a, b, patch, 0) return patch } function walk(a, b, patch, index) { if (a === b) { return } var apply = patch[index] var applyClear = false if (isThunk(a) || isThunk(b)) { thunks(a, b, patch, index) } else if (b == null) { // If a is a widget we will add a remove patch for it // Otherwise any child widgets/hooks must be destroyed. // This prevents adding two remove patches for a widget. if (!isWidget(a)) { clearState(a, patch, index) apply = patch[index] } apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b)) } else if (isVNode(b)) { if (isVNode(a)) { if (a.tagName === b.tagName && a.namespace === b.namespace && a.key === b.key) { var propsPatch = diffProps(a.properties, b.properties) if (propsPatch) { apply = appendPatch(apply, new VPatch(VPatch.PROPS, a, propsPatch)) } apply = diffChildren(a, b, patch, apply, index) } else { apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b)) applyClear = true } } else { apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b)) applyClear = true } } else if (isVText(b)) { if (!isVText(a)) { apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b)) applyClear = true } else if (a.text !== b.text) { apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b)) } } else if (isWidget(b)) { if (!isWidget(a)) { applyClear = true } apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b)) } if (apply) { patch[index] = apply } if (applyClear) { clearState(a, patch, index) } } function diffChildren(a, b, patch, apply, index) { var aChildren = a.children var orderedSet = reorder(aChildren, b.children) var bChildren = orderedSet.children var aLen = aChildren.length var bLen = bChildren.length var len = aLen > bLen ? aLen : bLen for (var i = 0; i < len; i++) { var leftNode = aChildren[i] var rightNode = bChildren[i] index += 1 if (!leftNode) { if (rightNode) { // Excess nodes in b need to be added apply = appendPatch(apply, new VPatch(VPatch.INSERT, null, rightNode)) } } else { walk(leftNode, rightNode, patch, index) } if (isVNode(leftNode) && leftNode.count) { index += leftNode.count } } if (orderedSet.moves) { // Reorder nodes last apply = appendPatch(apply, new VPatch( VPatch.ORDER, a, orderedSet.moves )) } return apply } function clearState(vNode, patch, index) { // TODO: Make this a single walk, not two unhook(vNode, patch, index) destroyWidgets(vNode, patch, index) } // Patch records for all destroyed widgets must be added because we need // a DOM node reference for the destroy function function destroyWidgets(vNode, patch, index) { if (isWidget(vNode)) { if (typeof vNode.destroy === "function") { patch[index] = appendPatch( patch[index], new VPatch(VPatch.REMOVE, vNode, null) ) } } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) { var children = vNode.children var len = children.length for (var i = 0; i < len; i++) { var child = children[i] index += 1 destroyWidgets(child, patch, index) if (isVNode(child) && child.count) { index += child.count } } } else if (isThunk(vNode)) { thunks(vNode, null, patch, index) } } // Create a sub-patch for thunks function thunks(a, b, patch, index) { var nodes = handleThunk(a, b) var thunkPatch = diff(nodes.a, nodes.b) if (hasPatches(thunkPatch)) { patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch) } } function hasPatches(patch) { for (var index in patch) { if (index !== "a") { return true } } return false } // Execute hooks when two nodes are identical function unhook(vNode, patch, index) { if (isVNode(vNode)) { if (vNode.hooks) { patch[index] = appendPatch( patch[index], new VPatch( VPatch.PROPS, vNode, undefinedKeys(vNode.hooks) ) ) } if (vNode.descendantHooks || vNode.hasThunks) { var children = vNode.children var len = children.length for (var i = 0; i < len; i++) { var child = children[i] index += 1 unhook(child, patch, index) if (isVNode(child) && child.count) { index += child.count } } } } else if (isThunk(vNode)) { thunks(vNode, null, patch, index) } } function undefinedKeys(obj) { var result = {} for (var key in obj) { result[key] = undefined } return result } // List diff, naive left to right reordering function reorder(aChildren, bChildren) { // O(M) time, O(M) memory var bChildIndex = keyIndex(bChildren) var bKeys = bChildIndex.keys var bFree = bChildIndex.free if (bFree.length === bChildren.length) { return { children: bChildren, moves: null } } // O(N) time, O(N) memory var aChildIndex = keyIndex(aChildren) var aKeys = aChildIndex.keys var aFree = aChildIndex.free if (aFree.length === aChildren.length) { return { children: bChildren, moves: null } } // O(MAX(N, M)) memory var newChildren = [] var freeIndex = 0 var freeCount = bFree.length var deletedItems = 0 // Iterate through a and match a node in b // O(N) time, for (var i = 0 ; i < aChildren.length; i++) { var aItem = aChildren[i] var itemIndex if (aItem.key) { if (bKeys.hasOwnProperty(aItem.key)) { // Match up the old keys itemIndex = bKeys[aItem.key] newChildren.push(bChildren[itemIndex]) } else { // Remove old keyed items itemIndex = i - deletedItems++ newChildren.push(null) } } else { // Match the item in a with the next free item in b if (freeIndex < freeCount) { itemIndex = bFree[freeIndex++] newChildren.push(bChildren[itemIndex]) } else { // There are no free items in b to match with // the free items in a, so the extra free nodes // are deleted. itemIndex = i - deletedItems++ newChildren.push(null) } } } var lastFreeIndex = freeIndex >= bFree.length ? bChildren.length : bFree[freeIndex] // Iterate through b and append any new keys // O(M) time for (var j = 0; j < bChildren.length; j++) { var newItem = bChildren[j] if (newItem.key) { if (!aKeys.hasOwnProperty(newItem.key)) { // Add any new keyed items // We are adding new items to the end and then sorting them // in place. In future we should insert new items in place. newChildren.push(newItem) } } else if (j >= lastFreeIndex) { // Add any leftover non-keyed items newChildren.push(newItem) } } var simulate = newChildren.slice() var simulateIndex = 0 var removes = [] var inserts = [] var simulateItem for (var k = 0; k < bChildren.length;) { var wantedItem = bChildren[k] simulateItem = simulate[simulateIndex] // remove items while (simulateItem === null && simulate.length) { removes.push(remove(simulate, simulateIndex, null)) simulateItem = simulate[simulateIndex] } if (!simulateItem || simulateItem.key !== wantedItem.key) { // if we need a key in this position... if (wantedItem.key) { if (simulateItem && simulateItem.key) { // if an insert doesn't put this key in place, it needs to move if (bKeys[simulateItem.key] !== k + 1) { removes.push(remove(simulate, simulateIndex, simulateItem.key)) simulateItem = simulate[simulateIndex] // if the remove didn't put the wanted item in place, we need to insert it if (!simulateItem || simulateItem.key !== wantedItem.key) { inserts.push({key: wantedItem.key, to: k}) } // items are matching, so skip ahead else { simulateIndex++ } } else { inserts.push({key: wantedItem.key, to: k}) } } else { inserts.push({key: wantedItem.key, to: k}) } k++ } // a key in simulate has no matching wanted key, remove it else if (simulateItem && simulateItem.key) { removes.push(remove(simulate, simulateIndex, simulateItem.key)) } } else { simulateIndex++ k++ } } // remove all the remaining nodes from simulate while(simulateIndex < simulate.length) { simulateItem = simulate[simulateIndex] removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key)) } // If the only moves we have are deletes then we can just // let the delete patch remove these items. if (removes.length === deletedItems && !inserts.length) { return { children: newChildren, moves: null } } return { children: newChildren, moves: { removes: removes, inserts: inserts } } } function remove(arr, index, key) { arr.splice(index, 1) return { from: index, key: key } } function keyIndex(children) { var keys = {} var free = [] var length = children.length for (var i = 0; i < length; i++) { var child = children[i] if (child.key) { keys[child.key] = i } else { free.push(i) } } return { keys: keys, // A hash of key name to index free: free // An array of unkeyed item indices } } function appendPatch(apply, patch) { if (apply) { if (isArray(apply)) { apply.push(patch) } else { apply = [apply, patch] } return apply } else { return patch } } },{"../vnode/handle-thunk":40,"../vnode/is-thunk":41,"../vnode/is-vnode":43,"../vnode/is-vtext":44,"../vnode/is-widget":45,"../vnode/vpatch":48,"./diff-props":50,"x-is-array":52}],52:[function(require,module,exports){ var nativeIsArray = Array.isArray var toString = Object.prototype.toString module.exports = nativeIsArray || isArray function isArray(obj) { return toString.call(obj) === "[object Array]" } },{}],53:[function(require,module,exports){ "use strict"; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var svg = require("virtual-dom/virtual-hyperscript/svg"); var _require = require("./render-dom"); var makeDOMDriver = _require.makeDOMDriver; var _require2 = require("./render-html"); var makeHTMLDriver = _require2.makeHTMLDriver; var mockDOMSource = require("./mock-dom-source"); var h = require("./virtual-hyperscript"); var hh = require("hyperscript-helpers")(h); var CycleDOM = _extends({ /** * A factory for the DOM driver function. Takes a `container` to define the * target on the existing DOM which this driver will operate on. The output * ("source") of this driver is a collection of Observables queried with: * `DOMSource.select(selector).events(eventType)` returns an Observable of * events of `eventType` happening on the element determined by `selector`. * Just `DOMSource.select(selector).observable` returns an Observable of the * DOM element matched by the given selector. Also, * `DOMSource.select(':root').observable` returns an Observable of DOM element * corresponding to the root (or container) of the app on the DOM. The * `events()` function also allows you to specify the `useCapture` parameter * of the event listener. That is, the full function signature is * `events(eventType, useCapture)` where `useCapture` is by default `false`. * * @param {(String|HTMLElement)} container the DOM selector for the element * (or the element itself) to contain the rendering of the VTrees. * @return {Function} the DOM driver function. The function expects an * Observable of VTree as input, and outputs the source object for this * driver, containing functions `select()` and `dispose()` that can be used * for debugging and testing. * @function makeDOMDriver */ makeDOMDriver: makeDOMDriver, /** * A factory for the HTML driver function. * * @return {Function} the HTML driver function. The function expects an * Observable of Virtual DOM elements as input, and outputs an Observable of * strings as the HTML renderization of the virtual DOM elements. * @function makeHTMLDriver */ makeHTMLDriver: makeHTMLDriver, /** * A shortcut to [virtual-hyperscript]( * https://github.com/Matt-Esch/virtual-dom/tree/master/virtual-hyperscript). * This is a helper for creating VTrees in Views. * @name h */ h: h }, hh, { /** * An adapter around virtual-hyperscript `h()` to allow JSX to be used easily * with Babel. Place the [Babel configuration comment]( * http://babeljs.io/docs/advanced/transformers/other/react/) `@jsx hJSX` at * the top of the ES6 file, make sure you import `hJSX` with * `import {hJSX} from '@cycle/dom'`, and then you can use JSX to create * VTrees. * @name hJSX */ hJSX: function hJSX(tag, attrs) { for (var _len = arguments.length, children = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } return h(tag, attrs, children); }, /** * A shortcut to the svg hyperscript function. * @name svg */ svg: svg, /** * A testing utility which aids in creating a queryable collection of * Observables. Call mockDOMSource giving it an object specifying selectors, * eventTypes and their Observables, and get as output an object following the * same format as the DOM Driver's source. Example: * * ```js * const userEvents = mockDOMSource({ * '.foo': { * 'click': Rx.Observable.just({target: {}}), * 'mouseover': Rx.Observable.just({target: {}}) * }, * '.bar': { * 'scroll': Rx.Observable.just({target: {}}) * } * }); * * // Usage * const click$ = userEvents.select('.foo').events('click'); * ``` * * @param {Object} mockedSelectors an object where keys are selector strings * and values are objects. Those nested objects have eventType strings as keys * and values are Observables you created. * @return {Object} fake DOM source object, containing a function `select()` * which can be used just like the DOM Driver's source. Call * `select(selector).events(eventType)` on the source object to get the * Observable you defined in the input of `mockDOMSource`. * @function mockDOMSource */ mockDOMSource: mockDOMSource }); module.exports = CycleDOM; /** * Shortcuts to * [hyperscript-helpers](https://github.com/ohanhi/hyperscript-helpers). * This is a helper for writing virtual-hyperscript. Create virtual DOM * elements with `div('.wrapper', [ h1('Header') ])` instead of * `h('div.wrapper', [ h('h1', 'Header') ])`. * @name hyperscript-helpers */ },{"./mock-dom-source":55,"./render-dom":56,"./render-html":57,"./virtual-hyperscript":59,"hyperscript-helpers":2,"virtual-dom/virtual-hyperscript/svg":39}],54:[function(require,module,exports){ (function (global){ "use strict"; var Rx = (typeof window !== "undefined" ? window['Rx'] : typeof global !== "undefined" ? global['Rx'] : null); var disposableCreate = Rx.Disposable.create; var CompositeDisposable = Rx.CompositeDisposable; var AnonymousObservable = Rx.AnonymousObservable; function createListener(_ref) { var element = _ref.element; var eventName = _ref.eventName; var handler = _ref.handler; var useCapture = _ref.useCapture; if (element.addEventListener) { element.addEventListener(eventName, handler, useCapture); return disposableCreate(function removeEventListener() { element.removeEventListener(eventName, handler, useCapture); }); } throw new Error("No listener found"); } function createEventListener(_ref2) { var element = _ref2.element; var eventName = _ref2.eventName; var handler = _ref2.handler; var useCapture = _ref2.useCapture; var disposables = new CompositeDisposable(); if (Array.isArray(element)) { for (var i = 0, len = element.length; i < len; i++) { disposables.add(createEventListener({ element: element[i], eventName: eventName, handler: handler, useCapture: useCapture })); } } else if (element) { disposables.add(createListener({ element: element, eventName: eventName, handler: handler, useCapture: useCapture })); } return disposables; } function fromEvent(element, eventName) { var useCapture = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; return new AnonymousObservable(function subscribe(observer) { return createEventListener({ element: element, eventName: eventName, handler: function handler() { observer.onNext(arguments[0]); }, useCapture: useCapture }); }).share(); } module.exports = fromEvent; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],55:[function(require,module,exports){ (function (global){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _rx = (typeof window !== "undefined" ? window['Rx'] : typeof global !== "undefined" ? global['Rx'] : null); var _rx2 = _interopRequireDefault(_rx); var emptyStream = _rx2['default'].Observable.empty(); function getEventsStreamForSelector(mockedEventTypes) { return function getEventsStream(eventType) { for (var key in mockedEventTypes) { if (mockedEventTypes.hasOwnProperty(key) && key === eventType) { return mockedEventTypes[key]; } } return emptyStream; }; } function mockDOMSource() { var mockedSelectors = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; return { select: function select(selector) { for (var key in mockedSelectors) { if (mockedSelectors.hasOwnProperty(key) && key === selector) { return { observable: emptyStream, events: getEventsStreamForSelector(mockedSelectors[key]) }; } } return { observable: emptyStream, events: function events() { return emptyStream; } }; } }; } exports['default'] = mockDOMSource; module.exports = exports['default']; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],56:[function(require,module,exports){ (function (global){ "use strict"; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; })(); var Rx = (typeof window !== "undefined" ? window['Rx'] : typeof global !== "undefined" ? global['Rx'] : null); var fromEvent = require("./fromevent"); var VDOM = { h: require("./virtual-hyperscript"), diff: require("virtual-dom/diff"), patch: require("virtual-dom/patch"), parse: typeof window !== "undefined" ? require("vdom-parser") : function () {} }; var _require = require("./transposition"); var transposeVTree = _require.transposeVTree; var matchesSelector = undefined; // Try-catch to prevent unnecessary import of DOM-specifics in Node.js env: try { matchesSelector = require("matches-selector"); } catch (err) { matchesSelector = function () {}; } function isElement(obj) { return typeof HTMLElement === "object" ? obj instanceof HTMLElement || obj instanceof DocumentFragment : //DOM2 obj && typeof obj === "object" && obj !== null && (obj.nodeType === 1 || obj.nodeType === 11) && typeof obj.nodeName === "string"; } function wrapTopLevelVTree(vtree, rootElem) { var _vtree$properties$id = vtree.properties.id; var vtreeId = _vtree$properties$id === undefined ? "" : _vtree$properties$id; var _vtree$properties$className = vtree.properties.className; var vtreeClass = _vtree$properties$className === undefined ? "" : _vtree$properties$className; var sameId = vtreeId === rootElem.id; var sameClass = vtreeClass === rootElem.className; var sameTagName = vtree.tagName.toUpperCase() === rootElem.tagName; if (sameId && sameClass && sameTagName) { return vtree; } var attrs = {}; if (rootElem.id) { attrs.id = rootElem.id; } if (rootElem.className) { attrs.className = rootElem.className; } return VDOM.h(rootElem.tagName, attrs, [vtree]); } function makeDiffAndPatchToElement$(rootElem) { return function diffAndPatchToElement$(_ref) { var _ref2 = _slicedToArray(_ref, 2); var oldVTree = _ref2[0]; var newVTree = _ref2[1]; if (typeof newVTree === "undefined") { return Rx.Observable.empty(); } var prevVTree = wrapTopLevelVTree(oldVTree, rootElem); var nextVTree = wrapTopLevelVTree(newVTree, rootElem); /* eslint-disable */ rootElem = VDOM.patch(rootElem, VDOM.diff(prevVTree, nextVTree)); /* eslint-enable */ return Rx.Observable.just(rootElem); }; } function renderRawRootElem$(vtree$, domContainer) { var diffAndPatchToElement$ = makeDiffAndPatchToElement$(domContainer); return vtree$.flatMapLatest(transposeVTree).startWith(VDOM.parse(domContainer)).pairwise().flatMap(diffAndPatchToElement$); } function isolateSource(source, scope) { return source.select(".cycle-scope-" + scope); } function isolateSink(sink, scope) { return sink.map(function (vtree) { var _vtree$properties$className2 = vtree.properties.className; var vtreeClass = _vtree$properties$className2 === undefined ? "" : _vtree$properties$className2; var c = (vtreeClass + " cycle-scope-" + scope).trim(); vtree.properties.className = c; return vtree; }); } function makeIsStrictlyInRootScope(rootList, namespace) { var classIsForeign = function classIsForeign(c) { var matched = c.match(/cycle-scope-(\S+)/); return matched && namespace.indexOf("." + c) === -1; }; return function isStrictlyInRootScope(leaf) { for (var el = leaf.parentElement; el !== null; el = el.parentElement) { if (rootList.indexOf(el) >= 0) { return true; } var classList = el.classList || String.prototype.split.call(el.className, " "); if (Array.prototype.some.call(classList, classIsForeign)) { return false; } } return true; }; } function makeEventsSelector(element$) { return function events(eventName) { var useCapture = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; if (typeof eventName !== "string") { throw new Error("DOM driver's events() expects argument to be a " + "string representing the event type to listen for."); } return element$.flatMapLatest(function (elements) { if (elements.length === 0) { return Rx.Observable.empty(); } return fromEvent(elements, eventName, useCapture); }).share(); }; } function makeElementSelector(rootEl$) { return function select(selector) { if (typeof selector !== "string") { throw new Error("DOM driver's select() expects the argument to be a " + "string as a CSS selector"); } var namespace = this.namespace; var scopedSelector = (namespace.join(" ") + " " + selector).trim(); var element$ = selector.trim() === ":root" ? rootEl$ : rootEl$.map(function (x) { var array = Array.isArray(x) ? x : [x]; return array.map(function (element) { if (matchesSelector(element, scopedSelector)) { return [element]; } else { var nodeList = element.querySelectorAll(scopedSelector); return Array.prototype.slice.call(nodeList); } }).reduce(function (prev, curr) { return prev.concat(curr); }, []).filter(makeIsStrictlyInRootScope(array, namespace)); }); return { observable: element$, namespace: namespace.concat(selector), select: makeElementSelector(element$), events: makeEventsSelector(element$), isolateSource: isolateSource, isolateSink: isolateSink }; }; } function validateDOMSink(vtree$) { if (!vtree$ || typeof vtree$.subscribe !== "function") { throw new Error("The DOM driver function expects as input an " + "Observable of virtual DOM elements"); } } function makeDOMDriver(container) { // Find and prepare the container var domContainer = typeof container === "string" ? document.querySelector(container) : container; // Check pre-conditions if (typeof container === "string" && domContainer === null) { throw new Error("Cannot render into unknown element `" + container + "`"); } else if (!isElement(domContainer)) { throw new Error("Given container is not a DOM element neither a selector " + "string."); } return function domDriver(vtree$) { validateDOMSink(vtree$); var rootElem$ = renderRawRootElem$(vtree$, domContainer).startWith(domContainer).replay(null, 1); var disposable = rootElem$.connect(); return { namespace: [], select: makeElementSelector(rootElem$), dispose: disposable.dispose.bind(disposable), isolateSource: isolateSource, isolateSink: isolateSink }; }; } module.exports = { isElement: isElement, wrapTopLevelVTree: wrapTopLevelVTree, makeDiffAndPatchToElement$: makeDiffAndPatchToElement$, renderRawRootElem$: renderRawRootElem$, validateDOMSink: validateDOMSink, makeDOMDriver: makeDOMDriver }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./fromevent":54,"./transposition":58,"./virtual-hyperscript":59,"matches-selector":3,"vdom-parser":4,"virtual-dom/diff":19,"virtual-dom/patch":26}],57:[function(require,module,exports){ (function (global){ "use strict"; var Rx = (typeof window !== "undefined" ? window['Rx'] : typeof global !== "undefined" ? global['Rx'] : null); var toHTML = require("vdom-to-html"); var _require = require("./transposition"); var transposeVTree = _require.transposeVTree; function makeBogusSelect() { return function select() { return { observable: Rx.Observable.empty(), events: function events() { return Rx.Observable.empty(); } }; }; } function makeHTMLDriver() { return function htmlDriver(vtree$) { var output$ = vtree$.flatMapLatest(transposeVTree).last().map(toHTML); output$.select = makeBogusSelect(); return output$; }; } module.exports = { makeBogusSelect: makeBogusSelect, makeHTMLDriver: makeHTMLDriver }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./transposition":58,"vdom-to-html":8}],58:[function(require,module,exports){ (function (global){ "use strict"; var Rx = (typeof window !== "undefined" ? window['Rx'] : typeof global !== "undefined" ? global['Rx'] : null); var VirtualNode = require("virtual-dom/vnode/vnode"); /** * Converts a tree of VirtualNode|Observable<VirtualNode> into * Observable<VirtualNode>. */ function transposeVTree(vtree) { if (typeof vtree.subscribe === "function") { return vtree.flatMap(transposeVTree); } else if (vtree.type === "VirtualText") { return Rx.Observable.just(vtree); } else if (vtree.type === "VirtualNode" && Array.isArray(vtree.children) && vtree.children.length > 0) { return Rx.Observable.combineLatest(vtree.children.map(transposeVTree), function () { for (var _len = arguments.length, arr = Array(_len), _key = 0; _key < _len; _key++) { arr[_key] = arguments[_key]; } return new VirtualNode(vtree.tagName, vtree.properties, arr, vtree.key, vtree.namespace); }); } else if (vtree.type === "VirtualNode" || vtree.type === "Widget" || vtree.type === "Thunk") { return Rx.Observable.just(vtree); } else { throw new Error("Unhandled case in transposeVTree()"); } } module.exports = { transposeVTree: transposeVTree }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"virtual-dom/vnode/vnode":47}],59:[function(require,module,exports){ /* eslint-disable */ 'use strict'; var isArray = require('x-is-array'); var VNode = require('virtual-dom/vnode/vnode.js'); var VText = require('virtual-dom/vnode/vtext.js'); var isVNode = require('virtual-dom/vnode/is-vnode'); var isVText = require('virtual-dom/vnode/is-vtext'); var isWidget = require('virtual-dom/vnode/is-widget'); var isHook = require('virtual-dom/vnode/is-vhook'); var isVThunk = require('virtual-dom/vnode/is-thunk'); var parseTag = require('virtual-dom/virtual-hyperscript/parse-tag.js'); var softSetHook = require('virtual-dom/virtual-hyperscript/hooks/soft-set-hook.js'); var evHook = require('virtual-dom/virtual-hyperscript/hooks/ev-hook.js'); module.exports = h; function h(tagName, properties, children) { var childNodes = []; var tag, props, key, namespace; if (!children && isChildren(properties)) { children = properties; props = {}; } props = props || properties || {}; tag = parseTag(tagName, props); // support keys if (props.hasOwnProperty('key')) { key = props.key; props.key = undefined; } // support namespace if (props.hasOwnProperty('namespace')) { namespace = props.namespace; props.namespace = undefined; } // fix cursor bug if (tag === 'INPUT' && !namespace && props.hasOwnProperty('value') && props.value !== undefined && !isHook(props.value)) { props.value = softSetHook(props.value); } transformProperties(props); if (children !== undefined && children !== null) { addChild(children, childNodes, tag, props); } return new VNode(tag, props, childNodes, key, namespace); } function addChild(c, childNodes, tag, props) { if (typeof c === 'string') { childNodes.push(new VText(c)); } else if (typeof c === 'number') { childNodes.push(new VText(String(c))); } else if (isChild(c)) { childNodes.push(c); } else if (isArray(c)) { for (var i = 0; i < c.length; i++) { addChild(c[i], childNodes, tag, props); } } else if (c === null || c === undefined) { return; } else { throw UnexpectedVirtualElement({ foreignObject: c, parentVnode: { tagName: tag, properties: props } }); } } function transformProperties(props) { for (var propName in props) { if (props.hasOwnProperty(propName)) { var value = props[propName]; if (isHook(value)) { continue; } if (propName.substr(0, 3) === 'ev-') { // add ev-foo support props[propName] = evHook(value); } } } } // START Cycle.js-specific code >>>>>>>> function isObservable(x) { return x && typeof x.subscribe === 'function'; } function isChild(x) { return isVNode(x) || isVText(x) || isObservable(x) || isWidget(x) || isVThunk(x); } // END Cycle.js-specific code <<<<<<<<<< function isChildren(x) { return typeof x === 'string' || isArray(x) || isChild(x); } function UnexpectedVirtualElement(data) { var err = new Error(); err.type = 'virtual-hyperscript.unexpected.virtual-element'; err.message = 'Unexpected virtual child passed to h().\n' + 'Expected a VNode / Vthunk / VWidget / string but:\n' + 'got:\n' + errorString(data.foreignObject) + '.\n' + 'The parent vnode is:\n' + errorString(data.parentVnode); '\n' + 'Suggested fix: change your `h(..., [ ... ])` callsite.'; err.foreignObject = data.foreignObject; err.parentVnode = data.parentVnode; return err; } function errorString(obj) { try { return JSON.stringify(obj, null, ' '); } catch (e) { return String(obj); } } /* eslint-enable */ },{"virtual-dom/virtual-hyperscript/hooks/ev-hook.js":34,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook.js":35,"virtual-dom/virtual-hyperscript/parse-tag.js":37,"virtual-dom/vnode/is-thunk":41,"virtual-dom/vnode/is-vhook":42,"virtual-dom/vnode/is-vnode":43,"virtual-dom/vnode/is-vtext":44,"virtual-dom/vnode/is-widget":45,"virtual-dom/vnode/vnode.js":47,"virtual-dom/vnode/vtext.js":49,"x-is-array":52}]},{},[53])(53) });
Examples/UIExplorer/AdSupportIOSExample.js
NishanthShankar/react-native
/** * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @flow */ 'use strict'; var React = require('react-native'); var { AdSupportIOS, StyleSheet, Text, View, } = React; exports.framework = 'React'; exports.title = 'Advertising ID'; exports.description = 'Example of using the ad support API.'; exports.examples = [ { title: 'Ad Support IOS', render: function(): ReactElement { return <AdSupportIOSExample />; }, } ]; var AdSupportIOSExample = React.createClass({ getInitialState: function() { return { deviceID: 'No IDFA yet', hasAdvertiserTracking: 'unset', }; }, componentDidMount: function() { AdSupportIOS.getAdvertisingId( this._onDeviceIDSuccess, this._onDeviceIDFailure ); AdSupportIOS.getAdvertisingTrackingEnabled( this._onHasTrackingSuccess, this._onHasTrackingFailure ); }, _onHasTrackingSuccess: function(hasTracking) { this.setState({ 'hasAdvertiserTracking': hasTracking, }); }, _onHasTrackingFailure: function(e) { this.setState({ 'hasAdvertiserTracking': 'Error!', }); }, _onDeviceIDSuccess: function(deviceID) { this.setState({ 'deviceID': deviceID, }); }, _onDeviceIDFailure: function(e) { this.setState({ 'deviceID': 'Error!', }); }, render: function() { return ( <View> <Text> <Text style={styles.title}>Advertising ID: </Text> {JSON.stringify(this.state.deviceID)} </Text> <Text> <Text style={styles.title}>Has Advertiser Tracking: </Text> {JSON.stringify(this.state.hasAdvertiserTracking)} </Text> </View> ); } }); var styles = StyleSheet.create({ title: { fontWeight: '500', }, });
tests/react/jsx_spread.js
paulshen/flow
/* @flow */ var React = require('react'); var Foo = React.createClass({ propTypes: { bar: React.PropTypes.string.isRequired, }, }); var props = {bar: 42}; var blah = <Foo {...props} />; // error bar, number given string expected
src/svg-icons/action/store.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionStore = (props) => ( <SvgIcon {...props}> <path d="M20 4H4v2h16V4zm1 10v-2l-1-5H4l-1 5v2h1v6h10v-6h4v6h2v-6h1zm-9 4H6v-4h6v4z"/> </SvgIcon> ); ActionStore = pure(ActionStore); ActionStore.displayName = 'ActionStore'; ActionStore.muiName = 'SvgIcon'; export default ActionStore;
ajax/libs/primereact/6.6.0/picklist/picklist.cjs.min.js
cdnjs/cdnjs
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("primereact/core"),n=require("primereact/button");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=o(e);function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function l(e,t,n){return t&&s(e.prototype,t),n&&s(e,n),e}function a(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function c(e,t){return(c=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function p(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&c(e,t)}function u(e){return(u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function h(e,t){return!t||"object"!==u(t)&&"function"!=typeof t?a(e):t}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function d(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function v(){return(v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e}).apply(this,arguments)}function g(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=e[n];return o}function m(e){if(Array.isArray(e))return g(e)}function y(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function b(e,t){if(e){if("string"==typeof e)return g(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?g(e,t):void 0}}function S(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function k(e){return m(e)||y(e)||b(e)||S()}function T(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}var C=function(n){p(u,e.Component);var o,s,c=(o=u,s=T(),function(){var e,t=f(o);if(s){var n=f(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return h(this,e)});function u(e){var t;return i(this,u),(t=c.call(this,e)).onClick=t.onClick.bind(a(t)),t.onKeyDown=t.onKeyDown.bind(a(t)),t}return l(u,[{key:"onClick",value:function(e){this.props.onClick&&this.props.onClick({originalEvent:e,value:this.props.value})}},{key:"onKeyDown",value:function(e){this.props.onKeyDown&&this.props.onKeyDown({originalEvent:e,value:this.props.value})}},{key:"render",value:function(){var e=this.props.template?this.props.template(this.props.value):this.props.value,n=t.classNames("p-picklist-item",{"p-highlight":this.props.selected},this.props.className);return r.default.createElement("li",{className:n,onClick:this.onClick,onKeyDown:this.onKeyDown,tabIndex:this.props.tabIndex,role:"option","aria-selected":this.props.selected},e,r.default.createElement(t.Ripple,null))}}]),u}();function E(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}d(C,"defaultProps",{value:null,className:null,template:null,selected:!1,tabIndex:null,onClick:null,onKeyDown:null});var R=function(n){p(u,e.Component);var o,s,c=(o=u,s=E(),function(){var e,t=f(o);if(s){var n=f(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return h(this,e)});function u(e){var t;return i(this,u),(t=c.call(this,e)).onItemClick=t.onItemClick.bind(a(t)),t.onItemKeyDown=t.onItemKeyDown.bind(a(t)),t}return l(u,[{key:"onItemClick",value:function(e){var n=e.originalEvent,o=e.value,r=k(this.props.selection),i=t.ObjectUtils.findIndexInList(o,r,this.props.dataKey),s=-1!==i;if(this.props.metaKeySelection){var l=n.metaKey||n.ctrlKey;s&&l?r.splice(i,1):(l||(r.length=0),r.push(o))}else s?r.splice(i,1):r.push(o);this.props.onSelectionChange&&this.props.onSelectionChange({event:n,value:r})}},{key:"onItemKeyDown",value:function(e){var t=e.originalEvent.currentTarget;switch(e.originalEvent.which){case 40:var n=this.findNextItem(t);n&&n.focus(),e.originalEvent.preventDefault();break;case 38:var o=this.findPrevItem(t);o&&o.focus(),e.originalEvent.preventDefault();break;case 13:this.onItemClick(e),e.originalEvent.preventDefault()}}},{key:"findNextItem",value:function(e){var n=e.nextElementSibling;return n?t.DomHandler.hasClass(n,"p-picklist-item")?n:this.findNextItem(n):null}},{key:"findPrevItem",value:function(e){var n=e.previousElementSibling;return n?t.DomHandler.hasClass(n,"p-picklist-item")?n:this.findPrevItem(n):null}},{key:"isSelected",value:function(e){return-1!==t.ObjectUtils.findIndexInList(e,this.props.selection,this.props.dataKey)}},{key:"render",value:function(){var e=this,n=null,o=null,i=t.classNames("p-picklist-list-wrapper",this.props.className),s=t.classNames("p-picklist-list",this.props.listClassName);return this.props.header&&(n=r.default.createElement("div",{className:"p-picklist-header"},t.ObjectUtils.getJSXElement(this.props.header,this.props))),this.props.list&&(o=this.props.list.map((function(t,n){return r.default.createElement(C,{key:JSON.stringify(t),value:t,template:e.props.itemTemplate,selected:e.isSelected(t),onClick:e.onItemClick,onKeyDown:e.onItemKeyDown,tabIndex:e.props.tabIndex})}))),r.default.createElement("div",{ref:this.props.forwardRef,className:i},n,r.default.createElement("ul",{className:s,style:this.props.style,role:"listbox","aria-multiselectable":!0},o))}}]),u}(),w=r.default.forwardRef((function(e,t){return r.default.createElement(R,v({forwardRef:t},e))}));function I(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}var K=function(o){p(d,e.Component);var s,c,u=(s=d,c=I(),function(){var e,t=f(s);if(c){var n=f(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return h(this,e)});function d(e){var t;return i(this,d),(t=u.call(this,e)).moveUp=t.moveUp.bind(a(t)),t.moveTop=t.moveTop.bind(a(t)),t.moveDown=t.moveDown.bind(a(t)),t.moveBottom=t.moveBottom.bind(a(t)),t}return l(d,[{key:"moveUp",value:function(e){var n=this.props.selection;if(n&&n.length){for(var o=k(this.props.list),r=0;r<n.length;r++){var i=t.ObjectUtils.findIndexInList(n[r],o,this.props.dataKey);if(0===i)break;var s=o[i-1];o[i-1]=o[i],o[i]=s}this.props.onReorder&&this.props.onReorder({originalEvent:e,value:o,direction:"up"})}}},{key:"moveTop",value:function(e){var n=this.props.selection;if(n&&n.length){for(var o=k(this.props.list),r=0;r<n.length;r++){var i=t.ObjectUtils.findIndexInList(n[r],o,this.props.dataKey);if(0===i)break;var s=o.splice(i,1)[0];o.unshift(s)}this.props.onReorder&&this.props.onReorder({originalEvent:e,value:o,direction:"top"})}}},{key:"moveDown",value:function(e){var n=this.props.selection;if(n&&n.length){for(var o=k(this.props.list),r=n.length-1;r>=0;r--){var i=t.ObjectUtils.findIndexInList(n[r],o,this.props.dataKey);if(i===o.length-1)break;var s=o[i+1];o[i+1]=o[i],o[i]=s}this.props.onReorder&&this.props.onReorder({originalEvent:e,value:o,direction:"down"}),this.movedDown=!0}}},{key:"moveBottom",value:function(e){var n=this.props.selection;if(n&&n.length){for(var o=k(this.props.list),r=n.length-1;r>=0;r--){var i=t.ObjectUtils.findIndexInList(n[r],o,this.props.dataKey);if(i===o.length-1)break;var s=o.splice(i,1)[0];o.push(s)}this.props.onReorder&&this.props.onReorder({originalEvent:e,value:o,direction:"bottom"})}}},{key:"render",value:function(){var e=!this.props.selection.length,o=t.classNames("p-picklist-buttons",this.props.className);return r.default.createElement("div",{className:o},r.default.createElement(n.Button,{disabled:e,type:"button",icon:"pi pi-angle-up",onClick:this.moveUp}),r.default.createElement(n.Button,{disabled:e,type:"button",icon:"pi pi-angle-double-up",onClick:this.moveTop}),r.default.createElement(n.Button,{disabled:e,type:"button",icon:"pi pi-angle-down",onClick:this.moveDown}),r.default.createElement(n.Button,{disabled:e,type:"button",icon:"pi pi-angle-double-down",onClick:this.moveBottom}))}}]),d}();function O(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}var x=function(o){p(d,e.Component);var s,c,u=(s=d,c=O(),function(){var e,t=f(s);if(c){var n=f(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return h(this,e)});function d(e){var t;return i(this,d),(t=u.call(this,e)).moveRight=t.moveRight.bind(a(t)),t.moveAllRight=t.moveAllRight.bind(a(t)),t.moveLeft=t.moveLeft.bind(a(t)),t.moveAllLeft=t.moveAllLeft.bind(a(t)),t}return l(d,[{key:"moveRight",value:function(e){var n=this.props.sourceSelection;if(n&&n.length){for(var o=k(this.props.target),r=k(this.props.source),i=0;i<n.length;i++){var s=n[i];-1===t.ObjectUtils.findIndexInList(s,o,this.props.dataKey)&&o.push(r.splice(t.ObjectUtils.findIndexInList(s,r,this.props.dataKey),1)[0])}this.props.onTransfer&&this.props.onTransfer({originalEvent:e,source:r,target:o,direction:"toTarget"})}}},{key:"moveAllRight",value:function(e){if(this.props.source){var t=[].concat(k(this.props.target),k(this.props.source));this.props.onTransfer&&this.props.onTransfer({originalEvent:e,source:[],target:t,direction:"allToTarget"})}}},{key:"moveLeft",value:function(e){var n=this.props.targetSelection;if(n&&n.length){for(var o=k(this.props.target),r=k(this.props.source),i=0;i<n.length;i++){var s=n[i];-1===t.ObjectUtils.findIndexInList(s,r,this.props.dataKey)&&r.push(o.splice(t.ObjectUtils.findIndexInList(s,o,this.props.dataKey),1)[0])}this.props.onTransfer&&this.props.onTransfer({originalEvent:e,source:r,target:o,direction:"toSource"})}}},{key:"moveAllLeft",value:function(e){if(this.props.source){var t=[].concat(k(this.props.source),k(this.props.target));this.props.onTransfer&&this.props.onTransfer({originalEvent:e,source:t,target:[],direction:"allToSource"})}}},{key:"render",value:function(){var e=!this.props.sourceSelection.length,o=!this.props.targetSelection.length,i=!this.props.source.length,s=!this.props.target.length,l=t.classNames("p-picklist-buttons p-picklist-transfer-buttons",this.props.className);return r.default.createElement("div",{className:l},r.default.createElement(n.Button,{disabled:e,type:"button",icon:"pi pi-angle-right",onClick:this.moveRight}),r.default.createElement(n.Button,{disabled:i,type:"button",icon:"pi pi-angle-double-right",onClick:this.moveAllRight}),r.default.createElement(n.Button,{disabled:o,type:"button",icon:"pi pi-angle-left",onClick:this.moveLeft}),r.default.createElement(n.Button,{disabled:s,type:"button",icon:"pi pi-angle-double-left",onClick:this.moveAllLeft}))}}]),d}();function N(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}var D=function(n){p(u,e.Component);var o,s,c=(o=u,s=N(),function(){var e,t=f(o);if(s){var n=f(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return h(this,e)});function u(e){var t;return i(this,u),(t=c.call(this,e)).state={},t.props.onSourceSelectionChange||(t.state.sourceSelection=[]),t.props.onTargetSelectionChange||(t.state.targetSelection=[]),t.onSourceReorder=t.onSourceReorder.bind(a(t)),t.onTargetReorder=t.onTargetReorder.bind(a(t)),t.onTransfer=t.onTransfer.bind(a(t)),t}return l(u,[{key:"getSourceSelection",value:function(){return this.props.onSourceSelectionChange?this.props.sourceSelection:this.state.sourceSelection}},{key:"getTargetSelection",value:function(){return this.props.onTargetSelectionChange?this.props.targetSelection:this.state.targetSelection}},{key:"onSourceReorder",value:function(e){this.handleChange(e,e.value,this.props.target),this.reorderedListElement=this.sourceListElement,this.reorderDirection=e.direction}},{key:"onTargetReorder",value:function(e){this.handleChange(e,this.props.source,e.value),this.reorderedListElement=this.targetListElement,this.reorderDirection=e.direction}},{key:"handleScrollPosition",value:function(e,n){if(e){var o=t.DomHandler.findSingle(e,".p-picklist-list");switch(n){case"up":this.scrollInView(o,-1);break;case"top":o.scrollTop=0;break;case"down":this.scrollInView(o,1);break;case"bottom":o.scrollTop=o.scrollHeight}}}},{key:"handleChange",value:function(e,t,n){this.props.onChange&&this.props.onChange({originalEvent:e.originalEvent,source:t,target:n})}},{key:"onTransfer",value:function(e){var t=e.originalEvent,n=e.source,o=e.target;switch(e.direction){case"toTarget":this.props.onMoveToTarget&&this.props.onMoveToTarget({originalEvent:t,value:this.getSourceSelection()});break;case"allToTarget":this.props.onMoveAllToTarget&&this.props.onMoveAllToTarget({originalEvent:t,value:this.props.source});break;case"toSource":this.props.onMoveToSource&&this.props.onMoveToSource({originalEvent:t,value:this.getTargetSelection()});break;case"allToSource":this.props.onMoveAllToSource&&this.props.onMoveAllToSource({originalEvent:t,value:this.props.target})}this.onSelectionChange({originalEvent:t,value:[]},"sourceSelection",this.props.onSourceSelectionChange),this.onSelectionChange({originalEvent:t,value:[]},"targetSelection",this.props.onTargetSelectionChange),this.handleChange(e,n,o)}},{key:"scrollInView",value:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,o=e.getElementsByClassName("p-highlight");t.DomHandler.scrollInView(e,-1===n?o[0]:o[o.length-1])}},{key:"onSelectionChange",value:function(e,t,n){n?n(e):this.setState(d({},t,e.value)),this.state.sourceSelection&&this.state.sourceSelection.length&&"targetSelection"===t?this.setState({sourceSelection:[]}):this.state.targetSelection&&this.state.targetSelection.length&&"sourceSelection"===t&&this.setState({targetSelection:[]})}},{key:"componentDidUpdate",value:function(){this.reorderedListElement&&(this.handleScrollPosition(this.reorderedListElement,this.reorderDirection),this.reorderedListElement=null,this.reorderDirection=null)}},{key:"render",value:function(){var e=this,n=t.classNames("p-picklist p-component",this.props.className),o=this.getSourceSelection(),i=this.getTargetSelection();return r.default.createElement("div",{id:this.props.id,className:n,style:this.props.style},this.props.showSourceControls&&r.default.createElement(K,{list:this.props.source,selection:o,onReorder:this.onSourceReorder,className:"p-picklist-source-controls",dataKey:this.props.dataKey}),r.default.createElement(w,{ref:function(t){return e.sourceListElement=t},list:this.props.source,selection:o,onSelectionChange:function(t){return e.onSelectionChange(t,"sourceSelection",e.props.onSourceSelectionChange)},itemTemplate:this.props.itemTemplate,header:this.props.sourceHeader,style:this.props.sourceStyle,className:"p-picklist-source-wrapper",listClassName:"p-picklist-source",metaKeySelection:this.props.metaKeySelection,tabIndex:this.props.tabIndex,dataKey:this.props.dataKey}),r.default.createElement(x,{onTransfer:this.onTransfer,source:this.props.source,target:this.props.target,sourceSelection:o,targetSelection:i,dataKey:this.props.dataKey}),r.default.createElement(w,{ref:function(t){return e.targetListElement=t},list:this.props.target,selection:i,onSelectionChange:function(t){return e.onSelectionChange(t,"targetSelection",e.props.onTargetSelectionChange)},itemTemplate:this.props.itemTemplate,header:this.props.targetHeader,style:this.props.targetStyle,className:"p-picklist-target-wrapper",listClassName:"p-picklist-target",metaKeySelection:this.props.metaKeySelection,tabIndex:this.props.tabIndex,dataKey:this.props.dataKey}),this.props.showTargetControls&&r.default.createElement(K,{list:this.props.target,selection:i,onReorder:this.onTargetReorder,className:"p-picklist-target-controls",dataKey:this.props.dataKey}))}}]),u}();d(D,"defaultProps",{id:null,source:null,target:null,sourceHeader:null,targetHeader:null,style:null,className:null,sourceStyle:null,targetStyle:null,sourceSelection:null,targetSelection:null,showSourceControls:!0,showTargetControls:!0,metaKeySelection:!0,tabIndex:0,dataKey:null,itemTemplate:null,onChange:null,onMoveToSource:null,onMoveAllToSource:null,onMoveToTarget:null,onMoveAllToTarget:null,onSourceSelectionChange:null,onTargetSelectionChange:null}),exports.PickList=D;
assets/js/dependencies/jquery.js
Theadd/on-black-sails
/*! * jQuery JavaScript Library v1.11.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-05-01T17:42Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var deletedIds = []; var slice = deletedIds.slice; var concat = deletedIds.concat; var push = deletedIds.push; var indexOf = deletedIds.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var version = "1.11.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1, IE<9 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: deletedIds.sort, splice: deletedIds.splice }; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( support.ownLast ) { for ( key in obj ) { return hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, type: function( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1, IE<9 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( indexOf ) { return indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; while ( j < len ) { first[ i++ ] = second[ j++ ]; } // Support: IE<9 // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) if ( len !== len ) { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: function() { return +( new Date() ); }, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.19 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-04-18 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select msallowclip=''><option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowclip^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); jQuery.fn.extend({ has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !(--remaining) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * Clean-up method for dom ready events */ function detach() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } } /** * The ready event handler and self cleanup method */ function completed() { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; var strundefined = typeof undefined; // Support: IE<9 // Iteration over object's inherited properties before its own var i; for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Note: most support tests are defined in their respective modules. // false until the test is run support.inlineBlockNeedsLayout = false; // Execute ASAP in case we need to set body.style.zoom jQuery(function() { // Minified: var a,b,c,d var val, div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Return for frameset docs that don't have a body return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); if ( typeof div.style.zoom !== strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; if ( val ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); }); (function() { var div = document.createElement( "div" ); // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. div = null; })(); /** * Determines whether an object can have data */ jQuery.acceptData = function( elem ) { var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], nodeType = +elem.nodeType || 1; // Do not set data on non-element DOM nodes because it will not be cleared (#8335). return nodeType !== 1 && nodeType !== 9 ? false : // Nodes accept data unless otherwise specified; rejection can be conditional !noData || noData !== true && elem.getAttribute("classid") === noData; }; var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function internalData( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements (space-suffixed to avoid Object.prototype collisions) // throw uncatchable exceptions if you attempt to set expando properties noData: { "applet ": true, "embed ": true, // ...but Flash objects (which have this classid) *can* handle expandos "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[0], attrs = elem && elem.attributes; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { // Minified: var a,b,c var input = document.createElement( "input" ), div = document.createElement( "div" ), fragment = document.createDocumentFragment(); // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName( "tbody" ).length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) input.type = "checkbox"; input.checked = true; fragment.appendChild( input ); support.appendChecked = input.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE6-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // #11217 - WebKit loses check when the name is after the checked attribute fragment.appendChild( div ); div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() support.noCloneEvent = true; if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } })(); (function() { var i, eventName, div = document.createElement( "div" ); // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; if ( !(support[ i + "Bubbles" ] = eventName in window) ) { // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" ); support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; } } // Null elements to avoid leaks in IE. div = null; })(); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: IE < 9, Android < 4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); jQuery._removeData( doc, fix ); } else { jQuery._data( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } (function() { var shrinkWrapBlocksVal; support.shrinkWrapBlocks = function() { if ( shrinkWrapBlocksVal != null ) { return shrinkWrapBlocksVal; } // Will be changed later if needed. shrinkWrapBlocksVal = false; // Minified: var b,c,d var div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); // Support: IE6 // Check if elements with layout shrink-wrap their children if ( typeof div.style.zoom !== strundefined ) { // Reset CSS: box-sizing; display; margin; border div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-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"; div.appendChild( document.createElement( "div" ) ).style.width = "5px"; shrinkWrapBlocksVal = div.offsetWidth !== 3; } body.removeChild( container ); return shrinkWrapBlocksVal; }; })(); var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles, curCSS, rposition = /^(top|right|bottom|left)$/; if ( window.getComputedStyle ) { getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; curCSS = function( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + ""; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, computed ) { var left, rs, rsLeft, ret, style = elem.style; computed = computed || getStyles( elem ); ret = computed ? computed[ name ] : undefined; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + "" || "auto"; }; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { var condition = conditionFn(); if ( condition == null ) { // The test was not ready at this point; screw the hook this time // but check again when needed next time. return; } if ( condition ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { // Minified: var b,c,d,e,f,g, h,i var div, style, a, pixelPositionVal, boxSizingReliableVal, reliableHiddenOffsetsVal, reliableMarginRightVal; // Setup div = document.createElement( "div" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; style = a && a.style; // Finish early in limited (non-browser) environments if ( !style ) { return; } style.cssText = "float:left;opacity:.5"; // Support: IE<9 // Make sure that element opacity exists (as opposed to filter) support.opacity = style.opacity === "0.5"; // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" || style.WebkitBoxSizing === ""; jQuery.extend(support, { reliableHiddenOffsets: function() { if ( reliableHiddenOffsetsVal == null ) { computeStyleTests(); } return reliableHiddenOffsetsVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelPosition: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelPositionVal; }, // Support: Android 2.3 reliableMarginRight: function() { if ( reliableMarginRightVal == null ) { computeStyleTests(); } return reliableMarginRightVal; } }); function computeStyleTests() { // Minified: var b,c,d,j var div, body, container, contents; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-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"; // Support: IE<9 // Assume reasonable values in the absence of getComputedStyle pixelPositionVal = boxSizingReliableVal = false; reliableMarginRightVal = true; // Check for getComputedStyle so that this code is not run in IE<9. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right contents = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding contents.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; contents.style.marginRight = contents.style.width = "0"; div.style.width = "1px"; reliableMarginRightVal = !parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight ); } // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; contents = div.getElementsByTagName( "td" ); contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; if ( reliableHiddenOffsetsVal ) { contents[ 0 ].style.display = ""; contents[ 1 ].style.display = "none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; } body.removeChild( container ); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Support: IE // Swallow errors from 'invalid' CSS values (#5509) try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !support.shrinkWrapBlocks() ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { // Minified: var a,b,c,d,e var input, div, select, a, opt; // Setup div = document.createElement( "div" ); div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName("a")[ 0 ]; // First batch of tests. select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE8 only // Check if we can trust getAttribute("value") input = document.createElement( "input" ); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; })(); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) { // Support: IE6 // When new option element is added to select box we need to // force reflow of newly added node in order to workaround delay // of initialization properties try { option.selected = optionSet = true; } catch ( _ ) { // Will be executed only in IE6 option.scrollHeight; } } else { option.selected = false; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return options; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = support.getSetAttribute, getSetInput = support.input; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hook for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // Retrieve booleans specially jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; } : function( elem, name, isXML ) { if ( !isXML ) { return elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; } }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) if ( name === "value" || value === elem.getAttribute( name ) ) { return value; } } }; // Some attributes are constructed with empty-string values when not defined attrHandle.id = attrHandle.name = attrHandle.coords = function( elem, name, isXML ) { var ret; if ( !isXML ) { return (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; } }; // Fixing value retrieval on a button requires this module jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); if ( ret && ret.specified ) { return ret.value; } }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } if ( !support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } var rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } // Support: Safari, IE9+ // mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !support.enctype ) { jQuery.propFix.enctype = "encoding"; } var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g; jQuery.parseJSON = function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { // Support: Android 2.3 // Workaround failure to string-cast null input return window.JSON.parse( data + "" ); } var requireNonComma, depth = null, str = jQuery.trim( data + "" ); // Guard against invalid (and possibly dangerous) input by ensuring that nothing remains // after removing valid tokens return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) { // Force termination if we see a misplaced comma if ( requireNonComma && comma ) { depth = 0; } // Perform no more replacements after returning to outermost depth if ( depth === 0 ) { return token; } // Commas must not follow "[", "{", or "," requireNonComma = open || comma; // Determine new depth // array/object open ("[" or "{"): depth += true - false (increment) // array/object close ("]" or "}"): depth += false - true (decrement) // other cases ("," or primitive): depth += true - true (numeric cast) depth += !close - !open; // Remove this token return ""; }) ) ? ( Function( "return " + str ) )() : jQuery.error( "Invalid JSON: " + data ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType.charAt( 0 ) === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!support.reliableHiddenOffsets() && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ? // Support: IE6+ function() { // XHR cannot access local files, always use ActiveX for that case return !this.isLocal && // Support: IE7-8 // oldIE XHR does not support non-RFC2616 methods (#13240) // See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx // and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9 // Although this check for six methods instead of eight // since IE also does not support "trace" and "connect" /^(get|post|head|put|delete|options)$/i.test( this.type ) && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; var xhrId = 0, xhrCallbacks = {}, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE<10 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }); } // Determine support properties support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( options ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !options.crossDomain || support.cors ) { var callback; return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; // Open the socket xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { // Support: IE<9 // IE's ActiveXObject throws a 'Type Mismatch' exception when setting // request header to a null-value. // // To keep consistent with other XHR implementations, cast the value // to string and ignore `undefined`. if ( headers[ i ] !== undefined ) { xhr.setRequestHeader( i, headers[ i ] + "" ); } } // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( options.hasContent && options.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responses; // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Clean up delete xhrCallbacks[ id ]; callback = undefined; xhr.onreadystatechange = jQuery.noop; // Abort manually if needed if ( isAbort ) { if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; // Support: IE<10 // Accessing binary-data responseText throws an exception // (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && options.isLocal && !options.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, xhr.getAllResponseHeaders() ); } }; if ( !options.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { // Add to the list of active xhr callbacks xhr.onreadystatechange = xhrCallbacks[ id ] = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off, url.length ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
html/assets/lib/elFinder/jquery/jquery-1.7.2.min.js
lapakku2016/ciproject
/*! jQuery v1.7.2 jquery.com | jquery.org/license */ (function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function ca(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function b_(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bD.test(a)?d(a,e):b_(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&f.type(b)==="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bZ(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bS,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bZ(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bZ(a,c,d,e,"*",g));return l}function bY(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bO),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bB(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?1:0,g=4;if(d>0){if(c!=="border")for(;e<g;e+=2)c||(d-=parseFloat(f.css(a,"padding"+bx[e]))||0),c==="margin"?d+=parseFloat(f.css(a,c+bx[e]))||0:d-=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0;return d+"px"}d=by(a,b);if(d<0||d==null)d=a.style[b];if(bt.test(d))return d;d=parseFloat(d)||0;if(c)for(;e<g;e+=2)d+=parseFloat(f.css(a,"padding"+bx[e]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+bx[e]))||0);return d+"px"}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;b.nodeType===1&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?b.outerHTML=a.outerHTML:c!=="input"||a.type!=="checkbox"&&a.type!=="radio"?c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text):(a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value)),b.removeAttribute(f.expando),b.removeAttribute("_submit_attached"),b.removeAttribute("_change_attached"))}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c,i[c][d])}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h,i){var j,k=d==null,l=0,m=a.length;if(d&&typeof d=="object"){for(l in d)e.access(a,c,l,d[l],1,h,f);g=1}else if(f!==b){j=i===b&&e.isFunction(f),k&&(j?(j=c,c=function(a,b,c){return j.call(e(a),c)}):(c.call(a,f),c=null));if(c)for(;l<m;l++)c(a[l],d,j?f.call(a[l],l,c(a[l],d)):f,i);g=1}return g?a:k?c.call(a):m?c(a[0],d):h},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m,n=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?n(g):h==="function"&&(!a.unique||!p.has(g))&&c.push(g)},o=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,j=!0,m=k||0,k=0,l=c.length;for(;c&&m<l;m++)if(c[m].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}j=!1,c&&(a.once?e===!0?p.disable():c=[]:d&&d.length&&(e=d.shift(),p.fireWith(e[0],e[1])))},p={add:function(){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){j&&f<=l&&(l--,f<=m&&m--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&p.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(j?a.once||d.push([b,c]):(!a.once||!e)&&o(b,c));return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!i}};return p};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p=c.createElement("div"),q=c.documentElement;p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="<div "+n+"display:block;'><div style='"+t+"0;display:block;overflow:hidden;'></div></div>"+"<table "+n+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="<table><tr><td style='"+t+"0;display:none'></td><td>t</td></tr></table>",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="<div style='width:5px;'></div>",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h,i,j=this[0],k=0,m=null;if(a===b){if(this.length){m=f.data(j);if(j.nodeType===1&&!f._data(j,"parsedAttrs")){g=j.attributes;for(i=g.length;k<i;k++)h=g[k].name,h.indexOf("data-")===0&&(h=f.camelCase(h.substring(5)),l(j,h,m[h]));f._data(j,"parsedAttrs",!0)}}return m}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!";return f.access(this,function(c){if(c===b){m=this.triggerHandler("getData"+e,[d[0]]),m===b&&j&&(m=f.data(j,a),m=l(j,a,m));return m===b&&d[1]?this.data(d[0]):m}d[1]=c,this.each(function(){var b=f(this);b.triggerHandler("setData"+e,d),f.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length<d)return f.queue(this[0],a);return c===b?this:this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise(c)}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,f.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i<g;i++)e=d[i],e&&(c=f.propFix[e]||e,h=u.test(e),h||f.attr(a,e,""),a.removeAttribute(v?e:c),h&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0,coords:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:g&&G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=f.event.special[c.type]||{},j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(!i.preDispatch||i.preDispatch.call(this,c)!==!1){if(e&&(!c.button||c.type!=="click")){n=f(this),n.context=this.ownerDocument||this;for(m=c.target;m!=this;m=m.parentNode||this)if(m.disabled!==!0){p={},r=[],n[0]=m;for(k=0;k<e;k++)s=d[k],t=s.selector,p[t]===b&&(p[t]=s.quick?H(m,s.quick):n.is(t)),p[t]&&r.push(s);r.length&&j.push({elem:m,matches:r})}}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){q=j[k],c.currentTarget=q.elem;for(l=0;l<q.matches.length&&!c.isImmediatePropagationStopped();l++){s=q.matches[l];if(h||!c.namespace&&!s.namespace||c.namespace_re&&c.namespace_re.test(s.namespace))c.data=s.data,c.handleObj=s,o=((f.event.special[s.origType]||{}).handle||s.handler).apply(q.elem,g),o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()))}}i.postDispatch&&i.postDispatch.call(this,c);return c.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),d._submit_attached=!0)})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.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){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9||d===11){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.globalPOS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")[\\s/>]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={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,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f .clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(f.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(g){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,function(a,b){b.src?f.ajax({type:"GET",global:!1,url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1></$2>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]==="<table>"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i<u;i++)bn(l[i]);else bn(l);l.nodeType?j.push(l):j=f.merge(j,l)}if(d){g=function(a){return!a.type||be.test(a.type)};for(k=0;j[k];k++){h=j[k];if(e&&f.nodeName(h,"script")&&(!h.type||be.test(h.type)))e.push(h.parentNode?h.parentNode.removeChild(h):h);else{if(h.nodeType===1){var v=f.grep(h.getElementsByTagName("script"),g);j.splice.apply(j,[k+1,0].concat(v))}d.appendChild(h)}}}return j},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bp=/alpha\([^)]*\)/i,bq=/opacity=([^)]*)/,br=/([A-Z]|^ms)/g,bs=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,bu=/^([\-+])=([\-+.\de]+)/,bv=/^margin/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Top","Right","Bottom","Left"],by,bz,bA;f.fn.css=function(a,c){return f.access(this,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)},a,c,arguments.length>1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),(e===""&&f.css(d,"display")==="none"||!f.contains(d.ownerDocument.documentElement,d))&&f._data(d,"olddisplay",cu(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ct("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(ct("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o,p,q;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]);if((k=f.cssHooks[g])&&"expand"in k){l=k.expand(a[g]),delete a[g];for(i in l)i in a||(a[i]=l[i])}}for(g in a){h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cu(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cm.test(h)?(q=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),q?(f._data(this,"toggle"+i,q==="show"?"hide":"show"),j[q]()):j[h]()):(m=cn.exec(h),n=j.cur(),m?(o=parseFloat(m[2]),p=m[3]||(f.cssNumber[i]?"":"px"),p!=="px"&&(f.style(this,i,(o||1)+p),n=(o||1)/j.cur()*n,f.style(this,i,n+p)),m[1]&&(o=(m[1]==="-="?-1:1)*o+n),j.custom(n,o,p)):j.custom(n,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:ct("show",1),slideUp:ct("hide",1),slideToggle:ct("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a){return a},swing:function(a){return-Math.cos(a*Math.PI)/2+.5}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.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,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cq||cr(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){f._data(e.elem,"fxshow"+e.prop)===b&&(e.options.hide?f._data(e.elem,"fxshow"+e.prop,e.start):e.options.show&&f._data(e.elem,"fxshow"+e.prop,e.end))},h()&&f.timers.push(h)&&!co&&(co=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cq||cr(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(co),co=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(cp.concat.apply([],cp),function(a,b){b.indexOf("margin")&&(f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)})}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cv,cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?cv=function(a,b,c,d){try{d=a.getBoundingClientRect()}catch(e){}if(!d||!f.contains(c,a))return d?{top:d.top,left:d.left}:{top:0,left:0};var g=b.body,h=cy(b),i=c.clientTop||g.clientTop||0,j=c.clientLeft||g.clientLeft||0,k=h.pageYOffset||f.support.boxModel&&c.scrollTop||g.scrollTop,l=h.pageXOffset||f.support.boxModel&&c.scrollLeft||g.scrollLeft,m=d.top+k-i,n=d.left+l-j;return{top:m,left:n}}:cv=function(a,b,c){var d,e=a.offsetParent,g=a,h=b.body,i=b.defaultView,j=i?i.getComputedStyle(a,null):a.currentStyle,k=a.offsetTop,l=a.offsetLeft;while((a=a.parentNode)&&a!==h&&a!==c){if(f.support.fixedPosition&&j.position==="fixed")break;d=i?i.getComputedStyle(a,null):a.currentStyle,k-=a.scrollTop,l-=a.scrollLeft,a===e&&(k+=a.offsetTop,l+=a.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(a.nodeName))&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),g=e,e=a.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),j=d}if(j.position==="relative"||j.position==="static")k+=h.offsetTop,l+=h.offsetLeft;f.support.fixedPosition&&j.position==="fixed"&&(k+=Math.max(c.scrollTop,h.scrollTop),l+=Math.max(c.scrollLeft,h.scrollLeft));return{top:k,left:l}},f.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){f.offset.setOffset(this,a,b)});var c=this[0],d=c&&c.ownerDocument;if(!d)return null;if(c===d.body)return f.offset.bodyOffset(c);return cv(c,d,d.documentElement)},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
app/javascript/mastodon/features/home_timeline/index.js
5thfloor/ichiji-social
import React from 'react'; import { connect } from 'react-redux'; import { expandHomeTimeline } from '../../actions/timelines'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ColumnSettingsContainer from './containers/column_settings_container'; import { Link } from 'react-router-dom'; const messages = defineMessages({ title: { id: 'column.home', defaultMessage: 'Home' }, }); const mapStateToProps = state => ({ hasUnread: state.getIn(['timelines', 'home', 'unread']) > 0, isPartial: state.getIn(['timelines', 'home', 'isPartial']), }); export default @connect(mapStateToProps) @injectIntl class HomeTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, intl: PropTypes.object.isRequired, hasUnread: PropTypes.bool, isPartial: PropTypes.bool, columnId: PropTypes.string, multiColumn: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('HOME', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } handleLoadMore = maxId => { this.props.dispatch(expandHomeTimeline({ maxId })); } componentDidMount () { this._checkIfReloadNeeded(false, this.props.isPartial); } componentDidUpdate (prevProps) { this._checkIfReloadNeeded(prevProps.isPartial, this.props.isPartial); } componentWillUnmount () { this._stopPolling(); } _checkIfReloadNeeded (wasPartial, isPartial) { const { dispatch } = this.props; if (wasPartial === isPartial) { return; } else if (!wasPartial && isPartial) { this.polling = setInterval(() => { dispatch(expandHomeTimeline()); }, 3000); } else if (wasPartial && !isPartial) { this._stopPolling(); } } _stopPolling () { if (this.polling) { clearInterval(this.polling); this.polling = null; } } render () { const { intl, shouldUpdateScroll, hasUnread, columnId, multiColumn } = this.props; const pinned = !!columnId; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='home' active={hasUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <ColumnSettingsContainer /> </ColumnHeader> <StatusListContainer trackScroll={!pinned} scrollKey={`home_timeline-${columnId}`} onLoadMore={this.handleLoadMore} timelineId='home' emptyMessage={<FormattedMessage id='empty_column.home' defaultMessage='Your home timeline is empty! Visit {public} or use search to get started and meet other users.' values={{ public: <Link to='/timelines/public'><FormattedMessage id='empty_column.home.public_timeline' defaultMessage='the public timeline' /></Link> }} />} shouldUpdateScroll={shouldUpdateScroll} bindToDocument={!multiColumn} /> </Column> ); } }
public/js/components/notifications/Notification.react.js
TRomesh/Coupley
import React from 'react'; import ListItem from 'material-ui/lib/lists/list-item'; import Divider from 'material-ui/lib/divider'; import Avatar from 'material-ui/lib/avatar'; import Colors from 'material-ui/lib/styles/colors'; import IconButton from 'material-ui/lib/icon-button'; import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert'; import IconMenu from 'material-ui/lib/menus/icon-menu'; import MenuItem from 'material-ui/lib/menus/menu-item'; import TextField from 'material-ui/lib/text-field'; import FlatButton from 'material-ui/lib/flat-button'; import injectTapEventPlugin from 'react-tap-event-plugin'; const iconButtonElement = ( <IconButton touch={true} tooltip="more" tooltipPosition="bottom-left"> <MoreVertIcon color={Colors.deepPurple500} /> </IconButton> ); const textStyle = { marginLeft: "15" } const Notification = React.createClass({ render: function() { return ( <div> <ListItem leftAvatar={<Avatar src="img/profilepics/tiffany" />} primaryText="rajika" secondaryText={ <p> <span style={{color: Colors.darkBlack}}>{this.props.id + ' ' + this.props.profilepic}</span> </p> } /> <Divider inset={true} /> </div> ); } }); export default Notification;
src/Parser/DestructionWarlock/Modules/Features/DimensionalRift.js
mwwscott0/WoWAnalyzer
import React from 'react'; import Module from 'Parser/Core/Module'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatNumber, formatPercentage } from 'common/format'; import { STATISTIC_ORDER } from 'Main/StatisticBox'; import StatisticsListBox from 'Main/StatisticsListBox'; const FLAME_RIFT = 'Flame Rift'; const CHAOS_TEAR = 'Chaos Tear'; const SHADOWY_TEAR = 'Shadowy Tear'; const UNSTABLE_TEAR = 'Unstable Tear'; class DimensionalRift extends Module { _riftDetails = { [FLAME_RIFT]: { ...SPELLS.SEARING_BOLT_RIFT, }, [CHAOS_TEAR]: { ...SPELLS.CHAOS_BOLT_RIFT, }, [SHADOWY_TEAR]: { ...SPELLS.SHADOW_BOLT_RIFT, }, [UNSTABLE_TEAR]: { ...SPELLS.CHAOS_BARRAGE_RIFT, }, }; _rifts = {}; on_initialized() { this.owner.playerPets.filter(pet => this._riftDetails[pet.name]).forEach((pet) => { this._rifts[pet.id] = { ...this._riftDetails[pet.name], damage: 0, }; }); } on_damage(event) { if (!this._rifts[event.sourceID]) { return; } this._rifts[event.sourceID].damage += (event.amount || 0) + (event.absorbed || 0); } statistic() { const rifts = Object.keys(this._rifts).map(id => this._rifts[id]); const totalDmg = rifts.reduce((sum, rift) => sum + rift.damage, 0); return ( <StatisticsListBox title={<span><SpellIcon id={SPELLS.DIMENSIONAL_RIFT_CAST.id} /> Dimensional Rift</span>} tooltip={`Your Dimensional Rifts did ${formatNumber(totalDmg)} total damage (${this.owner.formatItemDamageDone(totalDmg)}).`} > {rifts.map(rift => ( <div className="flex"> <div className="flex-main"> <SpellLink id={rift.id}> <SpellIcon id={rift.id} noLink /> {rift.name} </SpellLink> </div> <div className="flex-sub text-right"> {formatNumber(rift.damage)} ({formatPercentage(rift.damage / totalDmg)} %) </div> </div> ))} </StatisticsListBox> ); } statisticOrder = STATISTIC_ORDER.OPTIONAL(6); } export default DimensionalRift;
node_modules/react-bootstrap/es/MenuItem.js
cmccandless/SolRFrontEnd
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import all from 'react-prop-types/lib/all'; import SafeAnchor from './SafeAnchor'; import { bsClass, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { /** * Highlight the menu item as active. */ active: React.PropTypes.bool, /** * Disable the menu item, making it unselectable. */ disabled: React.PropTypes.bool, /** * Styles the menu item as a horizontal rule, providing visual separation between * groups of menu items. */ divider: all(React.PropTypes.bool, function (_ref) { var divider = _ref.divider, children = _ref.children; return divider && children ? new Error('Children will not be rendered for dividers') : null; }), /** * Value passed to the `onSelect` handler, useful for identifying the selected menu item. */ eventKey: React.PropTypes.any, /** * Styles the menu item as a header label, useful for describing a group of menu items. */ header: React.PropTypes.bool, /** * HTML `href` attribute corresponding to `a.href`. */ href: React.PropTypes.string, /** * Callback fired when the menu item is clicked. */ onClick: React.PropTypes.func, /** * Callback fired when the menu item is selected. * * ```js * (eventKey: any, event: Object) => any * ``` */ onSelect: React.PropTypes.func }; var defaultProps = { divider: false, disabled: false, header: false }; var MenuItem = function (_React$Component) { _inherits(MenuItem, _React$Component); function MenuItem(props, context) { _classCallCheck(this, MenuItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } MenuItem.prototype.handleClick = function handleClick(event) { var _props = this.props, href = _props.href, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (!href || disabled) { event.preventDefault(); } if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; MenuItem.prototype.render = function render() { var _props2 = this.props, active = _props2.active, disabled = _props2.disabled, divider = _props2.divider, header = _props2.header, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = _objectWithoutProperties(_props2, ['active', 'disabled', 'divider', 'header', 'onClick', 'className', 'style']); var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['eventKey', 'onSelect']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; if (divider) { // Forcibly blank out the children; separators shouldn't render any. elementProps.children = undefined; return React.createElement('li', _extends({}, elementProps, { role: 'separator', className: classNames(className, 'divider'), style: style })); } if (header) { return React.createElement('li', _extends({}, elementProps, { role: 'heading', className: classNames(className, prefix(bsProps, 'header')), style: style })); } return React.createElement( 'li', { role: 'presentation', className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(SafeAnchor, _extends({}, elementProps, { role: 'menuitem', tabIndex: '-1', onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return MenuItem; }(React.Component); MenuItem.propTypes = propTypes; MenuItem.defaultProps = defaultProps; export default bsClass('dropdown', MenuItem);
ui/src/components/Charts/BarChart.js
LearningLocker/learninglocker
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { List } from 'immutable'; import { AutoSizer } from 'react-virtualized'; import { BarChart as Chart, XAxis, YAxis, CartesianGrid } from 'recharts'; import { compose } from 'recompose'; import NoData from 'ui/components/Graphs/NoData'; import { wrapLabel } from 'ui/utils/defaultTitles'; import { Button } from 'react-toolbox/lib/button'; import uuid from 'uuid'; import { connect } from 'react-redux'; import { getMetadataSelector, setInMetadata } from 'ui/redux/modules/metadata'; import { Buttons, Chart as StyledChart, ChartWrapper, BarContainer, XAxisLabel, XAxis as StyledXAxis, YAxis as StyledYAxis, } from 'ui/components/Charts/styled'; import { getResultsData, getShortModel, getChartData, hasData, renderTooltips, renderBars, renderLegend, hiddenSeriesState } from './Chart'; const enhance = compose( hiddenSeriesState, connect((state, { model }) => ({ activePage: getMetadataSelector({ schema: 'visualisation', id: model.get('_id') })(state).get('activePage', 0) }), { setInMetadata }) ); class BarChart extends Component { static propTypes = { results: PropTypes.instanceOf(List), labels: PropTypes.instanceOf(List), colors: PropTypes.instanceOf(List), stacked: PropTypes.bool, chartWrapperFn: PropTypes.instanceOf(Function), } static defaultProps = { chartWrapperFn: component => (<AutoSizer>{component}</AutoSizer>) } displayPrevPage = () => this.props.setInMetadata({ schema: 'visualisation', id: this.props.model.get('_id'), path: ['activePage'], value: this.props.activePage - 1 }); displayNextPage = () => this.props.setInMetadata({ schema: 'visualisation', id: this.props.model.get('_id'), path: ['activePage'], value: this.props.activePage + 1 }); getDataChunk = model => data => page => data.slice(model.get('barChartGroupingLimit') * page, model.get('barChartGroupingLimit') * (page + 1)) getPages = (model, data) => Math.ceil(data.size / (model.get('barChartGroupingLimit') + 1)); hasPrevPage = pages => page => pages > 0 && page > 0 hasNextPage = pages => page => pages > 0 && page < pages - 1 sortData = data => data.sortBy(e => -e.get('total')) getSortedData = results => labels => ( this.sortData(getResultsData(results)(labels)) ) renderPrevButton = () => ( <span style={{ alignSelf: 'flex-start', marginLeft: 10 }}> <Button raised label="Previous" onMouseUp={this.displayPrevPage} icon={<i className="icon ion-chevron-left" />} /> </span> ) renderNextButton = () => ( <span style={{ marginRight: 10, marginLeft: 'auto' }}> <Button raised label="Next" onMouseUp={this.displayNextPage} icon={<i className="icon ion-chevron-right" />} /> </span> ) renderBarChart = model => colors => labels => data => stacked => page => ({ width, height }) => { const chartUuid = uuid.v4(); /* eslint-disable react/no-danger */ return ( <div> <style dangerouslySetInnerHTML={{ __html: ` .grid-${chartUuid} .recharts-cartesian-grid-horizontal { background-color: 'yellow'; visibility: hidden !important; } ` }} /> <Chart className={`grid-${chartUuid}`} data={getChartData(this.getDataChunk(model)(data)(page), this.props.hiddenSeries)} width={width} height={height} layout="vertical"> <CartesianGrid strokeDasharray="1 1" /> <YAxis dataKey="cellId" tickFormatter={getShortModel(data)} type="category" width={90} /> <XAxis type="number" /> {renderLegend(labels, this.props.toggleHiddenSeries)} {renderBars(colors)(labels)(stacked)} {renderTooltips(data, this.props.hiddenSeries)} </Chart> </div> ); /* eslint-enable react/no-danger */ }; renderResults = model => results => colors => labels => (stacked) => { const { activePage } = this.props; const data = this.getSortedData(results)(labels); const pages = this.getPages(model, data); return ( <StyledChart> <Buttons> {this.hasPrevPage(pages)(activePage) && this.renderPrevButton()} {this.hasNextPage(pages)(activePage) && this.renderNextButton()} </Buttons> <div className={'clearfix'} /> <BarContainer> <StyledYAxis> {wrapLabel(this.props.model.get('axesyLabel') || this.props.model.getIn(['axesgroup', 'searchString'], 'Y-Axis'))} </StyledYAxis> <ChartWrapper> {this.props.chartWrapperFn((this.renderBarChart(model)(colors)(labels)(data)(stacked)(activePage)))} </ChartWrapper> </BarContainer> <XAxisLabel> <StyledXAxis> {this.props.model.get('axesxLabel') || this.props.model.getIn(['axesvalue', 'searchString'], 'X-Axis')} </StyledXAxis> </XAxisLabel> </StyledChart> ); } render = () => { const { results, labels, stacked, colors, model } = this.props; return ( hasData(this.props.results) ? this.renderResults(model)(results)(colors)(labels)(stacked) : <NoData /> ); } } export default enhance(BarChart);
storybookStories/Modal.story.js
xclix/chan
import React from 'react'; import { storiesOf } from '@kadira/storybook'; import R from 'ramda'; import { createModal } from '../src/lib/gui/components/Modal'; storiesOf('Modal', module) .add('test modal', () => { const TestModal = () => <div> <div className="modal-header">Modal header</div> <div className="modal-content"> Test modal </div> </div>; const Modal = createModal({ TestModal }); return ( <Modal component="TestModal" onOverlayClick={R.identity} /> ); }) .add('test modal', () => { const TestModal = () => <div> <div className="modal-header">Modal header</div> <div className="modal-content"> Test modal </div> </div>; const Modal = createModal({ TestModal }); return ( <Modal component="TestModal" onOverlayClick={R.identity} /> ); }) .add('test modal', () => { const TestModal = () => <div> <div className="modal-header">Modal header</div> <div className="modal-content"> Test modal </div> </div>; const Modal = createModal({ TestModal }); return ( <Modal component="TestModal" onOverlayClick={R.identity} /> ); });
node_modules/react-tools/src/core/__tests__/refs-destruction-test.js
zlyi/react-components
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; var React = require('React'); var ReactTestUtils = require('ReactTestUtils'); var reactComponentExpect = require('reactComponentExpect'); var TestComponent = React.createClass({ render: function() { return ( <div> {this.props.destroy ? null : <div ref="theInnerDiv"> Lets try to destroy this. </div> } </div> ); } }); describe('refs-destruction', function() { beforeEach(function() { require('mock-modules').dumpCache(); }); it("should remove refs when destroying the parent", function() { var container = document.createElement('div'); var testInstance = React.render(<TestComponent />, container); reactComponentExpect(testInstance.refs.theInnerDiv) .toBeDOMComponentWithTag('div'); expect(Object.keys(testInstance.refs || {}).length).toEqual(1); React.unmountComponentAtNode(container); expect(Object.keys(testInstance.refs || {}).length).toEqual(0); }); it("should remove refs when destroying the child", function() { var container = document.createElement('div'); var testInstance = React.render(<TestComponent />, container); reactComponentExpect(testInstance.refs.theInnerDiv) .toBeDOMComponentWithTag('div'); expect(Object.keys(testInstance.refs || {}).length).toEqual(1); React.render(<TestComponent destroy={true} />, container); expect(Object.keys(testInstance.refs || {}).length).toEqual(0); }); });
docs/app/Examples/collections/Table/Variations/TableExampleBasic.js
clemensw/stardust
import React from 'react' import { Table } from 'semantic-ui-react' const TableExampleBasic = () => { return ( <Table basic> <Table.Header> <Table.Row> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Status</Table.HeaderCell> <Table.HeaderCell>Notes</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>John</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>Requires call</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jill</Table.Cell> <Table.Cell>Denied</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> </Table.Body> </Table> ) } export default TableExampleBasic
src/routes/not-found/NotFound.js
bmatthews/haze-lea
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './NotFound.css'; class NotFound extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1> {this.props.title} </h1> <p>Sorry, the page you were trying to view does not exist.</p> </div> </div> ); } } export default withStyles(s)(NotFound);
admin/client/components/ListSort.js
codevlabs/keystone
import { FormNote } from 'elemental'; import React from 'react'; import Popout from './Popout'; import PopoutList from './PopoutList'; import vkey from 'vkey'; import CurrentListStore from '../stores/CurrentListStore'; var ListSort = React.createClass({ displayName: 'ListSort', getInitialState () { return { altDown: false, popoutIsOpen: false }; }, componentDidMount () { document.body.addEventListener('keydown', this.handleKeyDown, false); document.body.addEventListener('keyup', this.handleKeyUp, false); }, componentWillUnmount () { document.body.removeEventListener('keydown', this.handleKeyDown); document.body.removeEventListener('keyup', this.handleKeyUp); }, handleKeyDown (e) { if (vkey[e.keyCode] !== '<alt>') return; this.setState({ altDown: true }); }, handleKeyUp (e) { if (vkey[e.keyCode] !== '<alt>') return; this.setState({ altDown: false }); }, openPopout () { this.setState({ popoutIsOpen: true }); }, closePopout () { this.setState({ popoutIsOpen: false }); }, handleSortSelect (path, inverted) { if (this.state.altDown) inverted = true; if (inverted) path = '-' + path; this.closePopout(); CurrentListStore.setActiveSort(path); }, renderSortOptions () { // TODO: Handle multiple sort paths let activeSortPath = CurrentListStore.getActiveSort().paths[0]; return CurrentListStore.getAvailableColumns().map((el, i) => { if (el.type === 'heading') { return <PopoutList.Heading key={'heading_' + i}>{el.content}</PopoutList.Heading>; } let path = el.field.path; let isSelected = activeSortPath && activeSortPath.path === path; let isInverted = isSelected && activeSortPath.invert; let icon = this.state.altDown || (isSelected && !isInverted) ? 'chevron-up' : 'chevron-down'; return ( <PopoutList.Item key={'column_' + el.field.path} icon={icon} isSelected={isSelected} label={el.field.label} onClick={() => { this.handleSortSelect(path, isSelected && !isInverted); }} /> ); }); }, render () { // TODO: Handle multiple sort paths let activeSortPath = CurrentListStore.getActiveSort().paths[0]; return ( <span> {activeSortPath && ( <span> <span className="ListHeader__sortedby"> sorted by </span> <a id="listHeaderSortButton" href="javascript:;" onClick={this.openPopout}> {activeSortPath.label.toLowerCase()} {activeSortPath.invert ? ' (descending)' : ''} <span className="disclosure-arrow" /> </a> </span> )} <Popout isOpen={this.state.popoutIsOpen} onCancel={this.closePopout} relativeToID="listHeaderSortButton"> <Popout.Header title="Sort" /> <Popout.Body scrollable> <PopoutList> {this.renderSortOptions()} </PopoutList> </Popout.Body> <Popout.Footer> <FormNote>Hold <kbd>alt</kbd> to toggle ascending/descending</FormNote> </Popout.Footer> </Popout> </span> ); } }); module.exports = ListSort;
submissions/winstonewert/src/root.js
winstonewert/flux-challenge
import React from 'react' import ObiWanPlanetMonitor from './obi-wan-planet-monitor' import DarkJediList from './dark-jedi-list' export default class Root extends React.Component { render() { return <div className="app-container"> <div className="css-root"> <ObiWanPlanetMonitor /> <DarkJediList /> </div> </div> } }
react/gameday2/components/embeds/EmbedTwitch.js
phil-lopreiato/the-blue-alliance
import React from 'react' import { webcastPropType } from '../../utils/webcastUtils' const EmbedTwitch = (props) => { const channel = props.webcast.channel const iframeSrc = `https://player.twitch.tv/?channel=${channel}` return ( <iframe src={iframeSrc} frameBorder="0" scrolling="no" height="100%" width="100%" allowFullScreen /> ) } EmbedTwitch.propTypes = { webcast: webcastPropType.isRequired, } export default EmbedTwitch
internals/templates/appContainer.js
sekkithub/wg
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) */ import React from 'react'; function App(props) { return ( <div> { props.children } </div> ); } export default App;
ajax/libs/yui/2.9.0/container/container_core-debug.js
idleberg/cdnjs
/* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ (function () { /** * Config is a utility used within an Object to allow the implementer to * maintain a list of local configuration properties and listen for changes * to those properties dynamically using CustomEvent. The initial values are * also maintained so that the configuration can be reset at any given point * to its initial state. * @namespace YAHOO.util * @class Config * @constructor * @param {Object} owner The owner Object to which this Config Object belongs */ YAHOO.util.Config = function (owner) { if (owner) { this.init(owner); } if (!owner) { YAHOO.log("No owner specified for Config object", "error", "Config"); } }; var Lang = YAHOO.lang, CustomEvent = YAHOO.util.CustomEvent, Config = YAHOO.util.Config; /** * Constant representing the CustomEvent type for the config changed event. * @property YAHOO.util.Config.CONFIG_CHANGED_EVENT * @private * @static * @final */ Config.CONFIG_CHANGED_EVENT = "configChanged"; /** * Constant representing the boolean type string * @property YAHOO.util.Config.BOOLEAN_TYPE * @private * @static * @final */ Config.BOOLEAN_TYPE = "boolean"; Config.prototype = { /** * Object reference to the owner of this Config Object * @property owner * @type Object */ owner: null, /** * Boolean flag that specifies whether a queue is currently * being executed * @property queueInProgress * @type Boolean */ queueInProgress: false, /** * Maintains the local collection of configuration property objects and * their specified values * @property config * @private * @type Object */ config: null, /** * Maintains the local collection of configuration property objects as * they were initially applied. * This object is used when resetting a property. * @property initialConfig * @private * @type Object */ initialConfig: null, /** * Maintains the local, normalized CustomEvent queue * @property eventQueue * @private * @type Object */ eventQueue: null, /** * Custom Event, notifying subscribers when Config properties are set * (setProperty is called without the silent flag * @event configChangedEvent */ configChangedEvent: null, /** * Initializes the configuration Object and all of its local members. * @method init * @param {Object} owner The owner Object to which this Config * Object belongs */ init: function (owner) { this.owner = owner; this.configChangedEvent = this.createEvent(Config.CONFIG_CHANGED_EVENT); this.configChangedEvent.signature = CustomEvent.LIST; this.queueInProgress = false; this.config = {}; this.initialConfig = {}; this.eventQueue = []; }, /** * Validates that the value passed in is a Boolean. * @method checkBoolean * @param {Object} val The value to validate * @return {Boolean} true, if the value is valid */ checkBoolean: function (val) { return (typeof val == Config.BOOLEAN_TYPE); }, /** * Validates that the value passed in is a number. * @method checkNumber * @param {Object} val The value to validate * @return {Boolean} true, if the value is valid */ checkNumber: function (val) { return (!isNaN(val)); }, /** * Fires a configuration property event using the specified value. * @method fireEvent * @private * @param {String} key The configuration property's name * @param {value} Object The value of the correct type for the property */ fireEvent: function ( key, value ) { YAHOO.log("Firing Config event: " + key + "=" + value, "info", "Config"); var property = this.config[key]; if (property && property.event) { property.event.fire(value); } }, /** * Adds a property to the Config Object's private config hash. * @method addProperty * @param {String} key The configuration property's name * @param {Object} propertyObject The Object containing all of this * property's arguments */ addProperty: function ( key, propertyObject ) { key = key.toLowerCase(); YAHOO.log("Added property: " + key, "info", "Config"); this.config[key] = propertyObject; propertyObject.event = this.createEvent(key, { scope: this.owner }); propertyObject.event.signature = CustomEvent.LIST; propertyObject.key = key; if (propertyObject.handler) { propertyObject.event.subscribe(propertyObject.handler, this.owner); } this.setProperty(key, propertyObject.value, true); if (! propertyObject.suppressEvent) { this.queueProperty(key, propertyObject.value); } }, /** * Returns a key-value configuration map of the values currently set in * the Config Object. * @method getConfig * @return {Object} The current config, represented in a key-value map */ getConfig: function () { var cfg = {}, currCfg = this.config, prop, property; for (prop in currCfg) { if (Lang.hasOwnProperty(currCfg, prop)) { property = currCfg[prop]; if (property && property.event) { cfg[prop] = property.value; } } } return cfg; }, /** * Returns the value of specified property. * @method getProperty * @param {String} key The name of the property * @return {Object} The value of the specified property */ getProperty: function (key) { var property = this.config[key.toLowerCase()]; if (property && property.event) { return property.value; } else { return undefined; } }, /** * Resets the specified property's value to its initial value. * @method resetProperty * @param {String} key The name of the property * @return {Boolean} True is the property was reset, false if not */ resetProperty: function (key) { key = key.toLowerCase(); var property = this.config[key]; if (property && property.event) { if (key in this.initialConfig) { this.setProperty(key, this.initialConfig[key]); return true; } } else { return false; } }, /** * Sets the value of a property. If the silent property is passed as * true, the property's event will not be fired. * @method setProperty * @param {String} key The name of the property * @param {String} value The value to set the property to * @param {Boolean} silent Whether the value should be set silently, * without firing the property event. * @return {Boolean} True, if the set was successful, false if it failed. */ setProperty: function (key, value, silent) { var property; key = key.toLowerCase(); YAHOO.log("setProperty: " + key + "=" + value, "info", "Config"); if (this.queueInProgress && ! silent) { // Currently running through a queue... this.queueProperty(key,value); return true; } else { property = this.config[key]; if (property && property.event) { if (property.validator && !property.validator(value)) { return false; } else { property.value = value; if (! silent) { this.fireEvent(key, value); this.configChangedEvent.fire([key, value]); } return true; } } else { return false; } } }, /** * Sets the value of a property and queues its event to execute. If the * event is already scheduled to execute, it is * moved from its current position to the end of the queue. * @method queueProperty * @param {String} key The name of the property * @param {String} value The value to set the property to * @return {Boolean} true, if the set was successful, false if * it failed. */ queueProperty: function (key, value) { key = key.toLowerCase(); YAHOO.log("queueProperty: " + key + "=" + value, "info", "Config"); var property = this.config[key], foundDuplicate = false, iLen, queueItem, queueItemKey, queueItemValue, sLen, supercedesCheck, qLen, queueItemCheck, queueItemCheckKey, queueItemCheckValue, i, s, q; if (property && property.event) { if (!Lang.isUndefined(value) && property.validator && !property.validator(value)) { // validator return false; } else { if (!Lang.isUndefined(value)) { property.value = value; } else { value = property.value; } foundDuplicate = false; iLen = this.eventQueue.length; for (i = 0; i < iLen; i++) { queueItem = this.eventQueue[i]; if (queueItem) { queueItemKey = queueItem[0]; queueItemValue = queueItem[1]; if (queueItemKey == key) { /* found a dupe... push to end of queue, null current item, and break */ this.eventQueue[i] = null; this.eventQueue.push( [key, (!Lang.isUndefined(value) ? value : queueItemValue)]); foundDuplicate = true; break; } } } // this is a refire, or a new property in the queue if (! foundDuplicate && !Lang.isUndefined(value)) { this.eventQueue.push([key, value]); } } if (property.supercedes) { sLen = property.supercedes.length; for (s = 0; s < sLen; s++) { supercedesCheck = property.supercedes[s]; qLen = this.eventQueue.length; for (q = 0; q < qLen; q++) { queueItemCheck = this.eventQueue[q]; if (queueItemCheck) { queueItemCheckKey = queueItemCheck[0]; queueItemCheckValue = queueItemCheck[1]; if (queueItemCheckKey == supercedesCheck.toLowerCase() ) { this.eventQueue.push([queueItemCheckKey, queueItemCheckValue]); this.eventQueue[q] = null; break; } } } } } YAHOO.log("Config event queue: " + this.outputEventQueue(), "info", "Config"); return true; } else { return false; } }, /** * Fires the event for a property using the property's current value. * @method refireEvent * @param {String} key The name of the property */ refireEvent: function (key) { key = key.toLowerCase(); var property = this.config[key]; if (property && property.event && !Lang.isUndefined(property.value)) { if (this.queueInProgress) { this.queueProperty(key); } else { this.fireEvent(key, property.value); } } }, /** * Applies a key-value Object literal to the configuration, replacing * any existing values, and queueing the property events. * Although the values will be set, fireQueue() must be called for their * associated events to execute. * @method applyConfig * @param {Object} userConfig The configuration Object literal * @param {Boolean} init When set to true, the initialConfig will * be set to the userConfig passed in, so that calling a reset will * reset the properties to the passed values. */ applyConfig: function (userConfig, init) { var sKey, oConfig; if (init) { oConfig = {}; for (sKey in userConfig) { if (Lang.hasOwnProperty(userConfig, sKey)) { oConfig[sKey.toLowerCase()] = userConfig[sKey]; } } this.initialConfig = oConfig; } for (sKey in userConfig) { if (Lang.hasOwnProperty(userConfig, sKey)) { this.queueProperty(sKey, userConfig[sKey]); } } }, /** * Refires the events for all configuration properties using their * current values. * @method refresh */ refresh: function () { var prop; for (prop in this.config) { if (Lang.hasOwnProperty(this.config, prop)) { this.refireEvent(prop); } } }, /** * Fires the normalized list of queued property change events * @method fireQueue */ fireQueue: function () { var i, queueItem, key, value, property; this.queueInProgress = true; for (i = 0;i < this.eventQueue.length; i++) { queueItem = this.eventQueue[i]; if (queueItem) { key = queueItem[0]; value = queueItem[1]; property = this.config[key]; property.value = value; // Clear out queue entry, to avoid it being // re-added to the queue by any queueProperty/supercedes // calls which are invoked during fireEvent this.eventQueue[i] = null; this.fireEvent(key,value); } } this.queueInProgress = false; this.eventQueue = []; }, /** * Subscribes an external handler to the change event for any * given property. * @method subscribeToConfigEvent * @param {String} key The property name * @param {Function} handler The handler function to use subscribe to * the property's event * @param {Object} obj The Object to use for scoping the event handler * (see CustomEvent documentation) * @param {Boolean} overrideContext Optional. If true, will override * "this" within the handler to map to the scope Object passed into the * method. * @return {Boolean} True, if the subscription was successful, * otherwise false. */ subscribeToConfigEvent: function (key, handler, obj, overrideContext) { var property = this.config[key.toLowerCase()]; if (property && property.event) { if (!Config.alreadySubscribed(property.event, handler, obj)) { property.event.subscribe(handler, obj, overrideContext); } return true; } else { return false; } }, /** * Unsubscribes an external handler from the change event for any * given property. * @method unsubscribeFromConfigEvent * @param {String} key The property name * @param {Function} handler The handler function to use subscribe to * the property's event * @param {Object} obj The Object to use for scoping the event * handler (see CustomEvent documentation) * @return {Boolean} True, if the unsubscription was successful, * otherwise false. */ unsubscribeFromConfigEvent: function (key, handler, obj) { var property = this.config[key.toLowerCase()]; if (property && property.event) { return property.event.unsubscribe(handler, obj); } else { return false; } }, /** * Returns a string representation of the Config object * @method toString * @return {String} The Config object in string format. */ toString: function () { var output = "Config"; if (this.owner) { output += " [" + this.owner.toString() + "]"; } return output; }, /** * Returns a string representation of the Config object's current * CustomEvent queue * @method outputEventQueue * @return {String} The string list of CustomEvents currently queued * for execution */ outputEventQueue: function () { var output = "", queueItem, q, nQueue = this.eventQueue.length; for (q = 0; q < nQueue; q++) { queueItem = this.eventQueue[q]; if (queueItem) { output += queueItem[0] + "=" + queueItem[1] + ", "; } } return output; }, /** * Sets all properties to null, unsubscribes all listeners from each * property's change event and all listeners from the configChangedEvent. * @method destroy */ destroy: function () { var oConfig = this.config, sProperty, oProperty; for (sProperty in oConfig) { if (Lang.hasOwnProperty(oConfig, sProperty)) { oProperty = oConfig[sProperty]; oProperty.event.unsubscribeAll(); oProperty.event = null; } } this.configChangedEvent.unsubscribeAll(); this.configChangedEvent = null; this.owner = null; this.config = null; this.initialConfig = null; this.eventQueue = null; } }; /** * Checks to determine if a particular function/Object pair are already * subscribed to the specified CustomEvent * @method YAHOO.util.Config.alreadySubscribed * @static * @param {YAHOO.util.CustomEvent} evt The CustomEvent for which to check * the subscriptions * @param {Function} fn The function to look for in the subscribers list * @param {Object} obj The execution scope Object for the subscription * @return {Boolean} true, if the function/Object pair is already subscribed * to the CustomEvent passed in */ Config.alreadySubscribed = function (evt, fn, obj) { var nSubscribers = evt.subscribers.length, subsc, i; if (nSubscribers > 0) { i = nSubscribers - 1; do { subsc = evt.subscribers[i]; if (subsc && subsc.obj == obj && subsc.fn == fn) { return true; } } while (i--); } return false; }; YAHOO.lang.augmentProto(Config, YAHOO.util.EventProvider); }()); (function () { /** * The Container family of components is designed to enable developers to * create different kinds of content-containing modules on the web. Module * and Overlay are the most basic containers, and they can be used directly * or extended to build custom containers. Also part of the Container family * are four UI controls that extend Module and Overlay: Tooltip, Panel, * Dialog, and SimpleDialog. * @module container * @title Container * @requires yahoo, dom, event * @optional dragdrop, animation, button */ /** * Module is a JavaScript representation of the Standard Module Format. * Standard Module Format is a simple standard for markup containers where * child nodes representing the header, body, and footer of the content are * denoted using the CSS classes "hd", "bd", and "ft" respectively. * Module is the base class for all other classes in the YUI * Container package. * @namespace YAHOO.widget * @class Module * @constructor * @param {String} el The element ID representing the Module <em>OR</em> * @param {HTMLElement} el The element representing the Module * @param {Object} userConfig The configuration Object literal containing * the configuration that should be set for this module. See configuration * documentation for more details. */ YAHOO.widget.Module = function (el, userConfig) { if (el) { this.init(el, userConfig); } else { YAHOO.log("No element or element ID specified" + " for Module instantiation", "error"); } }; var Dom = YAHOO.util.Dom, Config = YAHOO.util.Config, Event = YAHOO.util.Event, CustomEvent = YAHOO.util.CustomEvent, Module = YAHOO.widget.Module, UA = YAHOO.env.ua, m_oModuleTemplate, m_oHeaderTemplate, m_oBodyTemplate, m_oFooterTemplate, /** * Constant representing the name of the Module's events * @property EVENT_TYPES * @private * @final * @type Object */ EVENT_TYPES = { "BEFORE_INIT": "beforeInit", "INIT": "init", "APPEND": "append", "BEFORE_RENDER": "beforeRender", "RENDER": "render", "CHANGE_HEADER": "changeHeader", "CHANGE_BODY": "changeBody", "CHANGE_FOOTER": "changeFooter", "CHANGE_CONTENT": "changeContent", "DESTROY": "destroy", "BEFORE_SHOW": "beforeShow", "SHOW": "show", "BEFORE_HIDE": "beforeHide", "HIDE": "hide" }, /** * Constant representing the Module's configuration properties * @property DEFAULT_CONFIG * @private * @final * @type Object */ DEFAULT_CONFIG = { "VISIBLE": { key: "visible", value: true, validator: YAHOO.lang.isBoolean }, "EFFECT": { key: "effect", suppressEvent: true, supercedes: ["visible"] }, "MONITOR_RESIZE": { key: "monitorresize", value: true }, "APPEND_TO_DOCUMENT_BODY": { key: "appendtodocumentbody", value: false } }; /** * Constant representing the prefix path to use for non-secure images * @property YAHOO.widget.Module.IMG_ROOT * @static * @final * @type String */ Module.IMG_ROOT = null; /** * Constant representing the prefix path to use for securely served images * @property YAHOO.widget.Module.IMG_ROOT_SSL * @static * @final * @type String */ Module.IMG_ROOT_SSL = null; /** * Constant for the default CSS class name that represents a Module * @property YAHOO.widget.Module.CSS_MODULE * @static * @final * @type String */ Module.CSS_MODULE = "yui-module"; /** * CSS classname representing the module header. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @property YAHOO.widget.Module.CSS_HEADER * @static * @final * @type String */ Module.CSS_HEADER = "hd"; /** * CSS classname representing the module body. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @property YAHOO.widget.Module.CSS_BODY * @static * @final * @type String */ Module.CSS_BODY = "bd"; /** * CSS classname representing the module footer. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @property YAHOO.widget.Module.CSS_FOOTER * @static * @final * @type String */ Module.CSS_FOOTER = "ft"; /** * Constant representing the url for the "src" attribute of the iframe * used to monitor changes to the browser's base font size * @property YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL * @static * @final * @type String */ Module.RESIZE_MONITOR_SECURE_URL = "javascript:false;"; /** * Constant representing the buffer amount (in pixels) to use when positioning * the text resize monitor offscreen. The resize monitor is positioned * offscreen by an amount eqaul to its offsetHeight + the buffer value. * * @property YAHOO.widget.Module.RESIZE_MONITOR_BUFFER * @static * @type Number */ // Set to 1, to work around pixel offset in IE8, which increases when zoom is used Module.RESIZE_MONITOR_BUFFER = 1; /** * Singleton CustomEvent fired when the font size is changed in the browser. * Opera's "zoom" functionality currently does not support text * size detection. * @event YAHOO.widget.Module.textResizeEvent */ Module.textResizeEvent = new CustomEvent("textResize"); /** * Helper utility method, which forces a document level * redraw for Opera, which can help remove repaint * irregularities after applying DOM changes. * * @method YAHOO.widget.Module.forceDocumentRedraw * @static */ Module.forceDocumentRedraw = function() { var docEl = document.documentElement; if (docEl) { docEl.className += " "; docEl.className = YAHOO.lang.trim(docEl.className); } }; function createModuleTemplate() { if (!m_oModuleTemplate) { m_oModuleTemplate = document.createElement("div"); m_oModuleTemplate.innerHTML = ("<div class=\"" + Module.CSS_HEADER + "\"></div>" + "<div class=\"" + Module.CSS_BODY + "\"></div><div class=\"" + Module.CSS_FOOTER + "\"></div>"); m_oHeaderTemplate = m_oModuleTemplate.firstChild; m_oBodyTemplate = m_oHeaderTemplate.nextSibling; m_oFooterTemplate = m_oBodyTemplate.nextSibling; } return m_oModuleTemplate; } function createHeader() { if (!m_oHeaderTemplate) { createModuleTemplate(); } return (m_oHeaderTemplate.cloneNode(false)); } function createBody() { if (!m_oBodyTemplate) { createModuleTemplate(); } return (m_oBodyTemplate.cloneNode(false)); } function createFooter() { if (!m_oFooterTemplate) { createModuleTemplate(); } return (m_oFooterTemplate.cloneNode(false)); } Module.prototype = { /** * The class's constructor function * @property contructor * @type Function */ constructor: Module, /** * The main module element that contains the header, body, and footer * @property element * @type HTMLElement */ element: null, /** * The header element, denoted with CSS class "hd" * @property header * @type HTMLElement */ header: null, /** * The body element, denoted with CSS class "bd" * @property body * @type HTMLElement */ body: null, /** * The footer element, denoted with CSS class "ft" * @property footer * @type HTMLElement */ footer: null, /** * The id of the element * @property id * @type String */ id: null, /** * A string representing the root path for all images created by * a Module instance. * @deprecated It is recommend that any images for a Module be applied * via CSS using the "background-image" property. * @property imageRoot * @type String */ imageRoot: Module.IMG_ROOT, /** * Initializes the custom events for Module which are fired * automatically at appropriate times by the Module class. * @method initEvents */ initEvents: function () { var SIGNATURE = CustomEvent.LIST; /** * CustomEvent fired prior to class initalization. * @event beforeInitEvent * @param {class} classRef class reference of the initializing * class, such as this.beforeInitEvent.fire(Module) */ this.beforeInitEvent = this.createEvent(EVENT_TYPES.BEFORE_INIT); this.beforeInitEvent.signature = SIGNATURE; /** * CustomEvent fired after class initalization. * @event initEvent * @param {class} classRef class reference of the initializing * class, such as this.beforeInitEvent.fire(Module) */ this.initEvent = this.createEvent(EVENT_TYPES.INIT); this.initEvent.signature = SIGNATURE; /** * CustomEvent fired when the Module is appended to the DOM * @event appendEvent */ this.appendEvent = this.createEvent(EVENT_TYPES.APPEND); this.appendEvent.signature = SIGNATURE; /** * CustomEvent fired before the Module is rendered * @event beforeRenderEvent */ this.beforeRenderEvent = this.createEvent(EVENT_TYPES.BEFORE_RENDER); this.beforeRenderEvent.signature = SIGNATURE; /** * CustomEvent fired after the Module is rendered * @event renderEvent */ this.renderEvent = this.createEvent(EVENT_TYPES.RENDER); this.renderEvent.signature = SIGNATURE; /** * CustomEvent fired when the header content of the Module * is modified * @event changeHeaderEvent * @param {String/HTMLElement} content String/element representing * the new header content */ this.changeHeaderEvent = this.createEvent(EVENT_TYPES.CHANGE_HEADER); this.changeHeaderEvent.signature = SIGNATURE; /** * CustomEvent fired when the body content of the Module is modified * @event changeBodyEvent * @param {String/HTMLElement} content String/element representing * the new body content */ this.changeBodyEvent = this.createEvent(EVENT_TYPES.CHANGE_BODY); this.changeBodyEvent.signature = SIGNATURE; /** * CustomEvent fired when the footer content of the Module * is modified * @event changeFooterEvent * @param {String/HTMLElement} content String/element representing * the new footer content */ this.changeFooterEvent = this.createEvent(EVENT_TYPES.CHANGE_FOOTER); this.changeFooterEvent.signature = SIGNATURE; /** * CustomEvent fired when the content of the Module is modified * @event changeContentEvent */ this.changeContentEvent = this.createEvent(EVENT_TYPES.CHANGE_CONTENT); this.changeContentEvent.signature = SIGNATURE; /** * CustomEvent fired when the Module is destroyed * @event destroyEvent */ this.destroyEvent = this.createEvent(EVENT_TYPES.DESTROY); this.destroyEvent.signature = SIGNATURE; /** * CustomEvent fired before the Module is shown * @event beforeShowEvent */ this.beforeShowEvent = this.createEvent(EVENT_TYPES.BEFORE_SHOW); this.beforeShowEvent.signature = SIGNATURE; /** * CustomEvent fired after the Module is shown * @event showEvent */ this.showEvent = this.createEvent(EVENT_TYPES.SHOW); this.showEvent.signature = SIGNATURE; /** * CustomEvent fired before the Module is hidden * @event beforeHideEvent */ this.beforeHideEvent = this.createEvent(EVENT_TYPES.BEFORE_HIDE); this.beforeHideEvent.signature = SIGNATURE; /** * CustomEvent fired after the Module is hidden * @event hideEvent */ this.hideEvent = this.createEvent(EVENT_TYPES.HIDE); this.hideEvent.signature = SIGNATURE; }, /** * String identifying whether the current platform is windows or mac. This property * currently only identifies these 2 platforms, and returns false otherwise. * @property platform * @deprecated Use YAHOO.env.ua * @type {String|Boolean} */ platform: function () { var ua = navigator.userAgent.toLowerCase(); if (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1) { return "windows"; } else if (ua.indexOf("macintosh") != -1) { return "mac"; } else { return false; } }(), /** * String representing the user-agent of the browser * @deprecated Use YAHOO.env.ua * @property browser * @type {String|Boolean} */ browser: function () { var ua = navigator.userAgent.toLowerCase(); /* Check Opera first in case of spoof and check Safari before Gecko since Safari's user agent string includes "like Gecko" */ if (ua.indexOf('opera') != -1) { return 'opera'; } else if (ua.indexOf('msie 7') != -1) { return 'ie7'; } else if (ua.indexOf('msie') != -1) { return 'ie'; } else if (ua.indexOf('safari') != -1) { return 'safari'; } else if (ua.indexOf('gecko') != -1) { return 'gecko'; } else { return false; } }(), /** * Boolean representing whether or not the current browsing context is * secure (https) * @property isSecure * @type Boolean */ isSecure: function () { if (window.location.href.toLowerCase().indexOf("https") === 0) { return true; } else { return false; } }(), /** * Initializes the custom events for Module which are fired * automatically at appropriate times by the Module class. */ initDefaultConfig: function () { // Add properties // /** * Specifies whether the Module is visible on the page. * @config visible * @type Boolean * @default true */ this.cfg.addProperty(DEFAULT_CONFIG.VISIBLE.key, { handler: this.configVisible, value: DEFAULT_CONFIG.VISIBLE.value, validator: DEFAULT_CONFIG.VISIBLE.validator }); /** * <p> * Object or array of objects representing the ContainerEffect * classes that are active for animating the container. * </p> * <p> * <strong>NOTE:</strong> Although this configuration * property is introduced at the Module level, an out of the box * implementation is not shipped for the Module class so setting * the proroperty on the Module class has no effect. The Overlay * class is the first class to provide out of the box ContainerEffect * support. * </p> * @config effect * @type Object * @default null */ this.cfg.addProperty(DEFAULT_CONFIG.EFFECT.key, { handler: this.configEffect, suppressEvent: DEFAULT_CONFIG.EFFECT.suppressEvent, supercedes: DEFAULT_CONFIG.EFFECT.supercedes }); /** * Specifies whether to create a special proxy iframe to monitor * for user font resizing in the document * @config monitorresize * @type Boolean * @default true */ this.cfg.addProperty(DEFAULT_CONFIG.MONITOR_RESIZE.key, { handler: this.configMonitorResize, value: DEFAULT_CONFIG.MONITOR_RESIZE.value }); /** * Specifies if the module should be rendered as the first child * of document.body or appended as the last child when render is called * with document.body as the "appendToNode". * <p> * Appending to the body while the DOM is still being constructed can * lead to Operation Aborted errors in IE hence this flag is set to * false by default. * </p> * * @config appendtodocumentbody * @type Boolean * @default false */ this.cfg.addProperty(DEFAULT_CONFIG.APPEND_TO_DOCUMENT_BODY.key, { value: DEFAULT_CONFIG.APPEND_TO_DOCUMENT_BODY.value }); }, /** * The Module class's initialization method, which is executed for * Module and all of its subclasses. This method is automatically * called by the constructor, and sets up all DOM references for * pre-existing markup, and creates required markup if it is not * already present. * <p> * If the element passed in does not have an id, one will be generated * for it. * </p> * @method init * @param {String} el The element ID representing the Module <em>OR</em> * @param {HTMLElement} el The element representing the Module * @param {Object} userConfig The configuration Object literal * containing the configuration that should be set for this module. * See configuration documentation for more details. */ init: function (el, userConfig) { var elId, child; this.initEvents(); this.beforeInitEvent.fire(Module); /** * The Module's Config object used for monitoring * configuration properties. * @property cfg * @type YAHOO.util.Config */ this.cfg = new Config(this); if (this.isSecure) { this.imageRoot = Module.IMG_ROOT_SSL; } if (typeof el == "string") { elId = el; el = document.getElementById(el); if (! el) { el = (createModuleTemplate()).cloneNode(false); el.id = elId; } } this.id = Dom.generateId(el); this.element = el; child = this.element.firstChild; if (child) { var fndHd = false, fndBd = false, fndFt = false; do { // We're looking for elements if (1 == child.nodeType) { if (!fndHd && Dom.hasClass(child, Module.CSS_HEADER)) { this.header = child; fndHd = true; } else if (!fndBd && Dom.hasClass(child, Module.CSS_BODY)) { this.body = child; fndBd = true; } else if (!fndFt && Dom.hasClass(child, Module.CSS_FOOTER)){ this.footer = child; fndFt = true; } } } while ((child = child.nextSibling)); } this.initDefaultConfig(); Dom.addClass(this.element, Module.CSS_MODULE); if (userConfig) { this.cfg.applyConfig(userConfig, true); } /* Subscribe to the fireQueue() method of Config so that any queued configuration changes are excecuted upon render of the Module */ if (!Config.alreadySubscribed(this.renderEvent, this.cfg.fireQueue, this.cfg)) { this.renderEvent.subscribe(this.cfg.fireQueue, this.cfg, true); } this.initEvent.fire(Module); }, /** * Initialize an empty IFRAME that is placed out of the visible area * that can be used to detect text resize. * @method initResizeMonitor */ initResizeMonitor: function () { var isGeckoWin = (UA.gecko && this.platform == "windows"); if (isGeckoWin) { // Help prevent spinning loading icon which // started with FireFox 2.0.0.8/Win var self = this; setTimeout(function(){self._initResizeMonitor();}, 0); } else { this._initResizeMonitor(); } }, /** * Create and initialize the text resize monitoring iframe. * * @protected * @method _initResizeMonitor */ _initResizeMonitor : function() { var oDoc, oIFrame, sHTML; function fireTextResize() { Module.textResizeEvent.fire(); } if (!UA.opera) { oIFrame = Dom.get("_yuiResizeMonitor"); var supportsCWResize = this._supportsCWResize(); if (!oIFrame) { oIFrame = document.createElement("iframe"); if (this.isSecure && Module.RESIZE_MONITOR_SECURE_URL && UA.ie) { oIFrame.src = Module.RESIZE_MONITOR_SECURE_URL; } if (!supportsCWResize) { // Can't monitor on contentWindow, so fire from inside iframe sHTML = ["<html><head><script ", "type=\"text/javascript\">", "window.onresize=function(){window.parent.", "YAHOO.widget.Module.textResizeEvent.", "fire();};<", "\/script></head>", "<body></body></html>"].join(''); oIFrame.src = "data:text/html;charset=utf-8," + encodeURIComponent(sHTML); } oIFrame.id = "_yuiResizeMonitor"; oIFrame.title = "Text Resize Monitor"; oIFrame.tabIndex = -1; oIFrame.setAttribute("role", "presentation"); /* Need to set "position" property before inserting the iframe into the document or Safari's status bar will forever indicate the iframe is loading (See YUILibrary bug #1723064) */ oIFrame.style.position = "absolute"; oIFrame.style.visibility = "hidden"; var db = document.body, fc = db.firstChild; if (fc) { db.insertBefore(oIFrame, fc); } else { db.appendChild(oIFrame); } // Setting the background color fixes an issue with IE6/IE7, where // elements in the DOM, with -ve margin-top which positioned them // offscreen (so they would be overlapped by the iframe and its -ve top // setting), would have their -ve margin-top ignored, when the iframe // was added. oIFrame.style.backgroundColor = "transparent"; oIFrame.style.borderWidth = "0"; oIFrame.style.width = "2em"; oIFrame.style.height = "2em"; oIFrame.style.left = "0"; oIFrame.style.top = (-1 * (oIFrame.offsetHeight + Module.RESIZE_MONITOR_BUFFER)) + "px"; oIFrame.style.visibility = "visible"; /* Don't open/close the document for Gecko like we used to, since it leads to duplicate cookies. (See YUILibrary bug #1721755) */ if (UA.webkit) { oDoc = oIFrame.contentWindow.document; oDoc.open(); oDoc.close(); } } if (oIFrame && oIFrame.contentWindow) { Module.textResizeEvent.subscribe(this.onDomResize, this, true); if (!Module.textResizeInitialized) { if (supportsCWResize) { if (!Event.on(oIFrame.contentWindow, "resize", fireTextResize)) { /* This will fail in IE if document.domain has changed, so we must change the listener to use the oIFrame element instead */ Event.on(oIFrame, "resize", fireTextResize); } } Module.textResizeInitialized = true; } this.resizeMonitor = oIFrame; } } }, /** * Text resize monitor helper method. * Determines if the browser supports resize events on iframe content windows. * * @private * @method _supportsCWResize */ _supportsCWResize : function() { /* Gecko 1.8.0 (FF1.5), 1.8.1.0-5 (FF2) won't fire resize on contentWindow. Gecko 1.8.1.6+ (FF2.0.0.6+) and all other browsers will fire resize on contentWindow. We don't want to start sniffing for patch versions, so fire textResize the same way on all FF2 flavors */ var bSupported = true; if (UA.gecko && UA.gecko <= 1.8) { bSupported = false; } return bSupported; }, /** * Event handler fired when the resize monitor element is resized. * @method onDomResize * @param {DOMEvent} e The DOM resize event * @param {Object} obj The scope object passed to the handler */ onDomResize: function (e, obj) { var nTop = -1 * (this.resizeMonitor.offsetHeight + Module.RESIZE_MONITOR_BUFFER); this.resizeMonitor.style.top = nTop + "px"; this.resizeMonitor.style.left = "0"; }, /** * Sets the Module's header content to the markup specified, or appends * the passed element to the header. * * If no header is present, one will * be automatically created. An empty string can be passed to the method * to clear the contents of the header. * * @method setHeader * @param {HTML} headerContent The markup used to set the header content. * As a convenience, non HTMLElement objects can also be passed into * the method, and will be treated as strings, with the header innerHTML * set to their default toString implementations. * * <p>NOTE: Markup passed into this method is added to the DOM as HTML, and should be escaped by the implementor if coming from an external source.</p> * * <em>OR</em> * @param {HTMLElement} headerContent The HTMLElement to append to * <em>OR</em> * @param {DocumentFragment} headerContent The document fragment * containing elements which are to be added to the header */ setHeader: function (headerContent) { var oHeader = this.header || (this.header = createHeader()); if (headerContent.nodeName) { oHeader.innerHTML = ""; oHeader.appendChild(headerContent); } else { oHeader.innerHTML = headerContent; } if (this._rendered) { this._renderHeader(); } this.changeHeaderEvent.fire(headerContent); this.changeContentEvent.fire(); }, /** * Appends the passed element to the header. If no header is present, * one will be automatically created. * @method appendToHeader * @param {HTMLElement | DocumentFragment} element The element to * append to the header. In the case of a document fragment, the * children of the fragment will be appended to the header. */ appendToHeader: function (element) { var oHeader = this.header || (this.header = createHeader()); oHeader.appendChild(element); this.changeHeaderEvent.fire(element); this.changeContentEvent.fire(); }, /** * Sets the Module's body content to the HTML specified. * * If no body is present, one will be automatically created. * * An empty string can be passed to the method to clear the contents of the body. * @method setBody * @param {HTML} bodyContent The HTML used to set the body content * As a convenience, non HTMLElement objects can also be passed into * the method, and will be treated as strings, with the body innerHTML * set to their default toString implementations. * * <p>NOTE: Markup passed into this method is added to the DOM as HTML, and should be escaped by the implementor if coming from an external source.</p> * * <em>OR</em> * @param {HTMLElement} bodyContent The HTMLElement to add as the first and only * child of the body element. * <em>OR</em> * @param {DocumentFragment} bodyContent The document fragment * containing elements which are to be added to the body */ setBody: function (bodyContent) { var oBody = this.body || (this.body = createBody()); if (bodyContent.nodeName) { oBody.innerHTML = ""; oBody.appendChild(bodyContent); } else { oBody.innerHTML = bodyContent; } if (this._rendered) { this._renderBody(); } this.changeBodyEvent.fire(bodyContent); this.changeContentEvent.fire(); }, /** * Appends the passed element to the body. If no body is present, one * will be automatically created. * @method appendToBody * @param {HTMLElement | DocumentFragment} element The element to * append to the body. In the case of a document fragment, the * children of the fragment will be appended to the body. * */ appendToBody: function (element) { var oBody = this.body || (this.body = createBody()); oBody.appendChild(element); this.changeBodyEvent.fire(element); this.changeContentEvent.fire(); }, /** * Sets the Module's footer content to the HTML specified, or appends * the passed element to the footer. If no footer is present, one will * be automatically created. An empty string can be passed to the method * to clear the contents of the footer. * @method setFooter * @param {HTML} footerContent The HTML used to set the footer * As a convenience, non HTMLElement objects can also be passed into * the method, and will be treated as strings, with the footer innerHTML * set to their default toString implementations. * * <p>NOTE: Markup passed into this method is added to the DOM as HTML, and should be escaped by the implementor if coming from an external source.</p> * * <em>OR</em> * @param {HTMLElement} footerContent The HTMLElement to append to * the footer * <em>OR</em> * @param {DocumentFragment} footerContent The document fragment containing * elements which are to be added to the footer */ setFooter: function (footerContent) { var oFooter = this.footer || (this.footer = createFooter()); if (footerContent.nodeName) { oFooter.innerHTML = ""; oFooter.appendChild(footerContent); } else { oFooter.innerHTML = footerContent; } if (this._rendered) { this._renderFooter(); } this.changeFooterEvent.fire(footerContent); this.changeContentEvent.fire(); }, /** * Appends the passed element to the footer. If no footer is present, * one will be automatically created. * @method appendToFooter * @param {HTMLElement | DocumentFragment} element The element to * append to the footer. In the case of a document fragment, the * children of the fragment will be appended to the footer */ appendToFooter: function (element) { var oFooter = this.footer || (this.footer = createFooter()); oFooter.appendChild(element); this.changeFooterEvent.fire(element); this.changeContentEvent.fire(); }, /** * Renders the Module by inserting the elements that are not already * in the main Module into their correct places. Optionally appends * the Module to the specified node prior to the render's execution. * <p> * For Modules without existing markup, the appendToNode argument * is REQUIRED. If this argument is ommitted and the current element is * not present in the document, the function will return false, * indicating that the render was a failure. * </p> * <p> * NOTE: As of 2.3.1, if the appendToNode is the document's body element * then the module is rendered as the first child of the body element, * and not appended to it, to avoid Operation Aborted errors in IE when * rendering the module before window's load event is fired. You can * use the appendtodocumentbody configuration property to change this * to append to document.body if required. * </p> * @method render * @param {String} appendToNode The element id to which the Module * should be appended to prior to rendering <em>OR</em> * @param {HTMLElement} appendToNode The element to which the Module * should be appended to prior to rendering * @param {HTMLElement} moduleElement OPTIONAL. The element that * represents the actual Standard Module container. * @return {Boolean} Success or failure of the render */ render: function (appendToNode, moduleElement) { var me = this; function appendTo(parentNode) { if (typeof parentNode == "string") { parentNode = document.getElementById(parentNode); } if (parentNode) { me._addToParent(parentNode, me.element); me.appendEvent.fire(); } } this.beforeRenderEvent.fire(); if (! moduleElement) { moduleElement = this.element; } if (appendToNode) { appendTo(appendToNode); } else { // No node was passed in. If the element is not already in the Dom, this fails if (! Dom.inDocument(this.element)) { YAHOO.log("Render failed. Must specify appendTo node if " + " Module isn't already in the DOM.", "error"); return false; } } this._renderHeader(moduleElement); this._renderBody(moduleElement); this._renderFooter(moduleElement); this._rendered = true; this.renderEvent.fire(); return true; }, /** * Renders the currently set header into it's proper position under the * module element. If the module element is not provided, "this.element" * is used. * * @method _renderHeader * @protected * @param {HTMLElement} moduleElement Optional. A reference to the module element */ _renderHeader: function(moduleElement){ moduleElement = moduleElement || this.element; // Need to get everything into the DOM if it isn't already if (this.header && !Dom.inDocument(this.header)) { // There is a header, but it's not in the DOM yet. Need to add it. var firstChild = moduleElement.firstChild; if (firstChild) { moduleElement.insertBefore(this.header, firstChild); } else { moduleElement.appendChild(this.header); } } }, /** * Renders the currently set body into it's proper position under the * module element. If the module element is not provided, "this.element" * is used. * * @method _renderBody * @protected * @param {HTMLElement} moduleElement Optional. A reference to the module element. */ _renderBody: function(moduleElement){ moduleElement = moduleElement || this.element; if (this.body && !Dom.inDocument(this.body)) { // There is a body, but it's not in the DOM yet. Need to add it. if (this.footer && Dom.isAncestor(moduleElement, this.footer)) { moduleElement.insertBefore(this.body, this.footer); } else { moduleElement.appendChild(this.body); } } }, /** * Renders the currently set footer into it's proper position under the * module element. If the module element is not provided, "this.element" * is used. * * @method _renderFooter * @protected * @param {HTMLElement} moduleElement Optional. A reference to the module element */ _renderFooter: function(moduleElement){ moduleElement = moduleElement || this.element; if (this.footer && !Dom.inDocument(this.footer)) { // There is a footer, but it's not in the DOM yet. Need to add it. moduleElement.appendChild(this.footer); } }, /** * Removes the Module element from the DOM, sets all child elements to null, and purges the bounding element of event listeners. * @method destroy * @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners. * NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0. */ destroy: function (shallowPurge) { var parent, purgeChildren = !(shallowPurge); if (this.element) { Event.purgeElement(this.element, purgeChildren); parent = this.element.parentNode; } if (parent) { parent.removeChild(this.element); } this.element = null; this.header = null; this.body = null; this.footer = null; Module.textResizeEvent.unsubscribe(this.onDomResize, this); this.cfg.destroy(); this.cfg = null; this.destroyEvent.fire(); }, /** * Shows the Module element by setting the visible configuration * property to true. Also fires two events: beforeShowEvent prior to * the visibility change, and showEvent after. * @method show */ show: function () { this.cfg.setProperty("visible", true); }, /** * Hides the Module element by setting the visible configuration * property to false. Also fires two events: beforeHideEvent prior to * the visibility change, and hideEvent after. * @method hide */ hide: function () { this.cfg.setProperty("visible", false); }, // BUILT-IN EVENT HANDLERS FOR MODULE // /** * Default event handler for changing the visibility property of a * Module. By default, this is achieved by switching the "display" style * between "block" and "none". * This method is responsible for firing showEvent and hideEvent. * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. * @method configVisible */ configVisible: function (type, args, obj) { var visible = args[0]; if (visible) { if(this.beforeShowEvent.fire()) { Dom.setStyle(this.element, "display", "block"); this.showEvent.fire(); } } else { if (this.beforeHideEvent.fire()) { Dom.setStyle(this.element, "display", "none"); this.hideEvent.fire(); } } }, /** * Default event handler for the "effect" configuration property * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. * @method configEffect */ configEffect: function (type, args, obj) { this._cachedEffects = (this.cacheEffects) ? this._createEffects(args[0]) : null; }, /** * If true, ContainerEffects (and Anim instances) are cached when "effect" is set, and reused. * If false, new instances are created each time the container is hidden or shown, as was the * behavior prior to 2.9.0. * * @property cacheEffects * @since 2.9.0 * @default true * @type boolean */ cacheEffects : true, /** * Creates an array of ContainerEffect instances from the provided configs * * @method _createEffects * @param {Array|Object} effectCfg An effect configuration or array of effect configurations * @return {Array} An array of ContainerEffect instances. * @protected */ _createEffects: function(effectCfg) { var effectInstances = null, n, i, eff; if (effectCfg) { if (effectCfg instanceof Array) { effectInstances = []; n = effectCfg.length; for (i = 0; i < n; i++) { eff = effectCfg[i]; if (eff.effect) { effectInstances[effectInstances.length] = eff.effect(this, eff.duration); } } } else if (effectCfg.effect) { effectInstances = [effectCfg.effect(this, effectCfg.duration)]; } } return effectInstances; }, /** * Default event handler for the "monitorresize" configuration property * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. * @method configMonitorResize */ configMonitorResize: function (type, args, obj) { var monitor = args[0]; if (monitor) { this.initResizeMonitor(); } else { Module.textResizeEvent.unsubscribe(this.onDomResize, this, true); this.resizeMonitor = null; } }, /** * This method is a protected helper, used when constructing the DOM structure for the module * to account for situations which may cause Operation Aborted errors in IE. It should not * be used for general DOM construction. * <p> * If the parentNode is not document.body, the element is appended as the last element. * </p> * <p> * If the parentNode is document.body the element is added as the first child to help * prevent Operation Aborted errors in IE. * </p> * * @param {parentNode} The HTML element to which the element will be added * @param {element} The HTML element to be added to parentNode's children * @method _addToParent * @protected */ _addToParent: function(parentNode, element) { if (!this.cfg.getProperty("appendtodocumentbody") && parentNode === document.body && parentNode.firstChild) { parentNode.insertBefore(element, parentNode.firstChild); } else { parentNode.appendChild(element); } }, /** * Returns a String representation of the Object. * @method toString * @return {String} The string representation of the Module */ toString: function () { return "Module " + this.id; } }; YAHOO.lang.augmentProto(Module, YAHOO.util.EventProvider); }()); (function () { /** * Overlay is a Module that is absolutely positioned above the page flow. It * has convenience methods for positioning and sizing, as well as options for * controlling zIndex and constraining the Overlay's position to the current * visible viewport. Overlay also contains a dynamicly generated IFRAME which * is placed beneath it for Internet Explorer 6 and 5.x so that it will be * properly rendered above SELECT elements. * @namespace YAHOO.widget * @class Overlay * @extends YAHOO.widget.Module * @param {String} el The element ID representing the Overlay <em>OR</em> * @param {HTMLElement} el The element representing the Overlay * @param {Object} userConfig The configuration object literal containing * the configuration that should be set for this Overlay. See configuration * documentation for more details. * @constructor */ YAHOO.widget.Overlay = function (el, userConfig) { YAHOO.widget.Overlay.superclass.constructor.call(this, el, userConfig); }; var Lang = YAHOO.lang, CustomEvent = YAHOO.util.CustomEvent, Module = YAHOO.widget.Module, Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, Config = YAHOO.util.Config, UA = YAHOO.env.ua, Overlay = YAHOO.widget.Overlay, _SUBSCRIBE = "subscribe", _UNSUBSCRIBE = "unsubscribe", _CONTAINED = "contained", m_oIFrameTemplate, /** * Constant representing the name of the Overlay's events * @property EVENT_TYPES * @private * @final * @type Object */ EVENT_TYPES = { "BEFORE_MOVE": "beforeMove", "MOVE": "move" }, /** * Constant representing the Overlay's configuration properties * @property DEFAULT_CONFIG * @private * @final * @type Object */ DEFAULT_CONFIG = { "X": { key: "x", validator: Lang.isNumber, suppressEvent: true, supercedes: ["iframe"] }, "Y": { key: "y", validator: Lang.isNumber, suppressEvent: true, supercedes: ["iframe"] }, "XY": { key: "xy", suppressEvent: true, supercedes: ["iframe"] }, "CONTEXT": { key: "context", suppressEvent: true, supercedes: ["iframe"] }, "FIXED_CENTER": { key: "fixedcenter", value: false, supercedes: ["iframe", "visible"] }, "WIDTH": { key: "width", suppressEvent: true, supercedes: ["context", "fixedcenter", "iframe"] }, "HEIGHT": { key: "height", suppressEvent: true, supercedes: ["context", "fixedcenter", "iframe"] }, "AUTO_FILL_HEIGHT" : { key: "autofillheight", supercedes: ["height"], value:"body" }, "ZINDEX": { key: "zindex", value: null }, "CONSTRAIN_TO_VIEWPORT": { key: "constraintoviewport", value: false, validator: Lang.isBoolean, supercedes: ["iframe", "x", "y", "xy"] }, "IFRAME": { key: "iframe", value: (UA.ie == 6 ? true : false), validator: Lang.isBoolean, supercedes: ["zindex"] }, "PREVENT_CONTEXT_OVERLAP": { key: "preventcontextoverlap", value: false, validator: Lang.isBoolean, supercedes: ["constraintoviewport"] } }; /** * The URL that will be placed in the iframe * @property YAHOO.widget.Overlay.IFRAME_SRC * @static * @final * @type String */ Overlay.IFRAME_SRC = "javascript:false;"; /** * Number representing how much the iframe shim should be offset from each * side of an Overlay instance, in pixels. * @property YAHOO.widget.Overlay.IFRAME_SRC * @default 3 * @static * @final * @type Number */ Overlay.IFRAME_OFFSET = 3; /** * Number representing the minimum distance an Overlay instance should be * positioned relative to the boundaries of the browser's viewport, in pixels. * @property YAHOO.widget.Overlay.VIEWPORT_OFFSET * @default 10 * @static * @final * @type Number */ Overlay.VIEWPORT_OFFSET = 10; /** * Constant representing the top left corner of an element, used for * configuring the context element alignment * @property YAHOO.widget.Overlay.TOP_LEFT * @static * @final * @type String */ Overlay.TOP_LEFT = "tl"; /** * Constant representing the top right corner of an element, used for * configuring the context element alignment * @property YAHOO.widget.Overlay.TOP_RIGHT * @static * @final * @type String */ Overlay.TOP_RIGHT = "tr"; /** * Constant representing the top bottom left corner of an element, used for * configuring the context element alignment * @property YAHOO.widget.Overlay.BOTTOM_LEFT * @static * @final * @type String */ Overlay.BOTTOM_LEFT = "bl"; /** * Constant representing the bottom right corner of an element, used for * configuring the context element alignment * @property YAHOO.widget.Overlay.BOTTOM_RIGHT * @static * @final * @type String */ Overlay.BOTTOM_RIGHT = "br"; Overlay.PREVENT_OVERLAP_X = { "tltr": true, "blbr": true, "brbl": true, "trtl": true }; Overlay.PREVENT_OVERLAP_Y = { "trbr": true, "tlbl": true, "bltl": true, "brtr": true }; /** * Constant representing the default CSS class used for an Overlay * @property YAHOO.widget.Overlay.CSS_OVERLAY * @static * @final * @type String */ Overlay.CSS_OVERLAY = "yui-overlay"; /** * Constant representing the default hidden CSS class used for an Overlay. This class is * applied to the overlay's outer DIV whenever it's hidden. * * @property YAHOO.widget.Overlay.CSS_HIDDEN * @static * @final * @type String */ Overlay.CSS_HIDDEN = "yui-overlay-hidden"; /** * Constant representing the default CSS class used for an Overlay iframe shim. * * @property YAHOO.widget.Overlay.CSS_IFRAME * @static * @final * @type String */ Overlay.CSS_IFRAME = "yui-overlay-iframe"; /** * Constant representing the names of the standard module elements * used in the overlay. * @property YAHOO.widget.Overlay.STD_MOD_RE * @static * @final * @type RegExp */ Overlay.STD_MOD_RE = /^\s*?(body|footer|header)\s*?$/i; /** * A singleton CustomEvent used for reacting to the DOM event for * window scroll * @event YAHOO.widget.Overlay.windowScrollEvent */ Overlay.windowScrollEvent = new CustomEvent("windowScroll"); /** * A singleton CustomEvent used for reacting to the DOM event for * window resize * @event YAHOO.widget.Overlay.windowResizeEvent */ Overlay.windowResizeEvent = new CustomEvent("windowResize"); /** * The DOM event handler used to fire the CustomEvent for window scroll * @method YAHOO.widget.Overlay.windowScrollHandler * @static * @param {DOMEvent} e The DOM scroll event */ Overlay.windowScrollHandler = function (e) { var t = Event.getTarget(e); // - Webkit (Safari 2/3) and Opera 9.2x bubble scroll events from elements to window // - FF2/3 and IE6/7, Opera 9.5x don't bubble scroll events from elements to window // - IE doesn't recognize scroll registered on the document. // // Also, when document view is scrolled, IE doesn't provide a target, // rest of the browsers set target to window.document, apart from opera // which sets target to window. if (!t || t === window || t === window.document) { if (UA.ie) { if (! window.scrollEnd) { window.scrollEnd = -1; } clearTimeout(window.scrollEnd); window.scrollEnd = setTimeout(function () { Overlay.windowScrollEvent.fire(); }, 1); } else { Overlay.windowScrollEvent.fire(); } } }; /** * The DOM event handler used to fire the CustomEvent for window resize * @method YAHOO.widget.Overlay.windowResizeHandler * @static * @param {DOMEvent} e The DOM resize event */ Overlay.windowResizeHandler = function (e) { if (UA.ie) { if (! window.resizeEnd) { window.resizeEnd = -1; } clearTimeout(window.resizeEnd); window.resizeEnd = setTimeout(function () { Overlay.windowResizeEvent.fire(); }, 100); } else { Overlay.windowResizeEvent.fire(); } }; /** * A boolean that indicated whether the window resize and scroll events have * already been subscribed to. * @property YAHOO.widget.Overlay._initialized * @private * @type Boolean */ Overlay._initialized = null; if (Overlay._initialized === null) { Event.on(window, "scroll", Overlay.windowScrollHandler); Event.on(window, "resize", Overlay.windowResizeHandler); Overlay._initialized = true; } /** * Internal map of special event types, which are provided * by the instance. It maps the event type to the custom event * instance. Contains entries for the "windowScroll", "windowResize" and * "textResize" static container events. * * @property YAHOO.widget.Overlay._TRIGGER_MAP * @type Object * @static * @private */ Overlay._TRIGGER_MAP = { "windowScroll" : Overlay.windowScrollEvent, "windowResize" : Overlay.windowResizeEvent, "textResize" : Module.textResizeEvent }; YAHOO.extend(Overlay, Module, { /** * <p> * Array of default event types which will trigger * context alignment for the Overlay class. * </p> * <p>The array is empty by default for Overlay, * but maybe populated in future releases, so classes extending * Overlay which need to define their own set of CONTEXT_TRIGGERS * should concatenate their super class's prototype.CONTEXT_TRIGGERS * value with their own array of values. * </p> * <p> * E.g.: * <code>CustomOverlay.prototype.CONTEXT_TRIGGERS = YAHOO.widget.Overlay.prototype.CONTEXT_TRIGGERS.concat(["windowScroll"]);</code> * </p> * * @property CONTEXT_TRIGGERS * @type Array * @final */ CONTEXT_TRIGGERS : [], /** * The Overlay initialization method, which is executed for Overlay and * all of its subclasses. This method is automatically called by the * constructor, and sets up all DOM references for pre-existing markup, * and creates required markup if it is not already present. * @method init * @param {String} el The element ID representing the Overlay <em>OR</em> * @param {HTMLElement} el The element representing the Overlay * @param {Object} userConfig The configuration object literal * containing the configuration that should be set for this Overlay. * See configuration documentation for more details. */ init: function (el, userConfig) { /* Note that we don't pass the user config in here yet because we only want it executed once, at the lowest subclass level */ Overlay.superclass.init.call(this, el/*, userConfig*/); this.beforeInitEvent.fire(Overlay); Dom.addClass(this.element, Overlay.CSS_OVERLAY); if (userConfig) { this.cfg.applyConfig(userConfig, true); } if (this.platform == "mac" && UA.gecko) { if (! Config.alreadySubscribed(this.showEvent, this.showMacGeckoScrollbars, this)) { this.showEvent.subscribe(this.showMacGeckoScrollbars, this, true); } if (! Config.alreadySubscribed(this.hideEvent, this.hideMacGeckoScrollbars, this)) { this.hideEvent.subscribe(this.hideMacGeckoScrollbars, this, true); } } this.initEvent.fire(Overlay); }, /** * Initializes the custom events for Overlay which are fired * automatically at appropriate times by the Overlay class. * @method initEvents */ initEvents: function () { Overlay.superclass.initEvents.call(this); var SIGNATURE = CustomEvent.LIST; /** * CustomEvent fired before the Overlay is moved. * @event beforeMoveEvent * @param {Number} x x coordinate * @param {Number} y y coordinate */ this.beforeMoveEvent = this.createEvent(EVENT_TYPES.BEFORE_MOVE); this.beforeMoveEvent.signature = SIGNATURE; /** * CustomEvent fired after the Overlay is moved. * @event moveEvent * @param {Number} x x coordinate * @param {Number} y y coordinate */ this.moveEvent = this.createEvent(EVENT_TYPES.MOVE); this.moveEvent.signature = SIGNATURE; }, /** * Initializes the class's configurable properties which can be changed * using the Overlay's Config object (cfg). * @method initDefaultConfig */ initDefaultConfig: function () { Overlay.superclass.initDefaultConfig.call(this); var cfg = this.cfg; // Add overlay config properties // /** * The absolute x-coordinate position of the Overlay * @config x * @type Number * @default null */ cfg.addProperty(DEFAULT_CONFIG.X.key, { handler: this.configX, validator: DEFAULT_CONFIG.X.validator, suppressEvent: DEFAULT_CONFIG.X.suppressEvent, supercedes: DEFAULT_CONFIG.X.supercedes }); /** * The absolute y-coordinate position of the Overlay * @config y * @type Number * @default null */ cfg.addProperty(DEFAULT_CONFIG.Y.key, { handler: this.configY, validator: DEFAULT_CONFIG.Y.validator, suppressEvent: DEFAULT_CONFIG.Y.suppressEvent, supercedes: DEFAULT_CONFIG.Y.supercedes }); /** * An array with the absolute x and y positions of the Overlay * @config xy * @type Number[] * @default null */ cfg.addProperty(DEFAULT_CONFIG.XY.key, { handler: this.configXY, suppressEvent: DEFAULT_CONFIG.XY.suppressEvent, supercedes: DEFAULT_CONFIG.XY.supercedes }); /** * <p> * The array of context arguments for context-sensitive positioning. * </p> * * <p> * The format of the array is: <code>[contextElementOrId, overlayCorner, contextCorner, arrayOfTriggerEvents (optional), xyOffset (optional)]</code>, the * the 5 array elements described in detail below: * </p> * * <dl> * <dt>contextElementOrId &#60;String|HTMLElement&#62;</dt> * <dd>A reference to the context element to which the overlay should be aligned (or it's id).</dd> * <dt>overlayCorner &#60;String&#62;</dt> * <dd>The corner of the overlay which is to be used for alignment. This corner will be aligned to the * corner of the context element defined by the "contextCorner" entry which follows. Supported string values are: * "tr" (top right), "tl" (top left), "br" (bottom right), or "bl" (bottom left).</dd> * <dt>contextCorner &#60;String&#62;</dt> * <dd>The corner of the context element which is to be used for alignment. Supported string values are the same ones listed for the "overlayCorner" entry above.</dd> * <dt>arrayOfTriggerEvents (optional) &#60;Array[String|CustomEvent]&#62;</dt> * <dd> * <p> * By default, context alignment is a one time operation, aligning the Overlay to the context element when context configuration property is set, or when the <a href="#method_align">align</a> * method is invoked. However, you can use the optional "arrayOfTriggerEvents" entry to define the list of events which should force the overlay to re-align itself with the context element. * This is useful in situations where the layout of the document may change, resulting in the context element's position being modified. * </p> * <p> * The array can contain either event type strings for events the instance publishes (e.g. "beforeShow") or CustomEvent instances. Additionally the following * 3 static container event types are also currently supported : <code>"windowResize", "windowScroll", "textResize"</code> (defined in <a href="#property__TRIGGER_MAP">_TRIGGER_MAP</a> private property). * </p> * </dd> * <dt>xyOffset &#60;Number[]&#62;</dt> * <dd> * A 2 element Array specifying the X and Y pixel amounts by which the Overlay should be offset from the aligned corner. e.g. [5,0] offsets the Overlay 5 pixels to the left, <em>after</em> aligning the given context corners. * NOTE: If using this property and no triggers need to be defined, the arrayOfTriggerEvents property should be set to null to maintain correct array positions for the arguments. * </dd> * </dl> * * <p> * For example, setting this property to <code>["img1", "tl", "bl"]</code> will * align the Overlay's top left corner to the bottom left corner of the * context element with id "img1". * </p> * <p> * Setting this property to <code>["img1", "tl", "bl", null, [0,5]</code> will * align the Overlay's top left corner to the bottom left corner of the * context element with id "img1", and then offset it by 5 pixels on the Y axis (providing a 5 pixel gap between the bottom of the context element and top of the overlay). * </p> * <p> * Adding the optional trigger values: <code>["img1", "tl", "bl", ["beforeShow", "windowResize"], [0,5]]</code>, * will re-align the overlay position, whenever the "beforeShow" or "windowResize" events are fired. * </p> * * @config context * @type Array * @default null */ cfg.addProperty(DEFAULT_CONFIG.CONTEXT.key, { handler: this.configContext, suppressEvent: DEFAULT_CONFIG.CONTEXT.suppressEvent, supercedes: DEFAULT_CONFIG.CONTEXT.supercedes }); /** * Determines whether or not the Overlay should be anchored * to the center of the viewport. * * <p>This property can be set to:</p> * * <dl> * <dt>true</dt> * <dd> * To enable fixed center positioning * <p> * When enabled, the overlay will * be positioned in the center of viewport when initially displayed, and * will remain in the center of the viewport whenever the window is * scrolled or resized. * </p> * <p> * If the overlay is too big for the viewport, * it's top left corner will be aligned with the top left corner of the viewport. * </p> * </dd> * <dt>false</dt> * <dd> * To disable fixed center positioning. * <p>In this case the overlay can still be * centered as a one-off operation, by invoking the <code>center()</code> method, * however it will not remain centered when the window is scrolled/resized. * </dd> * <dt>"contained"<dt> * <dd>To enable fixed center positioning, as with the <code>true</code> option. * <p>However, unlike setting the property to <code>true</code>, * when the property is set to <code>"contained"</code>, if the overlay is * too big for the viewport, it will not get automatically centered when the * user scrolls or resizes the window (until the window is large enough to contain the * overlay). This is useful in cases where the Overlay has both header and footer * UI controls which the user may need to access. * </p> * </dd> * </dl> * * @config fixedcenter * @type Boolean | String * @default false */ cfg.addProperty(DEFAULT_CONFIG.FIXED_CENTER.key, { handler: this.configFixedCenter, value: DEFAULT_CONFIG.FIXED_CENTER.value, validator: DEFAULT_CONFIG.FIXED_CENTER.validator, supercedes: DEFAULT_CONFIG.FIXED_CENTER.supercedes }); /** * CSS width of the Overlay. * @config width * @type String * @default null */ cfg.addProperty(DEFAULT_CONFIG.WIDTH.key, { handler: this.configWidth, suppressEvent: DEFAULT_CONFIG.WIDTH.suppressEvent, supercedes: DEFAULT_CONFIG.WIDTH.supercedes }); /** * CSS height of the Overlay. * @config height * @type String * @default null */ cfg.addProperty(DEFAULT_CONFIG.HEIGHT.key, { handler: this.configHeight, suppressEvent: DEFAULT_CONFIG.HEIGHT.suppressEvent, supercedes: DEFAULT_CONFIG.HEIGHT.supercedes }); /** * Standard module element which should auto fill out the height of the Overlay if the height config property is set. * Supported values are "header", "body", "footer". * * @config autofillheight * @type String * @default null */ cfg.addProperty(DEFAULT_CONFIG.AUTO_FILL_HEIGHT.key, { handler: this.configAutoFillHeight, value : DEFAULT_CONFIG.AUTO_FILL_HEIGHT.value, validator : this._validateAutoFill, supercedes: DEFAULT_CONFIG.AUTO_FILL_HEIGHT.supercedes }); /** * CSS z-index of the Overlay. * @config zIndex * @type Number * @default null */ cfg.addProperty(DEFAULT_CONFIG.ZINDEX.key, { handler: this.configzIndex, value: DEFAULT_CONFIG.ZINDEX.value }); /** * True if the Overlay should be prevented from being positioned * out of the viewport. * @config constraintoviewport * @type Boolean * @default false */ cfg.addProperty(DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.key, { handler: this.configConstrainToViewport, value: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.value, validator: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.validator, supercedes: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.supercedes }); /** * @config iframe * @description Boolean indicating whether or not the Overlay should * have an IFRAME shim; used to prevent SELECT elements from * poking through an Overlay instance in IE6. When set to "true", * the iframe shim is created when the Overlay instance is intially * made visible. * @type Boolean * @default true for IE6 and below, false for all other browsers. */ cfg.addProperty(DEFAULT_CONFIG.IFRAME.key, { handler: this.configIframe, value: DEFAULT_CONFIG.IFRAME.value, validator: DEFAULT_CONFIG.IFRAME.validator, supercedes: DEFAULT_CONFIG.IFRAME.supercedes }); /** * @config preventcontextoverlap * @description Boolean indicating whether or not the Overlay should overlap its * context element (defined using the "context" configuration property) when the * "constraintoviewport" configuration property is set to "true". * @type Boolean * @default false */ cfg.addProperty(DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.key, { value: DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.value, validator: DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.validator, supercedes: DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.supercedes }); }, /** * Moves the Overlay to the specified position. This function is * identical to calling this.cfg.setProperty("xy", [x,y]); * @method moveTo * @param {Number} x The Overlay's new x position * @param {Number} y The Overlay's new y position */ moveTo: function (x, y) { this.cfg.setProperty("xy", [x, y]); }, /** * Adds a CSS class ("hide-scrollbars") and removes a CSS class * ("show-scrollbars") to the Overlay to fix a bug in Gecko on Mac OS X * (https://bugzilla.mozilla.org/show_bug.cgi?id=187435) * @method hideMacGeckoScrollbars */ hideMacGeckoScrollbars: function () { Dom.replaceClass(this.element, "show-scrollbars", "hide-scrollbars"); }, /** * Adds a CSS class ("show-scrollbars") and removes a CSS class * ("hide-scrollbars") to the Overlay to fix a bug in Gecko on Mac OS X * (https://bugzilla.mozilla.org/show_bug.cgi?id=187435) * @method showMacGeckoScrollbars */ showMacGeckoScrollbars: function () { Dom.replaceClass(this.element, "hide-scrollbars", "show-scrollbars"); }, /** * Internal implementation to set the visibility of the overlay in the DOM. * * @method _setDomVisibility * @param {boolean} visible Whether to show or hide the Overlay's outer element * @protected */ _setDomVisibility : function(show) { Dom.setStyle(this.element, "visibility", (show) ? "visible" : "hidden"); var hiddenClass = Overlay.CSS_HIDDEN; if (show) { Dom.removeClass(this.element, hiddenClass); } else { Dom.addClass(this.element, hiddenClass); } }, // BEGIN BUILT-IN PROPERTY EVENT HANDLERS // /** * The default event handler fired when the "visible" property is * changed. This method is responsible for firing showEvent * and hideEvent. * @method configVisible * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configVisible: function (type, args, obj) { var visible = args[0], currentVis = Dom.getStyle(this.element, "visibility"), effects = this._cachedEffects || this._createEffects(this.cfg.getProperty("effect")), isMacGecko = (this.platform == "mac" && UA.gecko), alreadySubscribed = Config.alreadySubscribed, ei, e, j, k, h, nEffectInstances; if (currentVis == "inherit") { e = this.element.parentNode; while (e.nodeType != 9 && e.nodeType != 11) { currentVis = Dom.getStyle(e, "visibility"); if (currentVis != "inherit") { break; } e = e.parentNode; } if (currentVis == "inherit") { currentVis = "visible"; } } if (visible) { // Show if (isMacGecko) { this.showMacGeckoScrollbars(); } if (effects) { // Animate in if (visible) { // Animate in if not showing // Fading out is a bit of a hack, but didn't want to risk doing // something broader (e.g a generic this._animatingOut) for 2.9.0 if (currentVis != "visible" || currentVis === "" || this._fadingOut) { if (this.beforeShowEvent.fire()) { nEffectInstances = effects.length; for (j = 0; j < nEffectInstances; j++) { ei = effects[j]; if (j === 0 && !alreadySubscribed(ei.animateInCompleteEvent, this.showEvent.fire, this.showEvent)) { ei.animateInCompleteEvent.subscribe(this.showEvent.fire, this.showEvent, true); } ei.animateIn(); } } } } } else { // Show if (currentVis != "visible" || currentVis === "") { if (this.beforeShowEvent.fire()) { this._setDomVisibility(true); this.cfg.refireEvent("iframe"); this.showEvent.fire(); } } else { this._setDomVisibility(true); } } } else { // Hide if (isMacGecko) { this.hideMacGeckoScrollbars(); } if (effects) { // Animate out if showing if (currentVis == "visible" || this._fadingIn) { if (this.beforeHideEvent.fire()) { nEffectInstances = effects.length; for (k = 0; k < nEffectInstances; k++) { h = effects[k]; if (k === 0 && !alreadySubscribed(h.animateOutCompleteEvent, this.hideEvent.fire, this.hideEvent)) { h.animateOutCompleteEvent.subscribe(this.hideEvent.fire, this.hideEvent, true); } h.animateOut(); } } } else if (currentVis === "") { this._setDomVisibility(false); } } else { // Simple hide if (currentVis == "visible" || currentVis === "") { if (this.beforeHideEvent.fire()) { this._setDomVisibility(false); this.hideEvent.fire(); } } else { this._setDomVisibility(false); } } } }, /** * Fixed center event handler used for centering on scroll/resize, but only if * the overlay is visible and, if "fixedcenter" is set to "contained", only if * the overlay fits within the viewport. * * @method doCenterOnDOMEvent */ doCenterOnDOMEvent: function () { var cfg = this.cfg, fc = cfg.getProperty("fixedcenter"); if (cfg.getProperty("visible")) { if (fc && (fc !== _CONTAINED || this.fitsInViewport())) { this.center(); } } }, /** * Determines if the Overlay (including the offset value defined by Overlay.VIEWPORT_OFFSET) * will fit entirely inside the viewport, in both dimensions - width and height. * * @method fitsInViewport * @return boolean true if the Overlay will fit, false if not */ fitsInViewport : function() { var nViewportOffset = Overlay.VIEWPORT_OFFSET, element = this.element, elementWidth = element.offsetWidth, elementHeight = element.offsetHeight, viewportWidth = Dom.getViewportWidth(), viewportHeight = Dom.getViewportHeight(); return ((elementWidth + nViewportOffset < viewportWidth) && (elementHeight + nViewportOffset < viewportHeight)); }, /** * The default event handler fired when the "fixedcenter" property * is changed. * @method configFixedCenter * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configFixedCenter: function (type, args, obj) { var val = args[0], alreadySubscribed = Config.alreadySubscribed, windowResizeEvent = Overlay.windowResizeEvent, windowScrollEvent = Overlay.windowScrollEvent; if (val) { this.center(); if (!alreadySubscribed(this.beforeShowEvent, this.center)) { this.beforeShowEvent.subscribe(this.center); } if (!alreadySubscribed(windowResizeEvent, this.doCenterOnDOMEvent, this)) { windowResizeEvent.subscribe(this.doCenterOnDOMEvent, this, true); } if (!alreadySubscribed(windowScrollEvent, this.doCenterOnDOMEvent, this)) { windowScrollEvent.subscribe(this.doCenterOnDOMEvent, this, true); } } else { this.beforeShowEvent.unsubscribe(this.center); windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent, this); windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent, this); } }, /** * The default event handler fired when the "height" property is changed. * @method configHeight * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configHeight: function (type, args, obj) { var height = args[0], el = this.element; Dom.setStyle(el, "height", height); this.cfg.refireEvent("iframe"); }, /** * The default event handler fired when the "autofillheight" property is changed. * @method configAutoFillHeight * * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configAutoFillHeight: function (type, args, obj) { var fillEl = args[0], cfg = this.cfg, autoFillHeight = "autofillheight", height = "height", currEl = cfg.getProperty(autoFillHeight), autoFill = this._autoFillOnHeightChange; cfg.unsubscribeFromConfigEvent(height, autoFill); Module.textResizeEvent.unsubscribe(autoFill); this.changeContentEvent.unsubscribe(autoFill); if (currEl && fillEl !== currEl && this[currEl]) { Dom.setStyle(this[currEl], height, ""); } if (fillEl) { fillEl = Lang.trim(fillEl.toLowerCase()); cfg.subscribeToConfigEvent(height, autoFill, this[fillEl], this); Module.textResizeEvent.subscribe(autoFill, this[fillEl], this); this.changeContentEvent.subscribe(autoFill, this[fillEl], this); cfg.setProperty(autoFillHeight, fillEl, true); } }, /** * The default event handler fired when the "width" property is changed. * @method configWidth * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configWidth: function (type, args, obj) { var width = args[0], el = this.element; Dom.setStyle(el, "width", width); this.cfg.refireEvent("iframe"); }, /** * The default event handler fired when the "zIndex" property is changed. * @method configzIndex * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configzIndex: function (type, args, obj) { var zIndex = args[0], el = this.element; if (! zIndex) { zIndex = Dom.getStyle(el, "zIndex"); if (! zIndex || isNaN(zIndex)) { zIndex = 0; } } if (this.iframe || this.cfg.getProperty("iframe") === true) { if (zIndex <= 0) { zIndex = 1; } } Dom.setStyle(el, "zIndex", zIndex); this.cfg.setProperty("zIndex", zIndex, true); if (this.iframe) { this.stackIframe(); } }, /** * The default event handler fired when the "xy" property is changed. * @method configXY * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configXY: function (type, args, obj) { var pos = args[0], x = pos[0], y = pos[1]; this.cfg.setProperty("x", x); this.cfg.setProperty("y", y); this.beforeMoveEvent.fire([x, y]); x = this.cfg.getProperty("x"); y = this.cfg.getProperty("y"); YAHOO.log(("xy: " + [x, y]), "iframe"); this.cfg.refireEvent("iframe"); this.moveEvent.fire([x, y]); }, /** * The default event handler fired when the "x" property is changed. * @method configX * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configX: function (type, args, obj) { var x = args[0], y = this.cfg.getProperty("y"); this.cfg.setProperty("x", x, true); this.cfg.setProperty("y", y, true); this.beforeMoveEvent.fire([x, y]); x = this.cfg.getProperty("x"); y = this.cfg.getProperty("y"); Dom.setX(this.element, x, true); this.cfg.setProperty("xy", [x, y], true); this.cfg.refireEvent("iframe"); this.moveEvent.fire([x, y]); }, /** * The default event handler fired when the "y" property is changed. * @method configY * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configY: function (type, args, obj) { var x = this.cfg.getProperty("x"), y = args[0]; this.cfg.setProperty("x", x, true); this.cfg.setProperty("y", y, true); this.beforeMoveEvent.fire([x, y]); x = this.cfg.getProperty("x"); y = this.cfg.getProperty("y"); Dom.setY(this.element, y, true); this.cfg.setProperty("xy", [x, y], true); this.cfg.refireEvent("iframe"); this.moveEvent.fire([x, y]); }, /** * Shows the iframe shim, if it has been enabled. * @method showIframe */ showIframe: function () { var oIFrame = this.iframe, oParentNode; if (oIFrame) { oParentNode = this.element.parentNode; if (oParentNode != oIFrame.parentNode) { this._addToParent(oParentNode, oIFrame); } oIFrame.style.display = "block"; } }, /** * Hides the iframe shim, if it has been enabled. * @method hideIframe */ hideIframe: function () { if (this.iframe) { this.iframe.style.display = "none"; } }, /** * Syncronizes the size and position of iframe shim to that of its * corresponding Overlay instance. * @method syncIframe */ syncIframe: function () { var oIFrame = this.iframe, oElement = this.element, nOffset = Overlay.IFRAME_OFFSET, nDimensionOffset = (nOffset * 2), aXY; if (oIFrame) { // Size <iframe> oIFrame.style.width = (oElement.offsetWidth + nDimensionOffset + "px"); oIFrame.style.height = (oElement.offsetHeight + nDimensionOffset + "px"); // Position <iframe> aXY = this.cfg.getProperty("xy"); if (!Lang.isArray(aXY) || (isNaN(aXY[0]) || isNaN(aXY[1]))) { this.syncPosition(); aXY = this.cfg.getProperty("xy"); } Dom.setXY(oIFrame, [(aXY[0] - nOffset), (aXY[1] - nOffset)]); } }, /** * Sets the zindex of the iframe shim, if it exists, based on the zindex of * the Overlay element. The zindex of the iframe is set to be one less * than the Overlay element's zindex. * * <p>NOTE: This method will not bump up the zindex of the Overlay element * to ensure that the iframe shim has a non-negative zindex. * If you require the iframe zindex to be 0 or higher, the zindex of * the Overlay element should be set to a value greater than 0, before * this method is called. * </p> * @method stackIframe */ stackIframe: function () { if (this.iframe) { var overlayZ = Dom.getStyle(this.element, "zIndex"); if (!YAHOO.lang.isUndefined(overlayZ) && !isNaN(overlayZ)) { Dom.setStyle(this.iframe, "zIndex", (overlayZ - 1)); } } }, /** * The default event handler fired when the "iframe" property is changed. * @method configIframe * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configIframe: function (type, args, obj) { var bIFrame = args[0]; function createIFrame() { var oIFrame = this.iframe, oElement = this.element, oParent; if (!oIFrame) { if (!m_oIFrameTemplate) { m_oIFrameTemplate = document.createElement("iframe"); if (this.isSecure) { m_oIFrameTemplate.src = Overlay.IFRAME_SRC; } /* Set the opacity of the <iframe> to 0 so that it doesn't modify the opacity of any transparent elements that may be on top of it (like a shadow). */ if (UA.ie) { m_oIFrameTemplate.style.filter = "alpha(opacity=0)"; /* Need to set the "frameBorder" property to 0 supress the default <iframe> border in IE. Setting the CSS "border" property alone doesn't supress it. */ m_oIFrameTemplate.frameBorder = 0; } else { m_oIFrameTemplate.style.opacity = "0"; } m_oIFrameTemplate.style.position = "absolute"; m_oIFrameTemplate.style.border = "none"; m_oIFrameTemplate.style.margin = "0"; m_oIFrameTemplate.style.padding = "0"; m_oIFrameTemplate.style.display = "none"; m_oIFrameTemplate.tabIndex = -1; m_oIFrameTemplate.className = Overlay.CSS_IFRAME; } oIFrame = m_oIFrameTemplate.cloneNode(false); oIFrame.id = this.id + "_f"; oParent = oElement.parentNode; var parentNode = oParent || document.body; this._addToParent(parentNode, oIFrame); this.iframe = oIFrame; } /* Show the <iframe> before positioning it since the "setXY" method of DOM requires the element be in the document and visible. */ this.showIframe(); /* Syncronize the size and position of the <iframe> to that of the Overlay. */ this.syncIframe(); this.stackIframe(); // Add event listeners to update the <iframe> when necessary if (!this._hasIframeEventListeners) { this.showEvent.subscribe(this.showIframe); this.hideEvent.subscribe(this.hideIframe); this.changeContentEvent.subscribe(this.syncIframe); this._hasIframeEventListeners = true; } } function onBeforeShow() { createIFrame.call(this); this.beforeShowEvent.unsubscribe(onBeforeShow); this._iframeDeferred = false; } if (bIFrame) { // <iframe> shim is enabled if (this.cfg.getProperty("visible")) { createIFrame.call(this); } else { if (!this._iframeDeferred) { this.beforeShowEvent.subscribe(onBeforeShow); this._iframeDeferred = true; } } } else { // <iframe> shim is disabled this.hideIframe(); if (this._hasIframeEventListeners) { this.showEvent.unsubscribe(this.showIframe); this.hideEvent.unsubscribe(this.hideIframe); this.changeContentEvent.unsubscribe(this.syncIframe); this._hasIframeEventListeners = false; } } }, /** * Set's the container's XY value from DOM if not already set. * * Differs from syncPosition, in that the XY value is only sync'd with DOM if * not already set. The method also refire's the XY config property event, so any * beforeMove, Move event listeners are invoked. * * @method _primeXYFromDOM * @protected */ _primeXYFromDOM : function() { if (YAHOO.lang.isUndefined(this.cfg.getProperty("xy"))) { // Set CFG XY based on DOM XY this.syncPosition(); // Account for XY being set silently in syncPosition (no moveTo fired/called) this.cfg.refireEvent("xy"); this.beforeShowEvent.unsubscribe(this._primeXYFromDOM); } }, /** * The default event handler fired when the "constraintoviewport" * property is changed. * @method configConstrainToViewport * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for * the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configConstrainToViewport: function (type, args, obj) { var val = args[0]; if (val) { if (! Config.alreadySubscribed(this.beforeMoveEvent, this.enforceConstraints, this)) { this.beforeMoveEvent.subscribe(this.enforceConstraints, this, true); } if (! Config.alreadySubscribed(this.beforeShowEvent, this._primeXYFromDOM)) { this.beforeShowEvent.subscribe(this._primeXYFromDOM); } } else { this.beforeShowEvent.unsubscribe(this._primeXYFromDOM); this.beforeMoveEvent.unsubscribe(this.enforceConstraints, this); } }, /** * The default event handler fired when the "context" property * is changed. * * @method configContext * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configContext: function (type, args, obj) { var contextArgs = args[0], contextEl, elementMagnetCorner, contextMagnetCorner, triggers, offset, defTriggers = this.CONTEXT_TRIGGERS; if (contextArgs) { contextEl = contextArgs[0]; elementMagnetCorner = contextArgs[1]; contextMagnetCorner = contextArgs[2]; triggers = contextArgs[3]; offset = contextArgs[4]; if (defTriggers && defTriggers.length > 0) { triggers = (triggers || []).concat(defTriggers); } if (contextEl) { if (typeof contextEl == "string") { this.cfg.setProperty("context", [ document.getElementById(contextEl), elementMagnetCorner, contextMagnetCorner, triggers, offset], true); } if (elementMagnetCorner && contextMagnetCorner) { this.align(elementMagnetCorner, contextMagnetCorner, offset); } if (this._contextTriggers) { // Unsubscribe Old Set this._processTriggers(this._contextTriggers, _UNSUBSCRIBE, this._alignOnTrigger); } if (triggers) { // Subscribe New Set this._processTriggers(triggers, _SUBSCRIBE, this._alignOnTrigger); this._contextTriggers = triggers; } } } }, /** * Custom Event handler for context alignment triggers. Invokes the align method * * @method _alignOnTrigger * @protected * * @param {String} type The event type (not used by the default implementation) * @param {Any[]} args The array of arguments for the trigger event (not used by the default implementation) */ _alignOnTrigger: function(type, args) { this.align(); }, /** * Helper method to locate the custom event instance for the event name string * passed in. As a convenience measure, any custom events passed in are returned. * * @method _findTriggerCE * @private * * @param {String|CustomEvent} t Either a CustomEvent, or event type (e.g. "windowScroll") for which a * custom event instance needs to be looked up from the Overlay._TRIGGER_MAP. */ _findTriggerCE : function(t) { var tce = null; if (t instanceof CustomEvent) { tce = t; } else if (Overlay._TRIGGER_MAP[t]) { tce = Overlay._TRIGGER_MAP[t]; } return tce; }, /** * Utility method that subscribes or unsubscribes the given * function from the list of trigger events provided. * * @method _processTriggers * @protected * * @param {Array[String|CustomEvent]} triggers An array of either CustomEvents, event type strings * (e.g. "beforeShow", "windowScroll") to/from which the provided function should be * subscribed/unsubscribed respectively. * * @param {String} mode Either "subscribe" or "unsubscribe", specifying whether or not * we are subscribing or unsubscribing trigger listeners * * @param {Function} fn The function to be subscribed/unsubscribed to/from the trigger event. * Context is always set to the overlay instance, and no additional object argument * get passed to the subscribed function. */ _processTriggers : function(triggers, mode, fn) { var t, tce; for (var i = 0, l = triggers.length; i < l; ++i) { t = triggers[i]; tce = this._findTriggerCE(t); if (tce) { tce[mode](fn, this, true); } else { this[mode](t, fn); } } }, // END BUILT-IN PROPERTY EVENT HANDLERS // /** * Aligns the Overlay to its context element using the specified corner * points (represented by the constants TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, * and BOTTOM_RIGHT. * @method align * @param {String} elementAlign The String representing the corner of * the Overlay that should be aligned to the context element * @param {String} contextAlign The corner of the context element * that the elementAlign corner should stick to. * @param {Number[]} xyOffset Optional. A 2 element array specifying the x and y pixel offsets which should be applied * after aligning the element and context corners. For example, passing in [5, -10] for this value, would offset the * Overlay by 5 pixels along the X axis (horizontally) and -10 pixels along the Y axis (vertically) after aligning the specified corners. */ align: function (elementAlign, contextAlign, xyOffset) { var contextArgs = this.cfg.getProperty("context"), me = this, context, element, contextRegion; function doAlign(v, h) { var alignX = null, alignY = null; switch (elementAlign) { case Overlay.TOP_LEFT: alignX = h; alignY = v; break; case Overlay.TOP_RIGHT: alignX = h - element.offsetWidth; alignY = v; break; case Overlay.BOTTOM_LEFT: alignX = h; alignY = v - element.offsetHeight; break; case Overlay.BOTTOM_RIGHT: alignX = h - element.offsetWidth; alignY = v - element.offsetHeight; break; } if (alignX !== null && alignY !== null) { if (xyOffset) { alignX += xyOffset[0]; alignY += xyOffset[1]; } me.moveTo(alignX, alignY); } } if (contextArgs) { context = contextArgs[0]; element = this.element; me = this; if (! elementAlign) { elementAlign = contextArgs[1]; } if (! contextAlign) { contextAlign = contextArgs[2]; } if (!xyOffset && contextArgs[4]) { xyOffset = contextArgs[4]; } if (element && context) { contextRegion = Dom.getRegion(context); switch (contextAlign) { case Overlay.TOP_LEFT: doAlign(contextRegion.top, contextRegion.left); break; case Overlay.TOP_RIGHT: doAlign(contextRegion.top, contextRegion.right); break; case Overlay.BOTTOM_LEFT: doAlign(contextRegion.bottom, contextRegion.left); break; case Overlay.BOTTOM_RIGHT: doAlign(contextRegion.bottom, contextRegion.right); break; } } } }, /** * The default event handler executed when the moveEvent is fired, if the * "constraintoviewport" is set to true. * @method enforceConstraints * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ enforceConstraints: function (type, args, obj) { var pos = args[0]; var cXY = this.getConstrainedXY(pos[0], pos[1]); this.cfg.setProperty("x", cXY[0], true); this.cfg.setProperty("y", cXY[1], true); this.cfg.setProperty("xy", cXY, true); }, /** * Shared implementation method for getConstrainedX and getConstrainedY. * * <p> * Given a coordinate value, returns the calculated coordinate required to * position the Overlay if it is to be constrained to the viewport, based on the * current element size, viewport dimensions, scroll values and preventoverlap * settings * </p> * * @method _getConstrainedPos * @protected * @param {String} pos The coordinate which needs to be constrained, either "x" or "y" * @param {Number} The coordinate value which needs to be constrained * @return {Number} The constrained coordinate value */ _getConstrainedPos: function(pos, val) { var overlayEl = this.element, buffer = Overlay.VIEWPORT_OFFSET, x = (pos == "x"), overlaySize = (x) ? overlayEl.offsetWidth : overlayEl.offsetHeight, viewportSize = (x) ? Dom.getViewportWidth() : Dom.getViewportHeight(), docScroll = (x) ? Dom.getDocumentScrollLeft() : Dom.getDocumentScrollTop(), overlapPositions = (x) ? Overlay.PREVENT_OVERLAP_X : Overlay.PREVENT_OVERLAP_Y, context = this.cfg.getProperty("context"), bOverlayFitsInViewport = (overlaySize + buffer < viewportSize), bPreventContextOverlap = this.cfg.getProperty("preventcontextoverlap") && context && overlapPositions[(context[1] + context[2])], minConstraint = docScroll + buffer, maxConstraint = docScroll + viewportSize - overlaySize - buffer, constrainedVal = val; if (val < minConstraint || val > maxConstraint) { if (bPreventContextOverlap) { constrainedVal = this._preventOverlap(pos, context[0], overlaySize, viewportSize, docScroll); } else { if (bOverlayFitsInViewport) { if (val < minConstraint) { constrainedVal = minConstraint; } else if (val > maxConstraint) { constrainedVal = maxConstraint; } } else { constrainedVal = minConstraint; } } } return constrainedVal; }, /** * Helper method, used to position the Overlap to prevent overlap with the * context element (used when preventcontextoverlap is enabled) * * @method _preventOverlap * @protected * @param {String} pos The coordinate to prevent overlap for, either "x" or "y". * @param {HTMLElement} contextEl The context element * @param {Number} overlaySize The related overlay dimension value (for "x", the width, for "y", the height) * @param {Number} viewportSize The related viewport dimension value (for "x", the width, for "y", the height) * @param {Object} docScroll The related document scroll value (for "x", the scrollLeft, for "y", the scrollTop) * * @return {Number} The new coordinate value which was set to prevent overlap */ _preventOverlap : function(pos, contextEl, overlaySize, viewportSize, docScroll) { var x = (pos == "x"), buffer = Overlay.VIEWPORT_OFFSET, overlay = this, contextElPos = ((x) ? Dom.getX(contextEl) : Dom.getY(contextEl)) - docScroll, contextElSize = (x) ? contextEl.offsetWidth : contextEl.offsetHeight, minRegionSize = contextElPos - buffer, maxRegionSize = (viewportSize - (contextElPos + contextElSize)) - buffer, bFlipped = false, flip = function () { var flippedVal; if ((overlay.cfg.getProperty(pos) - docScroll) > contextElPos) { flippedVal = (contextElPos - overlaySize); } else { flippedVal = (contextElPos + contextElSize); } overlay.cfg.setProperty(pos, (flippedVal + docScroll), true); return flippedVal; }, setPosition = function () { var displayRegionSize = ((overlay.cfg.getProperty(pos) - docScroll) > contextElPos) ? maxRegionSize : minRegionSize, position; if (overlaySize > displayRegionSize) { if (bFlipped) { /* All possible positions and values have been tried, but none were successful, so fall back to the original size and position. */ flip(); } else { flip(); bFlipped = true; position = setPosition(); } } return position; }; setPosition(); return this.cfg.getProperty(pos); }, /** * Given x coordinate value, returns the calculated x coordinate required to * position the Overlay if it is to be constrained to the viewport, based on the * current element size, viewport dimensions and scroll values. * * @param {Number} x The X coordinate value to be constrained * @return {Number} The constrained x coordinate */ getConstrainedX: function (x) { return this._getConstrainedPos("x", x); }, /** * Given y coordinate value, returns the calculated y coordinate required to * position the Overlay if it is to be constrained to the viewport, based on the * current element size, viewport dimensions and scroll values. * * @param {Number} y The Y coordinate value to be constrained * @return {Number} The constrained y coordinate */ getConstrainedY : function (y) { return this._getConstrainedPos("y", y); }, /** * Given x, y coordinate values, returns the calculated coordinates required to * position the Overlay if it is to be constrained to the viewport, based on the * current element size, viewport dimensions and scroll values. * * @param {Number} x The X coordinate value to be constrained * @param {Number} y The Y coordinate value to be constrained * @return {Array} The constrained x and y coordinates at index 0 and 1 respectively; */ getConstrainedXY: function(x, y) { return [this.getConstrainedX(x), this.getConstrainedY(y)]; }, /** * Centers the container in the viewport. * @method center */ center: function () { var nViewportOffset = Overlay.VIEWPORT_OFFSET, elementWidth = this.element.offsetWidth, elementHeight = this.element.offsetHeight, viewPortWidth = Dom.getViewportWidth(), viewPortHeight = Dom.getViewportHeight(), x, y; if (elementWidth < viewPortWidth) { x = (viewPortWidth / 2) - (elementWidth / 2) + Dom.getDocumentScrollLeft(); } else { x = nViewportOffset + Dom.getDocumentScrollLeft(); } if (elementHeight < viewPortHeight) { y = (viewPortHeight / 2) - (elementHeight / 2) + Dom.getDocumentScrollTop(); } else { y = nViewportOffset + Dom.getDocumentScrollTop(); } this.cfg.setProperty("xy", [parseInt(x, 10), parseInt(y, 10)]); this.cfg.refireEvent("iframe"); if (UA.webkit) { this.forceContainerRedraw(); } }, /** * Synchronizes the Panel's "xy", "x", and "y" properties with the * Panel's position in the DOM. This is primarily used to update * position information during drag & drop. * @method syncPosition */ syncPosition: function () { var pos = Dom.getXY(this.element); this.cfg.setProperty("x", pos[0], true); this.cfg.setProperty("y", pos[1], true); this.cfg.setProperty("xy", pos, true); }, /** * Event handler fired when the resize monitor element is resized. * @method onDomResize * @param {DOMEvent} e The resize DOM event * @param {Object} obj The scope object */ onDomResize: function (e, obj) { var me = this; Overlay.superclass.onDomResize.call(this, e, obj); setTimeout(function () { me.syncPosition(); me.cfg.refireEvent("iframe"); me.cfg.refireEvent("context"); }, 0); }, /** * Determines the content box height of the given element (height of the element, without padding or borders) in pixels. * * @method _getComputedHeight * @private * @param {HTMLElement} el The element for which the content height needs to be determined * @return {Number} The content box height of the given element, or null if it could not be determined. */ _getComputedHeight : (function() { if (document.defaultView && document.defaultView.getComputedStyle) { return function(el) { var height = null; if (el.ownerDocument && el.ownerDocument.defaultView) { var computed = el.ownerDocument.defaultView.getComputedStyle(el, ''); if (computed) { height = parseInt(computed.height, 10); } } return (Lang.isNumber(height)) ? height : null; }; } else { return function(el) { var height = null; if (el.style.pixelHeight) { height = el.style.pixelHeight; } return (Lang.isNumber(height)) ? height : null; }; } })(), /** * autofillheight validator. Verifies that the autofill value is either null * or one of the strings : "body", "header" or "footer". * * @method _validateAutoFillHeight * @protected * @param {String} val * @return true, if valid, false otherwise */ _validateAutoFillHeight : function(val) { return (!val) || (Lang.isString(val) && Overlay.STD_MOD_RE.test(val)); }, /** * The default custom event handler executed when the overlay's height is changed, * if the autofillheight property has been set. * * @method _autoFillOnHeightChange * @protected * @param {String} type The event type * @param {Array} args The array of arguments passed to event subscribers * @param {HTMLElement} el The header, body or footer element which is to be resized to fill * out the containers height */ _autoFillOnHeightChange : function(type, args, el) { var height = this.cfg.getProperty("height"); if ((height && height !== "auto") || (height === 0)) { this.fillHeight(el); } }, /** * Returns the sub-pixel height of the el, using getBoundingClientRect, if available, * otherwise returns the offsetHeight * @method _getPreciseHeight * @private * @param {HTMLElement} el * @return {Float} The sub-pixel height if supported by the browser, else the rounded height. */ _getPreciseHeight : function(el) { var height = el.offsetHeight; if (el.getBoundingClientRect) { var rect = el.getBoundingClientRect(); height = rect.bottom - rect.top; } return height; }, /** * <p> * Sets the height on the provided header, body or footer element to * fill out the height of the container. It determines the height of the * containers content box, based on it's configured height value, and * sets the height of the autofillheight element to fill out any * space remaining after the other standard module element heights * have been accounted for. * </p> * <p><strong>NOTE:</strong> This method is not designed to work if an explicit * height has not been set on the container, since for an "auto" height container, * the heights of the header/body/footer will drive the height of the container.</p> * * @method fillHeight * @param {HTMLElement} el The element which should be resized to fill out the height * of the container element. */ fillHeight : function(el) { if (el) { var container = this.innerElement || this.element, containerEls = [this.header, this.body, this.footer], containerEl, total = 0, filled = 0, remaining = 0, validEl = false; for (var i = 0, l = containerEls.length; i < l; i++) { containerEl = containerEls[i]; if (containerEl) { if (el !== containerEl) { filled += this._getPreciseHeight(containerEl); } else { validEl = true; } } } if (validEl) { if (UA.ie || UA.opera) { // Need to set height to 0, to allow height to be reduced Dom.setStyle(el, 'height', 0 + 'px'); } total = this._getComputedHeight(container); // Fallback, if we can't get computed value for content height if (total === null) { Dom.addClass(container, "yui-override-padding"); total = container.clientHeight; // Content, No Border, 0 Padding (set by yui-override-padding) Dom.removeClass(container, "yui-override-padding"); } remaining = Math.max(total - filled, 0); Dom.setStyle(el, "height", remaining + "px"); // Re-adjust height if required, to account for el padding and border if (el.offsetHeight != remaining) { remaining = Math.max(remaining - (el.offsetHeight - remaining), 0); } Dom.setStyle(el, "height", remaining + "px"); } } }, /** * Places the Overlay on top of all other instances of * YAHOO.widget.Overlay. * @method bringToTop */ bringToTop: function () { var aOverlays = [], oElement = this.element; function compareZIndexDesc(p_oOverlay1, p_oOverlay2) { var sZIndex1 = Dom.getStyle(p_oOverlay1, "zIndex"), sZIndex2 = Dom.getStyle(p_oOverlay2, "zIndex"), nZIndex1 = (!sZIndex1 || isNaN(sZIndex1)) ? 0 : parseInt(sZIndex1, 10), nZIndex2 = (!sZIndex2 || isNaN(sZIndex2)) ? 0 : parseInt(sZIndex2, 10); if (nZIndex1 > nZIndex2) { return -1; } else if (nZIndex1 < nZIndex2) { return 1; } else { return 0; } } function isOverlayElement(p_oElement) { var isOverlay = Dom.hasClass(p_oElement, Overlay.CSS_OVERLAY), Panel = YAHOO.widget.Panel; if (isOverlay && !Dom.isAncestor(oElement, p_oElement)) { if (Panel && Dom.hasClass(p_oElement, Panel.CSS_PANEL)) { aOverlays[aOverlays.length] = p_oElement.parentNode; } else { aOverlays[aOverlays.length] = p_oElement; } } } Dom.getElementsBy(isOverlayElement, "div", document.body); aOverlays.sort(compareZIndexDesc); var oTopOverlay = aOverlays[0], nTopZIndex; if (oTopOverlay) { nTopZIndex = Dom.getStyle(oTopOverlay, "zIndex"); if (!isNaN(nTopZIndex)) { var bRequiresBump = false; if (oTopOverlay != oElement) { bRequiresBump = true; } else if (aOverlays.length > 1) { var nNextZIndex = Dom.getStyle(aOverlays[1], "zIndex"); // Don't rely on DOM order to stack if 2 overlays are at the same zindex. if (!isNaN(nNextZIndex) && (nTopZIndex == nNextZIndex)) { bRequiresBump = true; } } if (bRequiresBump) { this.cfg.setProperty("zindex", (parseInt(nTopZIndex, 10) + 2)); } } } }, /** * Removes the Overlay element from the DOM and sets all child * elements to null. * @method destroy * @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners. * NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0. */ destroy: function (shallowPurge) { if (this.iframe) { this.iframe.parentNode.removeChild(this.iframe); } this.iframe = null; Overlay.windowResizeEvent.unsubscribe( this.doCenterOnDOMEvent, this); Overlay.windowScrollEvent.unsubscribe( this.doCenterOnDOMEvent, this); Module.textResizeEvent.unsubscribe(this._autoFillOnHeightChange); if (this._contextTriggers) { // Unsubscribe context triggers - to cover context triggers which listen for global // events such as windowResize and windowScroll. Easier just to unsubscribe all this._processTriggers(this._contextTriggers, _UNSUBSCRIBE, this._alignOnTrigger); } Overlay.superclass.destroy.call(this, shallowPurge); }, /** * Can be used to force the container to repaint/redraw it's contents. * <p> * By default applies and then removes a 1px bottom margin through the * application/removal of a "yui-force-redraw" class. * </p> * <p> * It is currently used by Overlay to force a repaint for webkit * browsers, when centering. * </p> * @method forceContainerRedraw */ forceContainerRedraw : function() { var c = this; Dom.addClass(c.element, "yui-force-redraw"); setTimeout(function() { Dom.removeClass(c.element, "yui-force-redraw"); }, 0); }, /** * Returns a String representation of the object. * @method toString * @return {String} The string representation of the Overlay. */ toString: function () { return "Overlay " + this.id; } }); }()); (function () { /** * OverlayManager is used for maintaining the focus status of * multiple Overlays. * @namespace YAHOO.widget * @namespace YAHOO.widget * @class OverlayManager * @constructor * @param {Array} overlays Optional. A collection of Overlays to register * with the manager. * @param {Object} userConfig The object literal representing the user * configuration of the OverlayManager */ YAHOO.widget.OverlayManager = function (userConfig) { this.init(userConfig); }; var Overlay = YAHOO.widget.Overlay, Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, Config = YAHOO.util.Config, CustomEvent = YAHOO.util.CustomEvent, OverlayManager = YAHOO.widget.OverlayManager; /** * The CSS class representing a focused Overlay * @property OverlayManager.CSS_FOCUSED * @static * @final * @type String */ OverlayManager.CSS_FOCUSED = "focused"; OverlayManager.prototype = { /** * The class's constructor function * @property contructor * @type Function */ constructor: OverlayManager, /** * The array of Overlays that are currently registered * @property overlays * @type YAHOO.widget.Overlay[] */ overlays: null, /** * Initializes the default configuration of the OverlayManager * @method initDefaultConfig */ initDefaultConfig: function () { /** * The collection of registered Overlays in use by * the OverlayManager * @config overlays * @type YAHOO.widget.Overlay[] * @default null */ this.cfg.addProperty("overlays", { suppressEvent: true } ); /** * The default DOM event that should be used to focus an Overlay * @config focusevent * @type String * @default "mousedown" */ this.cfg.addProperty("focusevent", { value: "mousedown" } ); }, /** * Initializes the OverlayManager * @method init * @param {Overlay[]} overlays Optional. A collection of Overlays to * register with the manager. * @param {Object} userConfig The object literal representing the user * configuration of the OverlayManager */ init: function (userConfig) { /** * The OverlayManager's Config object used for monitoring * configuration properties. * @property cfg * @type Config */ this.cfg = new Config(this); this.initDefaultConfig(); if (userConfig) { this.cfg.applyConfig(userConfig, true); } this.cfg.fireQueue(); /** * The currently activated Overlay * @property activeOverlay * @private * @type YAHOO.widget.Overlay */ var activeOverlay = null; /** * Returns the currently focused Overlay * @method getActive * @return {Overlay} The currently focused Overlay */ this.getActive = function () { return activeOverlay; }; /** * Focuses the specified Overlay * @method focus * @param {Overlay} overlay The Overlay to focus * @param {String} overlay The id of the Overlay to focus */ this.focus = function (overlay) { var o = this.find(overlay); if (o) { o.focus(); } }; /** * Removes the specified Overlay from the manager * @method remove * @param {Overlay} overlay The Overlay to remove * @param {String} overlay The id of the Overlay to remove */ this.remove = function (overlay) { var o = this.find(overlay), originalZ; if (o) { if (activeOverlay == o) { activeOverlay = null; } var bDestroyed = (o.element === null && o.cfg === null) ? true : false; if (!bDestroyed) { // Set it's zindex so that it's sorted to the end. originalZ = Dom.getStyle(o.element, "zIndex"); o.cfg.setProperty("zIndex", -1000, true); } this.overlays.sort(this.compareZIndexDesc); this.overlays = this.overlays.slice(0, (this.overlays.length - 1)); o.hideEvent.unsubscribe(o.blur); o.destroyEvent.unsubscribe(this._onOverlayDestroy, o); o.focusEvent.unsubscribe(this._onOverlayFocusHandler, o); o.blurEvent.unsubscribe(this._onOverlayBlurHandler, o); if (!bDestroyed) { Event.removeListener(o.element, this.cfg.getProperty("focusevent"), this._onOverlayElementFocus); o.cfg.setProperty("zIndex", originalZ, true); o.cfg.setProperty("manager", null); } /* _managed Flag for custom or existing. Don't want to remove existing */ if (o.focusEvent._managed) { o.focusEvent = null; } if (o.blurEvent._managed) { o.blurEvent = null; } if (o.focus._managed) { o.focus = null; } if (o.blur._managed) { o.blur = null; } } }; /** * Removes focus from all registered Overlays in the manager * @method blurAll */ this.blurAll = function () { var nOverlays = this.overlays.length, i; if (nOverlays > 0) { i = nOverlays - 1; do { this.overlays[i].blur(); } while(i--); } }; /** * Updates the state of the OverlayManager and overlay, as a result of the overlay * being blurred. * * @method _manageBlur * @param {Overlay} overlay The overlay instance which got blurred. * @protected */ this._manageBlur = function (overlay) { var changed = false; if (activeOverlay == overlay) { Dom.removeClass(activeOverlay.element, OverlayManager.CSS_FOCUSED); activeOverlay = null; changed = true; } return changed; }; /** * Updates the state of the OverlayManager and overlay, as a result of the overlay * receiving focus. * * @method _manageFocus * @param {Overlay} overlay The overlay instance which got focus. * @protected */ this._manageFocus = function(overlay) { var changed = false; if (activeOverlay != overlay) { if (activeOverlay) { activeOverlay.blur(); } activeOverlay = overlay; this.bringToTop(activeOverlay); Dom.addClass(activeOverlay.element, OverlayManager.CSS_FOCUSED); changed = true; } return changed; }; var overlays = this.cfg.getProperty("overlays"); if (! this.overlays) { this.overlays = []; } if (overlays) { this.register(overlays); this.overlays.sort(this.compareZIndexDesc); } }, /** * @method _onOverlayElementFocus * @description Event handler for the DOM event that is used to focus * the Overlay instance as specified by the "focusevent" * configuration property. * @private * @param {Event} p_oEvent Object representing the DOM event * object passed back by the event utility (Event). */ _onOverlayElementFocus: function (p_oEvent) { var oTarget = Event.getTarget(p_oEvent), oClose = this.close; if (oClose && (oTarget == oClose || Dom.isAncestor(oClose, oTarget))) { this.blur(); } else { this.focus(); } }, /** * @method _onOverlayDestroy * @description "destroy" event handler for the Overlay. * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. * @param {Overlay} p_oOverlay Object representing the overlay that * fired the event. */ _onOverlayDestroy: function (p_sType, p_aArgs, p_oOverlay) { this.remove(p_oOverlay); }, /** * @method _onOverlayFocusHandler * * @description focusEvent Handler, used to delegate to _manageFocus with the correct arguments. * * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. * @param {Overlay} p_oOverlay Object representing the overlay that * fired the event. */ _onOverlayFocusHandler: function(p_sType, p_aArgs, p_oOverlay) { this._manageFocus(p_oOverlay); }, /** * @method _onOverlayBlurHandler * @description blurEvent Handler, used to delegate to _manageBlur with the correct arguments. * * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. * @param {Overlay} p_oOverlay Object representing the overlay that * fired the event. */ _onOverlayBlurHandler: function(p_sType, p_aArgs, p_oOverlay) { this._manageBlur(p_oOverlay); }, /** * Subscribes to the Overlay based instance focusEvent, to allow the OverlayManager to * monitor focus state. * * If the instance already has a focusEvent (e.g. Menu), OverlayManager will subscribe * to the existing focusEvent, however if a focusEvent or focus method does not exist * on the instance, the _bindFocus method will add them, and the focus method will * update the OverlayManager's state directly. * * @method _bindFocus * @param {Overlay} overlay The overlay for which focus needs to be managed * @protected */ _bindFocus : function(overlay) { var mgr = this; if (!overlay.focusEvent) { overlay.focusEvent = overlay.createEvent("focus"); overlay.focusEvent.signature = CustomEvent.LIST; overlay.focusEvent._managed = true; } else { overlay.focusEvent.subscribe(mgr._onOverlayFocusHandler, overlay, mgr); } if (!overlay.focus) { Event.on(overlay.element, mgr.cfg.getProperty("focusevent"), mgr._onOverlayElementFocus, null, overlay); overlay.focus = function () { if (mgr._manageFocus(this)) { // For Panel/Dialog if (this.cfg.getProperty("visible") && this.focusFirst) { this.focusFirst(); } this.focusEvent.fire(); } }; overlay.focus._managed = true; } }, /** * Subscribes to the Overlay based instance's blurEvent to allow the OverlayManager to * monitor blur state. * * If the instance already has a blurEvent (e.g. Menu), OverlayManager will subscribe * to the existing blurEvent, however if a blurEvent or blur method does not exist * on the instance, the _bindBlur method will add them, and the blur method * update the OverlayManager's state directly. * * @method _bindBlur * @param {Overlay} overlay The overlay for which blur needs to be managed * @protected */ _bindBlur : function(overlay) { var mgr = this; if (!overlay.blurEvent) { overlay.blurEvent = overlay.createEvent("blur"); overlay.blurEvent.signature = CustomEvent.LIST; overlay.focusEvent._managed = true; } else { overlay.blurEvent.subscribe(mgr._onOverlayBlurHandler, overlay, mgr); } if (!overlay.blur) { overlay.blur = function () { if (mgr._manageBlur(this)) { this.blurEvent.fire(); } }; overlay.blur._managed = true; } overlay.hideEvent.subscribe(overlay.blur); }, /** * Subscribes to the Overlay based instance's destroyEvent, to allow the Overlay * to be removed for the OverlayManager when destroyed. * * @method _bindDestroy * @param {Overlay} overlay The overlay instance being managed * @protected */ _bindDestroy : function(overlay) { var mgr = this; overlay.destroyEvent.subscribe(mgr._onOverlayDestroy, overlay, mgr); }, /** * Ensures the zIndex configuration property on the managed overlay based instance * is set to the computed zIndex value from the DOM (with "auto" translating to 0). * * @method _syncZIndex * @param {Overlay} overlay The overlay instance being managed * @protected */ _syncZIndex : function(overlay) { var zIndex = Dom.getStyle(overlay.element, "zIndex"); if (!isNaN(zIndex)) { overlay.cfg.setProperty("zIndex", parseInt(zIndex, 10)); } else { overlay.cfg.setProperty("zIndex", 0); } }, /** * Registers an Overlay or an array of Overlays with the manager. Upon * registration, the Overlay receives functions for focus and blur, * along with CustomEvents for each. * * @method register * @param {Overlay} overlay An Overlay to register with the manager. * @param {Overlay[]} overlay An array of Overlays to register with * the manager. * @return {boolean} true if any Overlays are registered. */ register: function (overlay) { var registered = false, i, n; if (overlay instanceof Overlay) { overlay.cfg.addProperty("manager", { value: this } ); this._bindFocus(overlay); this._bindBlur(overlay); this._bindDestroy(overlay); this._syncZIndex(overlay); this.overlays.push(overlay); this.bringToTop(overlay); registered = true; } else if (overlay instanceof Array) { for (i = 0, n = overlay.length; i < n; i++) { registered = this.register(overlay[i]) || registered; } } return registered; }, /** * Places the specified Overlay instance on top of all other * Overlay instances. * @method bringToTop * @param {YAHOO.widget.Overlay} p_oOverlay Object representing an * Overlay instance. * @param {String} p_oOverlay String representing the id of an * Overlay instance. */ bringToTop: function (p_oOverlay) { var oOverlay = this.find(p_oOverlay), nTopZIndex, oTopOverlay, aOverlays; if (oOverlay) { aOverlays = this.overlays; aOverlays.sort(this.compareZIndexDesc); oTopOverlay = aOverlays[0]; if (oTopOverlay) { nTopZIndex = Dom.getStyle(oTopOverlay.element, "zIndex"); if (!isNaN(nTopZIndex)) { var bRequiresBump = false; if (oTopOverlay !== oOverlay) { bRequiresBump = true; } else if (aOverlays.length > 1) { var nNextZIndex = Dom.getStyle(aOverlays[1].element, "zIndex"); // Don't rely on DOM order to stack if 2 overlays are at the same zindex. if (!isNaN(nNextZIndex) && (nTopZIndex == nNextZIndex)) { bRequiresBump = true; } } if (bRequiresBump) { oOverlay.cfg.setProperty("zindex", (parseInt(nTopZIndex, 10) + 2)); } } aOverlays.sort(this.compareZIndexDesc); } } }, /** * Attempts to locate an Overlay by instance or ID. * @method find * @param {Overlay} overlay An Overlay to locate within the manager * @param {String} overlay An Overlay id to locate within the manager * @return {Overlay} The requested Overlay, if found, or null if it * cannot be located. */ find: function (overlay) { var isInstance = overlay instanceof Overlay, overlays = this.overlays, n = overlays.length, found = null, o, i; if (isInstance || typeof overlay == "string") { for (i = n-1; i >= 0; i--) { o = overlays[i]; if ((isInstance && (o === overlay)) || (o.id == overlay)) { found = o; break; } } } return found; }, /** * Used for sorting the manager's Overlays by z-index. * @method compareZIndexDesc * @private * @return {Number} 0, 1, or -1, depending on where the Overlay should * fall in the stacking order. */ compareZIndexDesc: function (o1, o2) { var zIndex1 = (o1.cfg) ? o1.cfg.getProperty("zIndex") : null, // Sort invalid (destroyed) zIndex2 = (o2.cfg) ? o2.cfg.getProperty("zIndex") : null; // objects at bottom. if (zIndex1 === null && zIndex2 === null) { return 0; } else if (zIndex1 === null){ return 1; } else if (zIndex2 === null) { return -1; } else if (zIndex1 > zIndex2) { return -1; } else if (zIndex1 < zIndex2) { return 1; } else { return 0; } }, /** * Shows all Overlays in the manager. * @method showAll */ showAll: function () { var overlays = this.overlays, n = overlays.length, i; for (i = n - 1; i >= 0; i--) { overlays[i].show(); } }, /** * Hides all Overlays in the manager. * @method hideAll */ hideAll: function () { var overlays = this.overlays, n = overlays.length, i; for (i = n - 1; i >= 0; i--) { overlays[i].hide(); } }, /** * Returns a string representation of the object. * @method toString * @return {String} The string representation of the OverlayManager */ toString: function () { return "OverlayManager"; } }; }()); (function () { /** * ContainerEffect encapsulates animation transitions that are executed when * an Overlay is shown or hidden. * @namespace YAHOO.widget * @class ContainerEffect * @constructor * @param {YAHOO.widget.Overlay} overlay The Overlay that the animation * should be associated with * @param {Object} attrIn The object literal representing the animation * arguments to be used for the animate-in transition. The arguments for * this literal are: attributes(object, see YAHOO.util.Anim for description), * duration(Number), and method(i.e. Easing.easeIn). * @param {Object} attrOut The object literal representing the animation * arguments to be used for the animate-out transition. The arguments for * this literal are: attributes(object, see YAHOO.util.Anim for description), * duration(Number), and method(i.e. Easing.easeIn). * @param {HTMLElement} targetElement Optional. The target element that * should be animated during the transition. Defaults to overlay.element. * @param {class} Optional. The animation class to instantiate. Defaults to * YAHOO.util.Anim. Other options include YAHOO.util.Motion. */ YAHOO.widget.ContainerEffect = function (overlay, attrIn, attrOut, targetElement, animClass) { if (!animClass) { animClass = YAHOO.util.Anim; } /** * The overlay to animate * @property overlay * @type YAHOO.widget.Overlay */ this.overlay = overlay; /** * The animation attributes to use when transitioning into view * @property attrIn * @type Object */ this.attrIn = attrIn; /** * The animation attributes to use when transitioning out of view * @property attrOut * @type Object */ this.attrOut = attrOut; /** * The target element to be animated * @property targetElement * @type HTMLElement */ this.targetElement = targetElement || overlay.element; /** * The animation class to use for animating the overlay * @property animClass * @type class */ this.animClass = animClass; }; var Dom = YAHOO.util.Dom, CustomEvent = YAHOO.util.CustomEvent, ContainerEffect = YAHOO.widget.ContainerEffect; /** * A pre-configured ContainerEffect instance that can be used for fading * an overlay in and out. * @method FADE * @static * @param {YAHOO.widget.Overlay} overlay The Overlay object to animate * @param {Number} dur The duration of the animation * @return {YAHOO.widget.ContainerEffect} The configured ContainerEffect object */ ContainerEffect.FADE = function (overlay, dur) { var Easing = YAHOO.util.Easing, fin = { attributes: {opacity:{from:0, to:1}}, duration: dur, method: Easing.easeIn }, fout = { attributes: {opacity:{to:0}}, duration: dur, method: Easing.easeOut }, fade = new ContainerEffect(overlay, fin, fout, overlay.element); fade.handleUnderlayStart = function() { var underlay = this.overlay.underlay; if (underlay && YAHOO.env.ua.ie) { var hasFilters = (underlay.filters && underlay.filters.length > 0); if(hasFilters) { Dom.addClass(overlay.element, "yui-effect-fade"); } } }; fade.handleUnderlayComplete = function() { var underlay = this.overlay.underlay; if (underlay && YAHOO.env.ua.ie) { Dom.removeClass(overlay.element, "yui-effect-fade"); } }; fade.handleStartAnimateIn = function (type, args, obj) { obj.overlay._fadingIn = true; Dom.addClass(obj.overlay.element, "hide-select"); if (!obj.overlay.underlay) { obj.overlay.cfg.refireEvent("underlay"); } obj.handleUnderlayStart(); obj.overlay._setDomVisibility(true); Dom.setStyle(obj.overlay.element, "opacity", 0); }; fade.handleCompleteAnimateIn = function (type,args,obj) { obj.overlay._fadingIn = false; Dom.removeClass(obj.overlay.element, "hide-select"); if (obj.overlay.element.style.filter) { obj.overlay.element.style.filter = null; } obj.handleUnderlayComplete(); obj.overlay.cfg.refireEvent("iframe"); obj.animateInCompleteEvent.fire(); }; fade.handleStartAnimateOut = function (type, args, obj) { obj.overlay._fadingOut = true; Dom.addClass(obj.overlay.element, "hide-select"); obj.handleUnderlayStart(); }; fade.handleCompleteAnimateOut = function (type, args, obj) { obj.overlay._fadingOut = false; Dom.removeClass(obj.overlay.element, "hide-select"); if (obj.overlay.element.style.filter) { obj.overlay.element.style.filter = null; } obj.overlay._setDomVisibility(false); Dom.setStyle(obj.overlay.element, "opacity", 1); obj.handleUnderlayComplete(); obj.overlay.cfg.refireEvent("iframe"); obj.animateOutCompleteEvent.fire(); }; fade.init(); return fade; }; /** * A pre-configured ContainerEffect instance that can be used for sliding an * overlay in and out. * @method SLIDE * @static * @param {YAHOO.widget.Overlay} overlay The Overlay object to animate * @param {Number} dur The duration of the animation * @return {YAHOO.widget.ContainerEffect} The configured ContainerEffect object */ ContainerEffect.SLIDE = function (overlay, dur) { var Easing = YAHOO.util.Easing, x = overlay.cfg.getProperty("x") || Dom.getX(overlay.element), y = overlay.cfg.getProperty("y") || Dom.getY(overlay.element), clientWidth = Dom.getClientWidth(), offsetWidth = overlay.element.offsetWidth, sin = { attributes: { points: { to: [x, y] } }, duration: dur, method: Easing.easeIn }, sout = { attributes: { points: { to: [(clientWidth + 25), y] } }, duration: dur, method: Easing.easeOut }, slide = new ContainerEffect(overlay, sin, sout, overlay.element, YAHOO.util.Motion); slide.handleStartAnimateIn = function (type,args,obj) { obj.overlay.element.style.left = ((-25) - offsetWidth) + "px"; obj.overlay.element.style.top = y + "px"; }; slide.handleTweenAnimateIn = function (type, args, obj) { var pos = Dom.getXY(obj.overlay.element), currentX = pos[0], currentY = pos[1]; if (Dom.getStyle(obj.overlay.element, "visibility") == "hidden" && currentX < x) { obj.overlay._setDomVisibility(true); } obj.overlay.cfg.setProperty("xy", [currentX, currentY], true); obj.overlay.cfg.refireEvent("iframe"); }; slide.handleCompleteAnimateIn = function (type, args, obj) { obj.overlay.cfg.setProperty("xy", [x, y], true); obj.startX = x; obj.startY = y; obj.overlay.cfg.refireEvent("iframe"); obj.animateInCompleteEvent.fire(); }; slide.handleStartAnimateOut = function (type, args, obj) { var vw = Dom.getViewportWidth(), pos = Dom.getXY(obj.overlay.element), yso = pos[1]; obj.animOut.attributes.points.to = [(vw + 25), yso]; }; slide.handleTweenAnimateOut = function (type, args, obj) { var pos = Dom.getXY(obj.overlay.element), xto = pos[0], yto = pos[1]; obj.overlay.cfg.setProperty("xy", [xto, yto], true); obj.overlay.cfg.refireEvent("iframe"); }; slide.handleCompleteAnimateOut = function (type, args, obj) { obj.overlay._setDomVisibility(false); obj.overlay.cfg.setProperty("xy", [x, y]); obj.animateOutCompleteEvent.fire(); }; slide.init(); return slide; }; ContainerEffect.prototype = { /** * Initializes the animation classes and events. * @method init */ init: function () { this.beforeAnimateInEvent = this.createEvent("beforeAnimateIn"); this.beforeAnimateInEvent.signature = CustomEvent.LIST; this.beforeAnimateOutEvent = this.createEvent("beforeAnimateOut"); this.beforeAnimateOutEvent.signature = CustomEvent.LIST; this.animateInCompleteEvent = this.createEvent("animateInComplete"); this.animateInCompleteEvent.signature = CustomEvent.LIST; this.animateOutCompleteEvent = this.createEvent("animateOutComplete"); this.animateOutCompleteEvent.signature = CustomEvent.LIST; this.animIn = new this.animClass( this.targetElement, this.attrIn.attributes, this.attrIn.duration, this.attrIn.method); this.animIn.onStart.subscribe(this.handleStartAnimateIn, this); this.animIn.onTween.subscribe(this.handleTweenAnimateIn, this); this.animIn.onComplete.subscribe(this.handleCompleteAnimateIn,this); this.animOut = new this.animClass( this.targetElement, this.attrOut.attributes, this.attrOut.duration, this.attrOut.method); this.animOut.onStart.subscribe(this.handleStartAnimateOut, this); this.animOut.onTween.subscribe(this.handleTweenAnimateOut, this); this.animOut.onComplete.subscribe(this.handleCompleteAnimateOut, this); }, /** * Triggers the in-animation. * @method animateIn */ animateIn: function () { this._stopAnims(this.lastFrameOnStop); this.beforeAnimateInEvent.fire(); this.animIn.animate(); }, /** * Triggers the out-animation. * @method animateOut */ animateOut: function () { this._stopAnims(this.lastFrameOnStop); this.beforeAnimateOutEvent.fire(); this.animOut.animate(); }, /** * Flag to define whether Anim should jump to the last frame, * when animateIn or animateOut is stopped. * * @property lastFrameOnStop * @default true * @type boolean */ lastFrameOnStop : true, /** * Stops both animIn and animOut instances, if in progress. * * @method _stopAnims * @param {boolean} finish If true, animation will jump to final frame. * @protected */ _stopAnims : function(finish) { if (this.animOut && this.animOut.isAnimated()) { this.animOut.stop(finish); } if (this.animIn && this.animIn.isAnimated()) { this.animIn.stop(finish); } }, /** * The default onStart handler for the in-animation. * @method handleStartAnimateIn * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleStartAnimateIn: function (type, args, obj) { }, /** * The default onTween handler for the in-animation. * @method handleTweenAnimateIn * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleTweenAnimateIn: function (type, args, obj) { }, /** * The default onComplete handler for the in-animation. * @method handleCompleteAnimateIn * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleCompleteAnimateIn: function (type, args, obj) { }, /** * The default onStart handler for the out-animation. * @method handleStartAnimateOut * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleStartAnimateOut: function (type, args, obj) { }, /** * The default onTween handler for the out-animation. * @method handleTweenAnimateOut * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleTweenAnimateOut: function (type, args, obj) { }, /** * The default onComplete handler for the out-animation. * @method handleCompleteAnimateOut * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleCompleteAnimateOut: function (type, args, obj) { }, /** * Returns a string representation of the object. * @method toString * @return {String} The string representation of the ContainerEffect */ toString: function () { var output = "ContainerEffect"; if (this.overlay) { output += " [" + this.overlay.toString() + "]"; } return output; } }; YAHOO.lang.augmentProto(ContainerEffect, YAHOO.util.EventProvider); })(); YAHOO.register("containercore", YAHOO.widget.Module, {version: "2.9.0", build: "2800"});
src/components/Transport/PlayButton.js
bocasfx/Q
import React from 'react'; import { connect } from 'react-redux'; import './PlayButton.css'; import { toggleTransport } from '../../actions/Transport'; import { stopNodes, dequeueParticles } from '../../actions/Nodes'; import { bindActionCreators } from 'redux'; import PropTypes from 'prop-types'; class PlayButton extends React.Component { static propTypes = { transport: PropTypes.object, stopNodes: PropTypes.func, dequeueParticles: PropTypes.func, toggleTransport: PropTypes.func, } constructor(props) { super(props); this.onClick = this.onClick.bind(this); } onClick() { if (this.props.transport.playing) { this.props.stopNodes(); this.props.dequeueParticles(); } this.props.toggleTransport(); } render() { let iconClass = 'fa'; iconClass += this.props.transport.playing ? ' fa-pause' : ' fa-play'; return ( <div className="play-button-container" onClick={this.onClick}> <i className={iconClass}/> </div> ); } } const mapStateToProps = (state) => { return { transport: state.transport, }; }; const mapDispatchToProps = (dispatch) => { return { toggleTransport: bindActionCreators(toggleTransport, dispatch), stopNodes: bindActionCreators(stopNodes, dispatch), dequeueParticles: bindActionCreators(dequeueParticles, dispatch), }; }; export default connect(mapStateToProps, mapDispatchToProps)(PlayButton);
ajax/libs/tinymce/4.3.2/plugins/legacyoutput/plugin.js
kennynaoh/cdnjs
/** * plugin.js * * Released under LGPL License. * Copyright (c) 1999-2015 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing * * This plugin will force TinyMCE to produce deprecated legacy output such as font elements, u elements, align * attributes and so forth. There are a few cases where these old items might be needed for example in email applications or with Flash * * However you should NOT use this plugin if you are building some system that produces web contents such as a CMS. All these elements are * not apart of the newer specifications for HTML and XHTML. */ /*global tinymce:true */ (function(tinymce) { // Override inline_styles setting to force TinyMCE to produce deprecated contents tinymce.on('AddEditor', function(e) { e.editor.settings.inline_styles = false; }); tinymce.PluginManager.add('legacyoutput', function(editor, url, $) { editor.on('init', function() { var alignElements = 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', fontSizes = tinymce.explode(editor.settings.font_size_style_values), schema = editor.schema; // Override some internal formats to produce legacy elements and attributes editor.formatter.register({ // Change alignment formats to use the deprecated align attribute alignleft: {selector: alignElements, attributes: {align: 'left'}}, aligncenter: {selector: alignElements, attributes: {align: 'center'}}, alignright: {selector: alignElements, attributes: {align: 'right'}}, alignjustify: {selector: alignElements, attributes: {align: 'justify'}}, // Change the basic formatting elements to use deprecated element types bold: [ {inline: 'b', remove: 'all'}, {inline: 'strong', remove: 'all'}, {inline: 'span', styles: {fontWeight: 'bold'}} ], italic: [ {inline: 'i', remove: 'all'}, {inline: 'em', remove: 'all'}, {inline: 'span', styles: {fontStyle: 'italic'}} ], underline: [ {inline: 'u', remove: 'all'}, {inline: 'span', styles: {textDecoration: 'underline'}, exact: true} ], strikethrough: [ {inline: 'strike', remove: 'all'}, {inline: 'span', styles: {textDecoration: 'line-through'}, exact: true} ], // Change font size and font family to use the deprecated font element fontname: {inline: 'font', attributes: {face: '%value'}}, fontsize: { inline: 'font', attributes: { size: function(vars) { return tinymce.inArray(fontSizes, vars.value) + 1; } } }, // Setup font elements for colors as well forecolor: {inline: 'font', attributes: {color: '%value'}}, hilitecolor: {inline: 'font', styles: {backgroundColor: '%value'}} }); // Check that deprecated elements are allowed if not add them tinymce.each('b,i,u,strike'.split(','), function(name) { schema.addValidElements(name + '[*]'); }); // Add font element if it's missing if (!schema.getElementRule("font")) { schema.addValidElements("font[face|size|color|style]"); } // Add the missing and depreacted align attribute for the serialization engine tinymce.each(alignElements.split(','), function(name) { var rule = schema.getElementRule(name); if (rule) { if (!rule.attributes.align) { rule.attributes.align = {}; rule.attributesOrder.push('align'); } } }); }); editor.addButton('fontsizeselect', function() { var items = [], defaultFontsizeFormats = '8pt=1 10pt=2 12pt=3 14pt=4 18pt=5 24pt=6 36pt=7'; var fontsize_formats = editor.settings.fontsize_formats || defaultFontsizeFormats; editor.$.each(fontsize_formats.split(' '), function(i, item) { var text = item, value = item; var values = item.split('='); if (values.length > 1) { text = values[0]; value = values[1]; } items.push({text: text, value: value}); }); return { type: 'listbox', text: 'Font Sizes', tooltip: 'Font Sizes', values: items, fixedWidth: true, onPostRender: function() { var self = this; editor.on('NodeChange', function() { var fontElm; fontElm = editor.dom.getParent(editor.selection.getNode(), 'font'); if (fontElm) { self.value(fontElm.size); } else { self.value(''); } }); }, onclick: function(e) { if (e.control.settings.value) { editor.execCommand('FontSize', false, e.control.settings.value); } } }; }); editor.addButton('fontselect', function() { function createFormats(formats) { formats = formats.replace(/;$/, '').split(';'); var i = formats.length; while (i--) { formats[i] = formats[i].split('='); } return formats; } var defaultFontsFormats = 'Andale Mono=andale mono,monospace;' + 'Arial=arial,helvetica,sans-serif;' + 'Arial Black=arial black,sans-serif;' + 'Book Antiqua=book antiqua,palatino,serif;' + 'Comic Sans MS=comic sans ms,sans-serif;' + 'Courier New=courier new,courier,monospace;' + 'Georgia=georgia,palatino,serif;' + 'Helvetica=helvetica,arial,sans-serif;' + 'Impact=impact,sans-serif;' + 'Symbol=symbol;' + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + 'Terminal=terminal,monaco,monospace;' + 'Times New Roman=times new roman,times,serif;' + 'Trebuchet MS=trebuchet ms,geneva,sans-serif;' + 'Verdana=verdana,geneva,sans-serif;' + 'Webdings=webdings;' + 'Wingdings=wingdings,zapf dingbats'; var items = [], fonts = createFormats(editor.settings.font_formats || defaultFontsFormats); $.each(fonts, function(i, font) { items.push({ text: {raw: font[0]}, value: font[1], textStyle: font[1].indexOf('dings') == -1 ? 'font-family:' + font[1] : '' }); }); return { type: 'listbox', text: 'Font Family', tooltip: 'Font Family', values: items, fixedWidth: true, onPostRender: function() { var self = this; editor.on('NodeChange', function() { var fontElm; fontElm = editor.dom.getParent(editor.selection.getNode(), 'font'); if (fontElm) { self.value(fontElm.face); } else { self.value(''); } }); }, onselect: function(e) { if (e.control.settings.value) { editor.execCommand('FontName', false, e.control.settings.value); } } }; }); }); })(tinymce);
app/js/containers/MyContainer.js
sgt39007/waji_redux
import React from 'react'; import { connect } from 'react-redux'; import * as AppActions from '../redux/actions/AppActions'; import { Container, List, Group, View, } from 'amazeui-touch'; import { Login, MyFooter } from '../components'; class MyContainer extends React.Component { componentWillMount() { const { dispatch } = this.props; dispatch(AppActions.hideTabbar(false)); dispatch(AppActions.hideNavLeft(true)); dispatch(AppActions.setNavTitle('个人信息')); } renderItems() { const { login, dispatch } = this.props; if (login.loadState.success) { const data = login.data; const img = <img width="60" src={`http://eswjdg.com/${data.hdimg}`} />; //登录了 return ( <div> <Group noPadded> {/*是否移除分组内容的 padding*/} <List> <List.Item title={`昵称: ${login.nickname}`} subTitle={`账号: ${login.username}`} target="_blank" media={img} /> <List.Item title={`性别: ${data.sex}`} /> <List.Item title={`地区: ${data.address}`} /> <List.Item title={`个性签名: ${data.sign}`} /> </List> </Group> <MyFooter /> </div> ); } else { // 没登录-> login的内容 return ( <Login dispatch={dispatch}/> ); } } render() { return ( <View> <Container scrollable> {this.renderItems()} </Container> </View> ); } } function mapStateToProps(state) { return { login: state.login } } export default connect(mapStateToProps)(MyContainer)
files/rxjs/2.2.15/rx.lite.js
anilanar/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: {} }; // Defaults function noop() { } function identity(x) { return x; } var defaultNow = Date.now; function defaultComparer(x, y) { return isEqual(x, y); } function defaultSubComparer(x, y) { return x - y; } function defaultKeySerializer(x) { return x.toString(); } function defaultError(err) { throw err; } function isPromise(p) { return typeof p.then === 'function'; } // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function'; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * @constructor * @private */ var Enumerator = Rx.internals.Enumerator = function (moveNext, getCurrent) { this.moveNext = moveNext; this.getCurrent = getCurrent; }; /** * @static * @memberOf Enumerator * @private */ var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent) { var done = false; return new Enumerator(function () { if (done) { return false; } var result = moveNext(); if (!result) { done = true; } return result; }, function () { return getCurrent(); }); }; var Enumerable = Rx.internals.Enumerable = function (getEnumerator) { this.getEnumerator = getEnumerator; }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, hasNext; if (isDisposed) { return; } try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } } catch (ex) { observer.onError(ex); return; } if (!hasNext) { observer.onCompleted(); return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed, lastException; var subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, hasNext; if (isDisposed) { return; } try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } } catch (ex) { observer.onError(ex); return; } if (!hasNext) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (arguments.length === 1) { repeatCount = -1; } return new Enumerable(function () { var current, left = repeatCount; return enumeratorCreate(function () { if (left === 0) { return false; } if (left > 0) { left--; } current = value; return true; }, function () { return current; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var current, index = -1; return enumeratorCreate( function () { if (++index < source.length) { current = selector.call(thisArg, source[index], index, source); return true; } return false; }, function () { return current; } ); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { /** * @constructor * @private */ function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber; if (typeof observerOrOnNext === 'object') { subscriber = observerOrOnNext; } else { subscriber = observerCreate(observerOrOnNext, onError, onCompleted); } return this._subscribe(subscriber); }; /** * Creates a list from an observable sequence. * * @memberOf Observable * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { function accumulator(list, i) { var newList = list.slice(0); newList.push(i); return newList; } return this.scan([], accumulator).startWith([]).finalValue(); }; return Observable; })(); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Converts a generator function to an observable sequence, using an optional scheduler to enumerate the generator. * * @example * var res = Rx.Observable.fromGenerator(function* () { yield 42; }); * var res = Rx.Observable.fromArray(function* () { yield 42; }, Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. */ observableProto.fromGenerator = function (genFn, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var gen; try { gen = genFn(); } catch (e) { observer.onError(e); return; } return scheduler.scheduleRecursive(function (self) { var next = gen.next(); if (next.done) { observer.onCompleted(); } else { observer.onNext(next.value); self(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throwException(new Error('Error')); * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { if (typeof handlerOrSecond === 'function') { return observableCatchHandler(this, handlerOrSecond); } return observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(args[i].subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { if (isOpen) { observer.onNext(left); } }, observer.onError.bind(observer), function () { if (isOpen) { observer.onCompleted(); } })); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); var next = function (i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.doAction(observer); * var res = observable.doAction(onNext); * var res = observable.doAction(onNext, onError); * var res = observable.doAction(onNext, onError, onCompleted); * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription = source.subscribe(observer); return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = source.takeLast(5); * var res = source.takeLast(5, Rx.Scheduler.timeout); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; function selectMany(selector) { return this.select(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.select(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; function createListener (element, name, handler) { // Node.js specific if (element.addListener) { element.addListener(name, handler); return disposableCreate(function () { element.removeListener(name, handler); }); } else if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (el && el.length) { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el[i], eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new Error('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return !selector ? this.multicast(new Subject()) : this.multicast(function () { return new Subject(); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish(null).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return !selector ? this.multicast(new AsyncSubject()) : this.multicast(function () { return new AsyncSubject(); }, selector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue). refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return !selector ? this.multicast(new ReplaySubject(bufferSize, window, scheduler)) : this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; /** @private */ var ConnectableObservable = Rx.ConnectableObservable = (function (_super) { inherits(ConnectableObservable, _super); /** * @constructor * @private */ function ConnectableObservable(source, subject) { var state = { subject: subject, source: source.asObservable(), hasSubscription: false, subscription: null }; this.connect = function () { if (!state.hasSubscription) { state.hasSubscription = true; state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { state.hasSubscription = false; })); } return state.subscription; }; function subscribe(observer) { return state.subject.subscribe(observer); } _super.call(this, subscribe); } /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.connect = function () { return this.connect(); }; /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.refCount = function () { var connectableSubscription = null, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect, subscription; count++; shouldConnect = count === 1; subscription = source.subscribe(observer); if (shouldConnect) { connectableSubscription = source.connect(); } return disposableCreate(function () { subscription.dispose(); count--; if (count === 0) { connectableSubscription.dispose(); } }); }); }; return ConnectableObservable; }(Observable)); function observableTimerTimeSpan(dueTime, scheduler) { var d = normalizeTime(dueTime); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(d, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { if (dueTime === period) { return new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }); } return observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { scheduler || (scheduler = timeoutScheduler); return observableTimerTimeSpanAndPeriod(period, period, scheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * * @example * var res = Rx.Observable.timer(5000); * var res = Rx.Observable.timer(5000, 1000); * var res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); * var res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); * * @param {Number} dueTime Relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; scheduler || (scheduler = timeoutScheduler); if (typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (typeof periodOrScheduler === 'object' && 'now' in periodOrScheduler) { scheduler = periodOrScheduler; } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * var res = Rx.Observable.delay(5000); * var res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.select(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { scheduler || (scheduler = timeoutScheduler); return this.select(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } if (atEnd) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { scheduler || (scheduler = timeoutScheduler); if (typeof intervalOrSampler === 'number') { return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); } return sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * * @example * 1 - res = source.timeout(new Date()); // As a date * 2 - res = source.timeout(5000); // 5 seconds * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { var schedulerMethod, source = this; other || (other = observableThrow(new Error('Timeout'))); scheduler || (scheduler = timeoutScheduler); if (dueTime instanceof Date) { schedulerMethod = function (dt, action) { scheduler.scheduleWithAbsolute(dt, action); }; } else { schedulerMethod = function (dt, action) { scheduler.scheduleWithRelative(dt, action); }; } return new AnonymousObservable(function (observer) { var createTimer, id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); createTimer = function () { var myId = id; timer.setDisposable(schedulerMethod(dueTime, function () { switched = id === myId; var timerWins = switched; if (timerWins) { subscription.setDisposable(other.subscribe(observer)); } })); }; createTimer(); original.setDisposable(source.subscribe(function (x) { var onNextWins = !switched; if (onNextWins) { id++; observer.onNext(x); createTimer(); } }, function (e) { var onErrorWins = !switched; if (onErrorWins) { id++; observer.onError(e); } }, function () { var onCompletedWins = !switched; if (onCompletedWins) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { if (hasResult) { observer.onNext(result); } try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * * @example * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); * * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; var firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false, setTimer = function (timeout) { var myId = id, timerWins = function () { return id === myId; }; var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } d.dispose(); }, function (e) { if (timerWins()) { observer.onError(e); } }, function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } })); }; setTimer(firstTimeout); var observerWins = function () { var res = !switched; if (res) { id++; } return res; }; original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(timeout); } }, function (e) { if (observerWins()) { observer.onError(e); } }, function () { if (observerWins()) { observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); if (hasValue) { observer.onNext(value); } observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * * @example * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var t = scheduler.scheduleWithRelative(duration, function () { observer.onCompleted(); }); return new CompositeDisposable(t, source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false, t = scheduler.scheduleWithRelative(duration, function () { open = true; }), d = source.subscribe(function (x) { if (open) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); return new CompositeDisposable(t, d); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time>. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var open = false, t = scheduler.scheduleWithAbsolute(startTime, function () { open = true; }), d = source.subscribe(function (x) { if (open) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); return new CompositeDisposable(t, d); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * * @example * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); * @param {Number} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler.scheduleWithAbsolute(endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { var self = this; return new AnonymousObservable(function (observer) { var conn = self.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); }); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { var source = this; return new AnonymousObservable(function (observer) { var q = [], previous = true; var subscription = combineLatestSource( source, subject.distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (results.shouldFire && previous) { observer.onNext(results.data); } if (results.shouldFire && !previous) { while (q.length > 0) { observer.onNext(q.shift()); } previous = true; } else if (!results.shouldFire && !previous) { q.push(results.data); } else if (!results.shouldFire && previous) { previous = false; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer) ); subject.onNext(false); return subscription; }); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); var AnonymousObservable = Rx.AnonymousObservable = (function (_super) { inherits(AnonymousObservable, _super); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } _super.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, _super); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { _super.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (_super) { function RemovableDisposable (subject, observer) { this.subject = subject; this.observer = observer; }; RemovableDisposable.prototype.dispose = function () { this.observer.dispose(); if (!this.subject.isDisposed) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); } }; function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = new RemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, _super); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; _super.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /* @private */ _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { var observer; checkDisposed.call(this); if (!this.isStopped) { var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onNext(value); observer.ensureActive(); } } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; } }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
public/bower_components/phaser/docs/scripts/jquery.min.js
taylorbf/testaroku
/*! jQuery v1.8.3 jquery.com | jquery.org/license */ (function(e, t) { function _(e) { var t = M[e] = {}; return v.each(e.split(y), function(e, n) { t[n] = !0 }), t } function H(e, n, r) { if (r === t && e.nodeType === 1) { var i = "data-" + n.replace(P, "-$1").toLowerCase(); r = e.getAttribute(i); if (typeof r == "string") { try { r = r === "true" ? !0 : r === "false" ? !1 : r === "null" ? null : +r + "" === r ? +r : D.test(r) ? v.parseJSON(r) : r } catch (s) {} v.data(e, n, r) } else r = t } return r } function B(e) { var t; for (t in e) { if (t === "data" && v.isEmptyObject(e[t])) continue; if (t !== "toJSON") return !1 } return !0 } function et() { return !1 } function tt() { return !0 } function ut(e) { return !e || !e.parentNode || e.parentNode.nodeType === 11 } function at(e, t) { do e = e[t]; while (e && e.nodeType !== 1); return e } function ft(e, t, n) { t = t || 0; if (v.isFunction(t)) return v.grep(e, function(e, r) { var i = !! t.call(e, r, e); return i === n }); if (t.nodeType) return v.grep(e, function(e, r) { return e === t === n }); if (typeof t == "string") { var r = v.grep(e, function(e) { return e.nodeType === 1 }); if (it.test(t)) return v.filter(t, r, !n); t = v.filter(t, r) } return v.grep(e, function(e, r) { return v.inArray(e, t) >= 0 === n }) } function lt(e) { var t = ct.split("|"), n = e.createDocumentFragment(); if (n.createElement) while (t.length) n.createElement(t.pop()); return n } function Lt(e, t) { return e.getElementsByTagName(t)[0] || e.appendChild(e.ownerDocument.createElement(t)) } function At(e, t) { if (t.nodeType !== 1 || !v.hasData(e)) return; var n, r, i, s = v._data(e), o = v._data(t, s), u = s.events; if (u) { delete o.handle, o.events = {}; for (n in u) for (r = 0, i = u[n].length; r < i; r++) v.event.add(t, n, u[n][r]) } o.data && (o.data = v.extend({}, o.data)) } function Ot(e, t) { var n; if (t.nodeType !== 1) return; t.clearAttributes && t.clearAttributes(), t.mergeAttributes && t.mergeAttributes(e), n = t.nodeName.toLowerCase(), n === "object" ? (t.parentNode && (t.outerHTML = e.outerHTML), v.support.html5Clone && e.innerHTML && !v.trim(t.innerHTML) && (t.innerHTML = e.innerHTML)) : n === "input" && Et.test(e.type) ? (t.defaultChecked = t.checked = e.checked, t.value !== e.value && (t.value = e.value)) : n === "option" ? t.selected = e.defaultSelected : n === "input" || n === "textarea" ? t.defaultValue = e.defaultValue : n === "script" && t.text !== e.text && (t.text = e.text), t.removeAttribute(v.expando) } function Mt(e) { return typeof e.getElementsByTagName != "undefined" ? e.getElementsByTagName("*") : typeof e.querySelectorAll != "undefined" ? e.querySelectorAll("*") : [] } function _t(e) { Et.test(e.type) && (e.defaultChecked = e.checked) } function Qt(e, t) { if (t in e) return t; var n = t.charAt(0).toUpperCase() + t.slice(1), r = t, i = Jt.length; while (i--) { t = Jt[i] + n; if (t in e) return t } return r } function Gt(e, t) { return e = t || e, v.css(e, "display") === "none" || !v.contains(e.ownerDocument, e) } function Yt(e, t) { var n, r, i = [], s = 0, o = e.length; for (; s < o; s++) { n = e[s]; if (!n.style) continue; i[s] = v._data(n, "olddisplay"), t ? (!i[s] && n.style.display === "none" && (n.style.display = ""), n.style.display === "" && Gt(n) && (i[s] = v._data(n, "olddisplay", nn(n.nodeName)))) : (r = Dt(n, "display"), !i[s] && r !== "none" && v._data(n, "olddisplay", r)) } for (s = 0; s < o; s++) { n = e[s]; if (!n.style) continue; if (!t || n.style.display === "none" || n.style.display === "") n.style.display = t ? i[s] || "" : "none" } return e } function Zt(e, t, n) { var r = Rt.exec(t); return r ? Math.max(0, r[1] - (n || 0)) + (r[2] || "px") : t } function en(e, t, n, r) { var i = n === (r ? "border" : "content") ? 4 : t === "width" ? 1 : 0, s = 0; for (; i < 4; i += 2) n === "margin" && (s += v.css(e, n + $t[i], !0)), r ? (n === "content" && (s -= parseFloat(Dt(e, "padding" + $t[i])) || 0), n !== "margin" && (s -= parseFloat(Dt(e, "border" + $t[i] + "Width")) || 0)) : (s += parseFloat(Dt(e, "padding" + $t[i])) || 0, n !== "padding" && (s += parseFloat(Dt(e, "border" + $t[i] + "Width")) || 0)); return s } function tn(e, t, n) { var r = t === "width" ? e.offsetWidth : e.offsetHeight, i = !0, s = v.support.boxSizing && v.css(e, "boxSizing") === "border-box"; if (r <= 0 || r == null) { r = Dt(e, t); if (r < 0 || r == null) r = e.style[t]; if (Ut.test(r)) return r; i = s && (v.support.boxSizingReliable || r === e.style[t]), r = parseFloat(r) || 0 } return r + en(e, t, n || (s ? "border" : "content"), i) + "px" } function nn(e) { if (Wt[e]) return Wt[e]; var t = v("<" + e + ">").appendTo(i.body), n = t.css("display"); t.remove(); if (n === "none" || n === "") { Pt = i.body.appendChild(Pt || v.extend(i.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 })); if (!Ht || !Pt.createElement) Ht = (Pt.contentWindow || Pt.contentDocument).document, Ht.write("<!doctype html><html><body>"), Ht.close(); t = Ht.body.appendChild(Ht.createElement(e)), n = Dt(t, "display"), i.body.removeChild(Pt) } return Wt[e] = n, n } function fn(e, t, n, r) { var i; if (v.isArray(t)) v.each(t, function(t, i) { n || sn.test(e) ? r(e, i) : fn(e + "[" + (typeof i == "object" ? t : "") + "]", i, n, r) }); else if (!n && v.type(t) === "object") for (i in t) fn(e + "[" + i + "]", t[i], n, r); else r(e, t) } function Cn(e) { return function(t, n) { typeof t != "string" && (n = t, t = "*"); var r, i, s, o = t.toLowerCase().split(y), u = 0, a = o.length; if (v.isFunction(n)) for (; u < a; u++) r = o[u], s = /^\+/.test(r), s && (r = r.substr(1) || "*"), i = e[r] = e[r] || [], i[s ? "unshift" : "push"](n) } } function kn(e, n, r, i, s, o) { s = s || n.dataTypes[0], o = o || {}, o[s] = !0; var u, a = e[s], f = 0, l = a ? a.length : 0, c = e === Sn; for (; f < l && (c || !u); f++) u = a[f](n, r, i), typeof u == "string" && (!c || o[u] ? u = t : (n.dataTypes.unshift(u), u = kn(e, n, r, i, u, o))); return (c || !u) && !o["*"] && (u = kn(e, n, r, i, "*", o)), u } function Ln(e, n) { var r, i, s = v.ajaxSettings.flatOptions || {}; for (r in n) n[r] !== t && ((s[r] ? e : i || (i = {}))[r] = n[r]); i && v.extend(!0, e, i) } function An(e, n, r) { var i, s, o, u, a = e.contents, f = e.dataTypes, l = e.responseFields; for (s in l) s in r && (n[l[s]] = r[s]); while (f[0] === "*") f.shift(), i === t && (i = e.mimeType || n.getResponseHeader("content-type")); if (i) for (s in a) if (a[s] && a[s].test(i)) { f.unshift(s); break } if (f[0] in r) o = f[0]; else { for (s in r) { if (!f[0] || e.converters[s + " " + f[0]]) { o = s; break } u || (u = s) } o = o || u } if (o) return o !== f[0] && f.unshift(o), r[o] } function On(e, t) { var n, r, i, s, o = e.dataTypes.slice(), u = o[0], a = {}, f = 0; e.dataFilter && (t = e.dataFilter(t, e.dataType)); if (o[1]) for (n in e.converters) a[n.toLowerCase()] = e.converters[n]; for (; i = o[++f];) if (i !== "*") { if (u !== "*" && u !== i) { n = a[u + " " + i] || a["* " + i]; if (!n) for (r in a) { s = r.split(" "); if (s[1] === i) { n = a[u + " " + s[0]] || a["* " + s[0]]; if (n) { n === !0 ? n = a[r] : a[r] !== !0 && (i = s[0], o.splice(f--, 0, i)); break } } } if (n !== !0) if (n && e["throws"]) t = n(t); else try { t = n(t) } catch (l) { return { state: "parsererror", error: n ? l : "No conversion from " + u + " to " + i } } } u = i } return { state: "success", data: t } } function Fn() { try { return new e.XMLHttpRequest } catch (t) {} } function In() { try { return new e.ActiveXObject("Microsoft.XMLHTTP") } catch (t) {} } function $n() { return setTimeout(function() { qn = t }, 0), qn = v.now() } function Jn(e, t) { v.each(t, function(t, n) { var r = (Vn[t] || []).concat(Vn["*"]), i = 0, s = r.length; for (; i < s; i++) if (r[i].call(e, t, n)) return }) } function Kn(e, t, n) { var r, i = 0, s = 0, o = Xn.length, u = v.Deferred().always(function() { delete a.elem }), a = function() { var t = qn || $n(), n = Math.max(0, f.startTime + f.duration - t), r = n / f.duration || 0, i = 1 - r, s = 0, o = f.tweens.length; for (; s < o; s++) f.tweens[s].run(i); return u.notifyWith(e, [f, i, n]), i < 1 && o ? n : (u.resolveWith(e, [f]), !1) }, f = u.promise({ elem: e, props: v.extend({}, t), opts: v.extend(!0, { specialEasing: {} }, n), originalProperties: t, originalOptions: n, startTime: qn || $n(), duration: n.duration, tweens: [], createTween: function(t, n, r) { var i = v.Tween(e, f.opts, t, n, f.opts.specialEasing[t] || f.opts.easing); return f.tweens.push(i), i }, stop: function(t) { var n = 0, r = t ? f.tweens.length : 0; for (; n < r; n++) f.tweens[n].run(1); return t ? u.resolveWith(e, [f, t]) : u.rejectWith(e, [f, t]), this } }), l = f.props; Qn(l, f.opts.specialEasing); for (; i < o; i++) { r = Xn[i].call(f, e, l, f.opts); if (r) return r } return Jn(f, l), v.isFunction(f.opts.start) && f.opts.start.call(e, f), v.fx.timer(v.extend(a, { anim: f, queue: f.opts.queue, elem: e })), f.progress(f.opts.progress).done(f.opts.done, f.opts.complete).fail(f.opts.fail).always(f.opts.always) } function Qn(e, t) { var n, r, i, s, o; for (n in e) { r = v.camelCase(n), i = t[r], s = e[n], v.isArray(s) && (i = s[1], s = e[n] = s[0]), n !== r && (e[r] = s, delete e[n]), o = v.cssHooks[r]; if (o && "expand" in o) { s = o.expand(s), delete e[r]; for (n in s) n in e || (e[n] = s[n], t[n] = i) } else t[r] = i } } function Gn(e, t, n) { var r, i, s, o, u, a, f, l, c, h = this, p = e.style, d = {}, m = [], g = e.nodeType && Gt(e); n.queue || (l = v._queueHooks(e, "fx"), l.unqueued == null && (l.unqueued = 0, c = l.empty.fire, l.empty.fire = function() { l.unqueued || c() }), l.unqueued++, h.always(function() { h.always(function() { l.unqueued--, v.queue(e, "fx").length || l.empty.fire() }) })), e.nodeType === 1 && ("height" in t || "width" in t) && (n.overflow = [p.overflow, p.overflowX, p.overflowY], v.css(e, "display") === "inline" && v.css(e, "float") === "none" && (!v.support.inlineBlockNeedsLayout || nn(e.nodeName) === "inline" ? p.display = "inline-block" : p.zoom = 1)), n.overflow && (p.overflow = "hidden", v.support.shrinkWrapBlocks || h.done(function() { p.overflow = n.overflow[0], p.overflowX = n.overflow[1], p.overflowY = n.overflow[2] })); for (r in t) { s = t[r]; if (Un.exec(s)) { delete t[r], a = a || s === "toggle"; if (s === (g ? "hide" : "show")) continue; m.push(r) } } o = m.length; if (o) { u = v._data(e, "fxshow") || v._data(e, "fxshow", {}), "hidden" in u && (g = u.hidden), a && (u.hidden = !g), g ? v(e).show() : h.done(function() { v(e).hide() }), h.done(function() { var t; v.removeData(e, "fxshow", !0); for (t in d) v.style(e, t, d[t]) }); for (r = 0; r < o; r++) i = m[r], f = h.createTween(i, g ? u[i] : 0), d[i] = u[i] || v.style(e, i), i in u || (u[i] = f.start, g && (f.end = f.start, f.start = i === "width" || i === "height" ? 1 : 0)) } } function Yn(e, t, n, r, i) { return new Yn.prototype.init(e, t, n, r, i) } function Zn(e, t) { var n, r = { height: e }, i = 0; t = t ? 1 : 0; for (; i < 4; i += 2 - t) n = $t[i], r["margin" + n] = r["padding" + n] = e; return t && (r.opacity = r.width = e), r } function tr(e) { return v.isWindow(e) ? e : e.nodeType === 9 ? e.defaultView || e.parentWindow : !1 } var n, r, i = e.document, s = e.location, o = e.navigator, u = e.jQuery, a = e.$, f = Array.prototype.push, l = Array.prototype.slice, c = Array.prototype.indexOf, h = Object.prototype.toString, p = Object.prototype.hasOwnProperty, d = String.prototype.trim, v = function(e, t) { return new v.fn.init(e, t, n) }, m = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, g = /\S/, y = /\s+/, b = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, w = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, E = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, S = /^[\],:{}\s]*$/, x = /(?:^|:|,)(?:\s*\[)+/g, T = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, N = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, C = /^-ms-/, k = /-([\da-z])/gi, L = function(e, t) { return (t + "").toUpperCase() }, A = function() { i.addEventListener ? (i.removeEventListener("DOMContentLoaded", A, !1), v.ready()) : i.readyState === "complete" && (i.detachEvent("onreadystatechange", A), v.ready()) }, O = {}; v.fn = v.prototype = { constructor: v, init: function(e, n, r) { var s, o, u, a; if (!e) return this; if (e.nodeType) return this.context = this[0] = e, this.length = 1, this; if (typeof e == "string") { e.charAt(0) === "<" && e.charAt(e.length - 1) === ">" && e.length >= 3 ? s = [null, e, null] : s = w.exec(e); if (s && (s[1] || !n)) { if (s[1]) return n = n instanceof v ? n[0] : n, a = n && n.nodeType ? n.ownerDocument || n : i, e = v.parseHTML(s[1], a, !0), E.test(s[1]) && v.isPlainObject(n) && this.attr.call(e, n, !0), v.merge(this, e); o = i.getElementById(s[2]); if (o && o.parentNode) { if (o.id !== s[2]) return r.find(e); this.length = 1, this[0] = o } return this.context = i, this.selector = e, this } return !n || n.jquery ? (n || r).find(e) : this.constructor(n).find(e) } return v.isFunction(e) ? r.ready(e) : (e.selector !== t && (this.selector = e.selector, this.context = e.context), v.makeArray(e, this)) }, selector: "", jquery: "1.8.3", length: 0, size: function() { return this.length }, toArray: function() { return l.call(this) }, get: function(e) { return e == null ? this.toArray() : e < 0 ? this[this.length + e] : this[e] }, pushStack: function(e, t, n) { var r = v.merge(this.constructor(), e); return r.prevObject = this, r.context = this.context, t === "find" ? r.selector = this.selector + (this.selector ? " " : "") + n : t && (r.selector = this.selector + "." + t + "(" + n + ")"), r }, each: function(e, t) { return v.each(this, e, t) }, ready: function(e) { return v.ready.promise().done(e), this }, eq: function(e) { return e = +e, e === -1 ? this.slice(e) : this.slice(e, e + 1) }, first: function() { return this.eq(0) }, last: function() { return this.eq(-1) }, slice: function() { return this.pushStack(l.apply(this, arguments), "slice", l.call(arguments).join(",")) }, map: function(e) { return this.pushStack(v.map(this, function(t, n) { return e.call(t, n, t) })) }, end: function() { return this.prevObject || this.constructor(null) }, push: f, sort: [].sort, splice: [].splice }, v.fn.init.prototype = v.fn, v.extend = v.fn.extend = function() { var e, n, r, i, s, o, u = arguments[0] || {}, a = 1, f = arguments.length, l = !1; typeof u == "boolean" && (l = u, u = arguments[1] || {}, a = 2), typeof u != "object" && !v.isFunction(u) && (u = {}), f === a && (u = this, --a); for (; a < f; a++) if ((e = arguments[a]) != null) for (n in e) { r = u[n], i = e[n]; if (u === i) continue; l && i && (v.isPlainObject(i) || (s = v.isArray(i))) ? (s ? (s = !1, o = r && v.isArray(r) ? r : []) : o = r && v.isPlainObject(r) ? r : {}, u[n] = v.extend(l, o, i)) : i !== t && (u[n] = i) } return u }, v.extend({ noConflict: function(t) { return e.$ === v && (e.$ = a), t && e.jQuery === v && (e.jQuery = u), v }, isReady: !1, readyWait: 1, holdReady: function(e) { e ? v.readyWait++ : v.ready(!0) }, ready: function(e) { if (e === !0 ? --v.readyWait : v.isReady) return; if (!i.body) return setTimeout(v.ready, 1); v.isReady = !0; if (e !== !0 && --v.readyWait > 0) return; r.resolveWith(i, [v]), v.fn.trigger && v(i).trigger("ready").off("ready") }, isFunction: function(e) { return v.type(e) === "function" }, isArray: Array.isArray || function(e) { return v.type(e) === "array" }, isWindow: function(e) { return e != null && e == e.window }, isNumeric: function(e) { return !isNaN(parseFloat(e)) && isFinite(e) }, type: function(e) { return e == null ? String(e) : O[h.call(e)] || "object" }, isPlainObject: function(e) { if (!e || v.type(e) !== "object" || e.nodeType || v.isWindow(e)) return !1; try { if (e.constructor && !p.call(e, "constructor") && !p.call(e.constructor.prototype, "isPrototypeOf")) return !1 } catch (n) { return !1 } var r; for (r in e); return r === t || p.call(e, r) }, isEmptyObject: function(e) { var t; for (t in e) return !1; return !0 }, error: function(e) { throw new Error(e) }, parseHTML: function(e, t, n) { var r; return !e || typeof e != "string" ? null : (typeof t == "boolean" && (n = t, t = 0), t = t || i, (r = E.exec(e)) ? [t.createElement(r[1])] : (r = v.buildFragment([e], t, n ? null : []), v.merge([], (r.cacheable ? v.clone(r.fragment) : r.fragment).childNodes))) }, parseJSON: function(t) { if (!t || typeof t != "string") return null; t = v.trim(t); if (e.JSON && e.JSON.parse) return e.JSON.parse(t); if (S.test(t.replace(T, "@").replace(N, "]").replace(x, ""))) return (new Function("return " + t))(); v.error("Invalid JSON: " + t) }, parseXML: function(n) { var r, i; if (!n || typeof n != "string") return null; try { e.DOMParser ? (i = new DOMParser, r = i.parseFromString(n, "text/xml")) : (r = new ActiveXObject("Microsoft.XMLDOM"), r.async = "false", r.loadXML(n)) } catch (s) { r = t } return (!r || !r.documentElement || r.getElementsByTagName("parsererror").length) && v.error("Invalid XML: " + n), r }, noop: function() {}, globalEval: function(t) { t && g.test(t) && (e.execScript || function(t) { e.eval.call(e, t) })(t) }, camelCase: function(e) { return e.replace(C, "ms-").replace(k, L) }, nodeName: function(e, t) { return e.nodeName && e.nodeName.toLowerCase() === t.toLowerCase() }, each: function(e, n, r) { var i, s = 0, o = e.length, u = o === t || v.isFunction(e); if (r) { if (u) { for (i in e) if (n.apply(e[i], r) === !1) break } else for (; s < o;) if (n.apply(e[s++], r) === !1) break } else if (u) { for (i in e) if (n.call(e[i], i, e[i]) === !1) break } else for (; s < o;) if (n.call(e[s], s, e[s++]) === !1) break; return e }, trim: d && !d.call("\ufeff\u00a0") ? function(e) { return e == null ? "" : d.call(e) } : function(e) { return e == null ? "" : (e + "").replace(b, "") }, makeArray: function(e, t) { var n, r = t || []; return e != null && (n = v.type(e), e.length == null || n === "string" || n === "function" || n === "regexp" || v.isWindow(e) ? f.call(r, e) : v.merge(r, e)), r }, inArray: function(e, t, n) { var r; if (t) { if (c) return c.call(t, e, n); r = t.length, n = n ? n < 0 ? Math.max(0, r + n) : n : 0; for (; n < r; n++) if (n in t && t[n] === e) return n } return -1 }, merge: function(e, n) { var r = n.length, i = e.length, s = 0; if (typeof r == "number") for (; s < r; s++) e[i++] = n[s]; else while (n[s] !== t) e[i++] = n[s++]; return e.length = i, e }, grep: function(e, t, n) { var r, i = [], s = 0, o = e.length; n = !! n; for (; s < o; s++) r = !! t(e[s], s), n !== r && i.push(e[s]); return i }, map: function(e, n, r) { var i, s, o = [], u = 0, a = e.length, f = e instanceof v || a !== t && typeof a == "number" && (a > 0 && e[0] && e[a - 1] || a === 0 || v.isArray(e)); if (f) for (; u < a; u++) i = n(e[u], u, r), i != null && (o[o.length] = i); else for (s in e) i = n(e[s], s, r), i != null && (o[o.length] = i); return o.concat.apply([], o) }, guid: 1, proxy: function(e, n) { var r, i, s; return typeof n == "string" && (r = e[n], n = e, e = r), v.isFunction(e) ? (i = l.call(arguments, 2), s = function() { return e.apply(n, i.concat(l.call(arguments))) }, s.guid = e.guid = e.guid || v.guid++, s) : t }, access: function(e, n, r, i, s, o, u) { var a, f = r == null, l = 0, c = e.length; if (r && typeof r == "object") { for (l in r) v.access(e, n, l, r[l], 1, o, i); s = 1 } else if (i !== t) { a = u === t && v.isFunction(i), f && (a ? (a = n, n = function(e, t, n) { return a.call(v(e), n) }) : (n.call(e, i), n = null)); if (n) for (; l < c; l++) n(e[l], r, a ? i.call(e[l], l, n(e[l], r)) : i, u); s = 1 } return s ? e : f ? n.call(e) : c ? n(e[0], r) : o }, now: function() { return (new Date).getTime() } }), v.ready.promise = function(t) { if (!r) { r = v.Deferred(); if (i.readyState === "complete") setTimeout(v.ready, 1); else if (i.addEventListener) i.addEventListener("DOMContentLoaded", A, !1), e.addEventListener("load", v.ready, !1); else { i.attachEvent("onreadystatechange", A), e.attachEvent("onload", v.ready); var n = !1; try { n = e.frameElement == null && i.documentElement } catch (s) {} n && n.doScroll && function o() { if (!v.isReady) { try { n.doScroll("left") } catch (e) { return setTimeout(o, 50) } v.ready() } }() } } return r.promise(t) }, v.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(e, t) { O["[object " + t + "]"] = t.toLowerCase() }), n = v(i); var M = {}; v.Callbacks = function(e) { e = typeof e == "string" ? M[e] || _(e) : v.extend({}, e); var n, r, i, s, o, u, a = [], f = !e.once && [], l = function(t) { n = e.memory && t, r = !0, u = s || 0, s = 0, o = a.length, i = !0; for (; a && u < o; u++) if (a[u].apply(t[0], t[1]) === !1 && e.stopOnFalse) { n = !1; break } i = !1, a && (f ? f.length && l(f.shift()) : n ? a = [] : c.disable()) }, c = { add: function() { if (a) { var t = a.length; (function r(t) { v.each(t, function(t, n) { var i = v.type(n); i === "function" ? (!e.unique || !c.has(n)) && a.push(n) : n && n.length && i !== "string" && r(n) }) })(arguments), i ? o = a.length : n && (s = t, l(n)) } return this }, remove: function() { return a && v.each(arguments, function(e, t) { var n; while ((n = v.inArray(t, a, n)) > -1) a.splice(n, 1), i && (n <= o && o--, n <= u && u--) }), this }, has: function(e) { return v.inArray(e, a) > -1 }, empty: function() { return a = [], this }, disable: function() { return a = f = n = t, this }, disabled: function() { return !a }, lock: function() { return f = t, n || c.disable(), this }, locked: function() { return !f }, fireWith: function(e, t) { return t = t || [], t = [e, t.slice ? t.slice() : t], a && (!r || f) && (i ? f.push(t) : l(t)), this }, fire: function() { return c.fireWith(this, arguments), this }, fired: function() { return !!r } }; return c }, v.extend({ Deferred: function(e) { var t = [ ["resolve", "done", v.Callbacks("once memory"), "resolved"], ["reject", "fail", v.Callbacks("once memory"), "rejected"], ["notify", "progress", v.Callbacks("memory")] ], n = "pending", r = { state: function() { return n }, always: function() { return i.done(arguments).fail(arguments), this }, then: function() { var e = arguments; return v.Deferred(function(n) { v.each(t, function(t, r) { var s = r[0], o = e[t]; i[r[1]](v.isFunction(o) ? function() { var e = o.apply(this, arguments); e && v.isFunction(e.promise) ? e.promise().done(n.resolve).fail(n.reject).progress(n.notify) : n[s + "With"](this === i ? n : this, [e]) } : n[s]) }), e = null }).promise() }, promise: function(e) { return e != null ? v.extend(e, r) : r } }, i = {}; return r.pipe = r.then, v.each(t, function(e, s) { var o = s[2], u = s[3]; r[s[1]] = o.add, u && o.add(function() { n = u }, t[e ^ 1][2].disable, t[2][2].lock), i[s[0]] = o.fire, i[s[0] + "With"] = o.fireWith }), r.promise(i), e && e.call(i, i), i }, when: function(e) { var t = 0, n = l.call(arguments), r = n.length, i = r !== 1 || e && v.isFunction(e.promise) ? r : 0, s = i === 1 ? e : v.Deferred(), o = function(e, t, n) { return function(r) { t[e] = this, n[e] = arguments.length > 1 ? l.call(arguments) : r, n === u ? s.notifyWith(t, n) : --i || s.resolveWith(t, n) } }, u, a, f; if (r > 1) { u = new Array(r), a = new Array(r), f = new Array(r); for (; t < r; t++) n[t] && v.isFunction(n[t].promise) ? n[t].promise().done(o(t, f, n)).fail(s.reject).progress(o(t, a, u)) : --i } return i || s.resolveWith(f, n), s.promise() } }), v.support = function() { var t, n, r, s, o, u, a, f, l, c, h, p = i.createElement("div"); p.setAttribute("className", "t"), p.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>", n = p.getElementsByTagName("*"), r = p.getElementsByTagName("a")[0]; if (!n || !r || !n.length) return {}; s = i.createElement("select"), o = s.appendChild(i.createElement("option")), u = p.getElementsByTagName("input")[0], r.style.cssText = "top:1px;float:left;opacity:.5", t = { leadingWhitespace: p.firstChild.nodeType === 3, tbody: !p.getElementsByTagName("tbody").length, htmlSerialize: !! p.getElementsByTagName("link").length, style: /top/.test(r.getAttribute("style")), hrefNormalized: r.getAttribute("href") === "/a", opacity: /^0.5/.test(r.style.opacity), cssFloat: !! r.style.cssFloat, checkOn: u.value === "on", optSelected: o.selected, getSetAttribute: p.className !== "t", enctype: !! i.createElement("form").enctype, html5Clone: i.createElement("nav").cloneNode(!0).outerHTML !== "<:nav></:nav>", boxModel: i.compatMode === "CSS1Compat", submitBubbles: !0, changeBubbles: !0, focusinBubbles: !1, deleteExpando: !0, noCloneEvent: !0, inlineBlockNeedsLayout: !1, shrinkWrapBlocks: !1, reliableMarginRight: !0, boxSizingReliable: !0, pixelPosition: !1 }, u.checked = !0, t.noCloneChecked = u.cloneNode(!0).checked, s.disabled = !0, t.optDisabled = !o.disabled; try { delete p.test } catch (d) { t.deleteExpando = !1 }!p.addEventListener && p.attachEvent && p.fireEvent && (p.attachEvent("onclick", h = function() { t.noCloneEvent = !1 }), p.cloneNode(!0).fireEvent("onclick"), p.detachEvent("onclick", h)), u = i.createElement("input"), u.value = "t", u.setAttribute("type", "radio"), t.radioValue = u.value === "t", u.setAttribute("checked", "checked"), u.setAttribute("name", "t"), p.appendChild(u), a = i.createDocumentFragment(), a.appendChild(p.lastChild), t.checkClone = a.cloneNode(!0).cloneNode(!0).lastChild.checked, t.appendChecked = u.checked, a.removeChild(u), a.appendChild(p); if (p.attachEvent) for (l in { submit: !0, change: !0, focusin: !0 }) f = "on" + l, c = f in p, c || (p.setAttribute(f, "return;"), c = typeof p[f] == "function"), t[l + "Bubbles"] = c; return v(function() { var n, r, s, o, u = "padding:0;margin:0;border:0;display:block;overflow:hidden;", a = i.getElementsByTagName("body")[0]; if (!a) return; n = i.createElement("div"), n.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px", a.insertBefore(n, a.firstChild), r = i.createElement("div"), n.appendChild(r), r.innerHTML = "<table><tr><td></td><td>t</td></tr></table>", s = r.getElementsByTagName("td"), s[0].style.cssText = "padding:0;margin:0;border:0;display:none", c = s[0].offsetHeight === 0, s[0].style.display = "", s[1].style.display = "none", t.reliableHiddenOffsets = c && s[0].offsetHeight === 0, r.innerHTML = "", r.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;", t.boxSizing = r.offsetWidth === 4, t.doesNotIncludeMarginInBodyOffset = a.offsetTop !== 1, e.getComputedStyle && (t.pixelPosition = (e.getComputedStyle(r, null) || {}).top !== "1%", t.boxSizingReliable = (e.getComputedStyle(r, null) || { width: "4px" }).width === "4px", o = i.createElement("div"), o.style.cssText = r.style.cssText = u, o.style.marginRight = o.style.width = "0", r.style.width = "1px", r.appendChild(o), t.reliableMarginRight = !parseFloat((e.getComputedStyle(o, null) || {}).marginRight)), typeof r.style.zoom != "undefined" && (r.innerHTML = "", r.style.cssText = u + "width:1px;padding:1px;display:inline;zoom:1", t.inlineBlockNeedsLayout = r.offsetWidth === 3, r.style.display = "block", r.style.overflow = "visible", r.innerHTML = "<div></div>", r.firstChild.style.width = "5px", t.shrinkWrapBlocks = r.offsetWidth !== 3, n.style.zoom = 1), a.removeChild(n), n = r = s = o = null }), a.removeChild(p), n = r = s = o = u = a = p = null, t }(); var D = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, P = /([A-Z])/g; v.extend({ cache: {}, deletedIds: [], uuid: 0, expando: "jQuery" + (v.fn.jquery + Math.random()).replace(/\D/g, ""), noData: { embed: !0, object: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", applet: !0 }, hasData: function(e) { return e = e.nodeType ? v.cache[e[v.expando]] : e[v.expando], !! e && !B(e) }, data: function(e, n, r, i) { if (!v.acceptData(e)) return; var s, o, u = v.expando, a = typeof n == "string", f = e.nodeType, l = f ? v.cache : e, c = f ? e[u] : e[u] && u; if ((!c || !l[c] || !i && !l[c].data) && a && r === t) return; c || (f ? e[u] = c = v.deletedIds.pop() || v.guid++ : c = u), l[c] || (l[c] = {}, f || (l[c].toJSON = v.noop)); if (typeof n == "object" || typeof n == "function") i ? l[c] = v.extend(l[c], n) : l[c].data = v.extend(l[c].data, n); return s = l[c], i || (s.data || (s.data = {}), s = s.data), r !== t && (s[v.camelCase(n)] = r), a ? (o = s[n], o == null && (o = s[v.camelCase(n)])) : o = s, o }, removeData: function(e, t, n) { if (!v.acceptData(e)) return; var r, i, s, o = e.nodeType, u = o ? v.cache : e, a = o ? e[v.expando] : v.expando; if (!u[a]) return; if (t) { r = n ? u[a] : u[a].data; if (r) { v.isArray(t) || (t in r ? t = [t] : (t = v.camelCase(t), t in r ? t = [t] : t = t.split(" "))); for (i = 0, s = t.length; i < s; i++) delete r[t[i]]; if (!(n ? B : v.isEmptyObject)(r)) return } } if (!n) { delete u[a].data; if (!B(u[a])) return } o ? v.cleanData([e], !0) : v.support.deleteExpando || u != u.window ? delete u[a] : u[a] = null }, _data: function(e, t, n) { return v.data(e, t, n, !0) }, acceptData: function(e) { var t = e.nodeName && v.noData[e.nodeName.toLowerCase()]; return !t || t !== !0 && e.getAttribute("classid") === t } }), v.fn.extend({ data: function(e, n) { var r, i, s, o, u, a = this[0], f = 0, l = null; if (e === t) { if (this.length) { l = v.data(a); if (a.nodeType === 1 && !v._data(a, "parsedAttrs")) { s = a.attributes; for (u = s.length; f < u; f++) o = s[f].name, o.indexOf("data-") || (o = v.camelCase(o.substring(5)), H(a, o, l[o])); v._data(a, "parsedAttrs", !0) } } return l } return typeof e == "object" ? this.each(function() { v.data(this, e) }) : (r = e.split(".", 2), r[1] = r[1] ? "." + r[1] : "", i = r[1] + "!", v.access(this, function(n) { if (n === t) return l = this.triggerHandler("getData" + i, [r[0]]), l === t && a && (l = v.data(a, e), l = H(a, e, l)), l === t && r[1] ? this.data(r[0]) : l; r[1] = n, this.each(function() { var t = v(this); t.triggerHandler("setData" + i, r), v.data(this, e, n), t.triggerHandler("changeData" + i, r) }) }, null, n, arguments.length > 1, null, !1)) }, removeData: function(e) { return this.each(function() { v.removeData(this, e) }) } }), v.extend({ queue: function(e, t, n) { var r; if (e) return t = (t || "fx") + "queue", r = v._data(e, t), n && (!r || v.isArray(n) ? r = v._data(e, t, v.makeArray(n)) : r.push(n)), r || [] }, dequeue: function(e, t) { t = t || "fx"; var n = v.queue(e, t), r = n.length, i = n.shift(), s = v._queueHooks(e, t), o = function() { v.dequeue(e, t) }; i === "inprogress" && (i = n.shift(), r--), i && (t === "fx" && n.unshift("inprogress"), delete s.stop, i.call(e, o, s)), !r && s && s.empty.fire() }, _queueHooks: function(e, t) { var n = t + "queueHooks"; return v._data(e, n) || v._data(e, n, { empty: v.Callbacks("once memory").add(function() { v.removeData(e, t + "queue", !0), v.removeData(e, n, !0) }) }) } }), v.fn.extend({ queue: function(e, n) { var r = 2; return typeof e != "string" && (n = e, e = "fx", r--), arguments.length < r ? v.queue(this[0], e) : n === t ? this : this.each(function() { var t = v.queue(this, e, n); v._queueHooks(this, e), e === "fx" && t[0] !== "inprogress" && v.dequeue(this, e) }) }, dequeue: function(e) { return this.each(function() { v.dequeue(this, e) }) }, delay: function(e, t) { return e = v.fx ? v.fx.speeds[e] || e : e, t = t || "fx", this.queue(t, function(t, n) { var r = setTimeout(t, e); n.stop = function() { clearTimeout(r) } }) }, clearQueue: function(e) { return this.queue(e || "fx", []) }, promise: function(e, n) { var r, i = 1, s = v.Deferred(), o = this, u = this.length, a = function() { --i || s.resolveWith(o, [o]) }; typeof e != "string" && (n = e, e = t), e = e || "fx"; while (u--) r = v._data(o[u], e + "queueHooks"), r && r.empty && (i++, r.empty.add(a)); return a(), s.promise(n) } }); var j, F, I, q = /[\t\r\n]/g, R = /\r/g, U = /^(?:button|input)$/i, z = /^(?:button|input|object|select|textarea)$/i, W = /^a(?:rea|)$/i, X = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, V = v.support.getSetAttribute; v.fn.extend({ attr: function(e, t) { return v.access(this, v.attr, e, t, arguments.length > 1) }, removeAttr: function(e) { return this.each(function() { v.removeAttr(this, e) }) }, prop: function(e, t) { return v.access(this, v.prop, e, t, arguments.length > 1) }, removeProp: function(e) { return e = v.propFix[e] || e, this.each(function() { try { this[e] = t, delete this[e] } catch (n) {} }) }, addClass: function(e) { var t, n, r, i, s, o, u; if (v.isFunction(e)) return this.each(function(t) { v(this).addClass(e.call(this, t, this.className)) }); if (e && typeof e == "string") { t = e.split(y); for (n = 0, r = this.length; n < r; n++) { i = this[n]; if (i.nodeType === 1) if (!i.className && t.length === 1) i.className = e; else { s = " " + i.className + " "; for (o = 0, u = t.length; o < u; o++) s.indexOf(" " + t[o] + " ") < 0 && (s += t[o] + " "); i.className = v.trim(s) } } } return this }, removeClass: function(e) { var n, r, i, s, o, u, a; if (v.isFunction(e)) return this.each(function(t) { v(this).removeClass(e.call(this, t, this.className)) }); if (e && typeof e == "string" || e === t) { n = (e || "").split(y); for (u = 0, a = this.length; u < a; u++) { i = this[u]; if (i.nodeType === 1 && i.className) { r = (" " + i.className + " ").replace(q, " "); for (s = 0, o = n.length; s < o; s++) while (r.indexOf(" " + n[s] + " ") >= 0) r = r.replace(" " + n[s] + " ", " "); i.className = e ? v.trim(r) : "" } } } return this }, toggleClass: function(e, t) { var n = typeof e, r = typeof t == "boolean"; return v.isFunction(e) ? this.each(function(n) { v(this).toggleClass(e.call(this, n, this.className, t), t) }) : this.each(function() { if (n === "string") { var i, s = 0, o = v(this), u = t, a = e.split(y); while (i = a[s++]) u = r ? u : !o.hasClass(i), o[u ? "addClass" : "removeClass"](i) } else if (n === "undefined" || n === "boolean") this.className && v._data(this, "__className__", this.className), this.className = this.className || e === !1 ? "" : v._data(this, "__className__") || "" }) }, hasClass: function(e) { var t = " " + e + " ", n = 0, r = this.length; for (; n < r; n++) if (this[n].nodeType === 1 && (" " + this[n].className + " ").replace(q, " ").indexOf(t) >= 0) return !0; return !1 }, val: function(e) { var n, r, i, s = this[0]; if (!arguments.length) { if (s) return n = v.valHooks[s.type] || v.valHooks[s.nodeName.toLowerCase()], n && "get" in n && (r = n.get(s, "value")) !== t ? r : (r = s.value, typeof r == "string" ? r.replace(R, "") : r == null ? "" : r); return } return i = v.isFunction(e), this.each(function(r) { var s, o = v(this); if (this.nodeType !== 1) return; i ? s = e.call(this, r, o.val()) : s = e, s == null ? s = "" : typeof s == "number" ? s += "" : v.isArray(s) && (s = v.map(s, function(e) { return e == null ? "" : e + "" })), n = v.valHooks[this.type] || v.valHooks[this.nodeName.toLowerCase()]; if (!n || !("set" in n) || n.set(this, s, "value") === t) this.value = s }) } }), v.extend({ valHooks: { option: { get: function(e) { var t = e.attributes.value; return !t || t.specified ? e.value : e.text } }, select: { get: function(e) { var t, n, r = e.options, i = e.selectedIndex, s = e.type === "select-one" || i < 0, o = s ? null : [], u = s ? i + 1 : r.length, a = i < 0 ? u : s ? i : 0; for (; a < u; a++) { n = r[a]; if ((n.selected || a === i) && (v.support.optDisabled ? !n.disabled : n.getAttribute("disabled") === null) && (!n.parentNode.disabled || !v.nodeName(n.parentNode, "optgroup"))) { t = v(n).val(); if (s) return t; o.push(t) } } return o }, set: function(e, t) { var n = v.makeArray(t); return v(e).find("option").each(function() { this.selected = v.inArray(v(this).val(), n) >= 0 }), n.length || (e.selectedIndex = -1), n } } }, attrFn: {}, attr: function(e, n, r, i) { var s, o, u, a = e.nodeType; if (!e || a === 3 || a === 8 || a === 2) return; if (i && v.isFunction(v.fn[n])) return v(e)[n](r); if (typeof e.getAttribute == "undefined") return v.prop(e, n, r); u = a !== 1 || !v.isXMLDoc(e), u && (n = n.toLowerCase(), o = v.attrHooks[n] || (X.test(n) ? F : j)); if (r !== t) { if (r === null) { v.removeAttr(e, n); return } return o && "set" in o && u && (s = o.set(e, r, n)) !== t ? s : (e.setAttribute(n, r + ""), r) } return o && "get" in o && u && (s = o.get(e, n)) !== null ? s : (s = e.getAttribute(n), s === null ? t : s) }, removeAttr: function(e, t) { var n, r, i, s, o = 0; if (t && e.nodeType === 1) { r = t.split(y); for (; o < r.length; o++) i = r[o], i && (n = v.propFix[i] || i, s = X.test(i), s || v.attr(e, i, ""), e.removeAttribute(V ? i : n), s && n in e && (e[n] = !1)) } }, attrHooks: { type: { set: function(e, t) { if (U.test(e.nodeName) && e.parentNode) v.error("type property can't be changed"); else if (!v.support.radioValue && t === "radio" && v.nodeName(e, "input")) { var n = e.value; return e.setAttribute("type", t), n && (e.value = n), t } } }, value: { get: function(e, t) { return j && v.nodeName(e, "button") ? j.get(e, t) : t in e ? e.value : null }, set: function(e, t, n) { if (j && v.nodeName(e, "button")) return j.set(e, t, n); e.value = t } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function(e, n, r) { var i, s, o, u = e.nodeType; if (!e || u === 3 || u === 8 || u === 2) return; return o = u !== 1 || !v.isXMLDoc(e), o && (n = v.propFix[n] || n, s = v.propHooks[n]), r !== t ? s && "set" in s && (i = s.set(e, r, n)) !== t ? i : e[n] = r : s && "get" in s && (i = s.get(e, n)) !== null ? i : e[n] }, propHooks: { tabIndex: { get: function(e) { var n = e.getAttributeNode("tabindex"); return n && n.specified ? parseInt(n.value, 10) : z.test(e.nodeName) || W.test(e.nodeName) && e.href ? 0 : t } } } }), F = { get: function(e, n) { var r, i = v.prop(e, n); return i === !0 || typeof i != "boolean" && (r = e.getAttributeNode(n)) && r.nodeValue !== !1 ? n.toLowerCase() : t }, set: function(e, t, n) { var r; return t === !1 ? v.removeAttr(e, n) : (r = v.propFix[n] || n, r in e && (e[r] = !0), e.setAttribute(n, n.toLowerCase())), n } }, V || (I = { name: !0, id: !0, coords: !0 }, j = v.valHooks.button = { get: function(e, n) { var r; return r = e.getAttributeNode(n), r && (I[n] ? r.value !== "" : r.specified) ? r.value : t }, set: function(e, t, n) { var r = e.getAttributeNode(n); return r || (r = i.createAttribute(n), e.setAttributeNode(r)), r.value = t + "" } }, v.each(["width", "height"], function(e, t) { v.attrHooks[t] = v.extend(v.attrHooks[t], { set: function(e, n) { if (n === "") return e.setAttribute(t, "auto"), n } }) }), v.attrHooks.contenteditable = { get: j.get, set: function(e, t, n) { t === "" && (t = "false"), j.set(e, t, n) } }), v.support.hrefNormalized || v.each(["href", "src", "width", "height"], function(e, n) { v.attrHooks[n] = v.extend(v.attrHooks[n], { get: function(e) { var r = e.getAttribute(n, 2); return r === null ? t : r } }) }), v.support.style || (v.attrHooks.style = { get: function(e) { return e.style.cssText.toLowerCase() || t }, set: function(e, t) { return e.style.cssText = t + "" } }), v.support.optSelected || (v.propHooks.selected = v.extend(v.propHooks.selected, { get: function(e) { var t = e.parentNode; return t && (t.selectedIndex, t.parentNode && t.parentNode.selectedIndex), null } })), v.support.enctype || (v.propFix.enctype = "encoding"), v.support.checkOn || v.each(["radio", "checkbox"], function() { v.valHooks[this] = { get: function(e) { return e.getAttribute("value") === null ? "on" : e.value } } }), v.each(["radio", "checkbox"], function() { v.valHooks[this] = v.extend(v.valHooks[this], { set: function(e, t) { if (v.isArray(t)) return e.checked = v.inArray(v(e).val(), t) >= 0 } }) }); var $ = /^(?:textarea|input|select)$/i, J = /^([^\.]*|)(?:\.(.+)|)$/, K = /(?:^|\s)hover(\.\S+|)\b/, Q = /^key/, G = /^(?:mouse|contextmenu)|click/, Y = /^(?:focusinfocus|focusoutblur)$/, Z = function(e) { return v.event.special.hover ? e : e.replace(K, "mouseenter$1 mouseleave$1") }; v.event = { add: function(e, n, r, i, s) { var o, u, a, f, l, c, h, p, d, m, g; if (e.nodeType === 3 || e.nodeType === 8 || !n || !r || !(o = v._data(e))) return; r.handler && (d = r, r = d.handler, s = d.selector), r.guid || (r.guid = v.guid++), a = o.events, a || (o.events = a = {}), u = o.handle, u || (o.handle = u = function(e) { return typeof v == "undefined" || !! e && v.event.triggered === e.type ? t : v.event.dispatch.apply(u.elem, arguments) }, u.elem = e), n = v.trim(Z(n)).split(" "); for (f = 0; f < n.length; f++) { l = J.exec(n[f]) || [], c = l[1], h = (l[2] || "").split(".").sort(), g = v.event.special[c] || {}, c = (s ? g.delegateType : g.bindType) || c, g = v.event.special[c] || {}, p = v.extend({ type: c, origType: l[1], data: i, handler: r, guid: r.guid, selector: s, needsContext: s && v.expr.match.needsContext.test(s), namespace: h.join(".") }, d), m = a[c]; if (!m) { m = a[c] = [], m.delegateCount = 0; if (!g.setup || g.setup.call(e, i, h, u) === !1) e.addEventListener ? e.addEventListener(c, u, !1) : e.attachEvent && e.attachEvent("on" + c, u) } g.add && (g.add.call(e, p), p.handler.guid || (p.handler.guid = r.guid)), s ? m.splice(m.delegateCount++, 0, p) : m.push(p), v.event.global[c] = !0 } e = null }, global: {}, remove: function(e, t, n, r, i) { var s, o, u, a, f, l, c, h, p, d, m, g = v.hasData(e) && v._data(e); if (!g || !(h = g.events)) return; t = v.trim(Z(t || "")).split(" "); for (s = 0; s < t.length; s++) { o = J.exec(t[s]) || [], u = a = o[1], f = o[2]; if (!u) { for (u in h) v.event.remove(e, u + t[s], n, r, !0); continue } p = v.event.special[u] || {}, u = (r ? p.delegateType : p.bindType) || u, d = h[u] || [], l = d.length, f = f ? new RegExp("(^|\\.)" + f.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; for (c = 0; c < d.length; c++) m = d[c], (i || a === m.origType) && (!n || n.guid === m.guid) && (!f || f.test(m.namespace)) && (!r || r === m.selector || r === "**" && m.selector) && (d.splice(c--, 1), m.selector && d.delegateCount--, p.remove && p.remove.call(e, m)); d.length === 0 && l !== d.length && ((!p.teardown || p.teardown.call(e, f, g.handle) === !1) && v.removeEvent(e, u, g.handle), delete h[u]) } v.isEmptyObject(h) && (delete g.handle, v.removeData(e, "events", !0)) }, customEvent: { getData: !0, setData: !0, changeData: !0 }, trigger: function(n, r, s, o) { if (!s || s.nodeType !== 3 && s.nodeType !== 8) { var u, a, f, l, c, h, p, d, m, g, y = n.type || n, b = []; if (Y.test(y + v.event.triggered)) return; y.indexOf("!") >= 0 && (y = y.slice(0, -1), a = !0), y.indexOf(".") >= 0 && (b = y.split("."), y = b.shift(), b.sort()); if ((!s || v.event.customEvent[y]) && !v.event.global[y]) return; n = typeof n == "object" ? n[v.expando] ? n : new v.Event(y, n) : new v.Event(y), n.type = y, n.isTrigger = !0, n.exclusive = a, n.namespace = b.join("."), n.namespace_re = n.namespace ? new RegExp("(^|\\.)" + b.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, h = y.indexOf(":") < 0 ? "on" + y : ""; if (!s) { u = v.cache; for (f in u) u[f].events && u[f].events[y] && v.event.trigger(n, r, u[f].handle.elem, !0); return } n.result = t, n.target || (n.target = s), r = r != null ? v.makeArray(r) : [], r.unshift(n), p = v.event.special[y] || {}; if (p.trigger && p.trigger.apply(s, r) === !1) return; m = [ [s, p.bindType || y] ]; if (!o && !p.noBubble && !v.isWindow(s)) { g = p.delegateType || y, l = Y.test(g + y) ? s : s.parentNode; for (c = s; l; l = l.parentNode) m.push([l, g]), c = l; c === (s.ownerDocument || i) && m.push([c.defaultView || c.parentWindow || e, g]) } for (f = 0; f < m.length && !n.isPropagationStopped(); f++) l = m[f][0], n.type = m[f][1], d = (v._data(l, "events") || {})[n.type] && v._data(l, "handle"), d && d.apply(l, r), d = h && l[h], d && v.acceptData(l) && d.apply && d.apply(l, r) === !1 && n.preventDefault(); return n.type = y, !o && !n.isDefaultPrevented() && (!p._default || p._default.apply(s.ownerDocument, r) === !1) && (y !== "click" || !v.nodeName(s, "a")) && v.acceptData(s) && h && s[y] && (y !== "focus" && y !== "blur" || n.target.offsetWidth !== 0) && !v.isWindow(s) && (c = s[h], c && (s[h] = null), v.event.triggered = y, s[y](), v.event.triggered = t, c && (s[h] = c)), n.result } return }, dispatch: function(n) { n = v.event.fix(n || e.event); var r, i, s, o, u, a, f, c, h, p, d = (v._data(this, "events") || {})[n.type] || [], m = d.delegateCount, g = l.call(arguments), y = !n.exclusive && !n.namespace, b = v.event.special[n.type] || {}, w = []; g[0] = n, n.delegateTarget = this; if (b.preDispatch && b.preDispatch.call(this, n) === !1) return; if (m && (!n.button || n.type !== "click")) for (s = n.target; s != this; s = s.parentNode || this) if (s.disabled !== !0 || n.type !== "click") { u = {}, f = []; for (r = 0; r < m; r++) c = d[r], h = c.selector, u[h] === t && (u[h] = c.needsContext ? v(h, this).index(s) >= 0 : v.find(h, this, null, [s]).length), u[h] && f.push(c); f.length && w.push({ elem: s, matches: f }) } d.length > m && w.push({ elem: this, matches: d.slice(m) }); for (r = 0; r < w.length && !n.isPropagationStopped(); r++) { a = w[r], n.currentTarget = a.elem; for (i = 0; i < a.matches.length && !n.isImmediatePropagationStopped(); i++) { c = a.matches[i]; if (y || !n.namespace && !c.namespace || n.namespace_re && n.namespace_re.test(c.namespace)) n.data = c.data, n.handleObj = c, o = ((v.event.special[c.origType] || {}).handle || c.handler).apply(a.elem, g), o !== t && (n.result = o, o === !1 && (n.preventDefault(), n.stopPropagation())) } } return b.postDispatch && b.postDispatch.call(this, n), n.result }, props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function(e, t) { return e.which == null && (e.which = t.charCode != null ? t.charCode : t.keyCode), e } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function(e, n) { var r, s, o, u = n.button, a = n.fromElement; return e.pageX == null && n.clientX != null && (r = e.target.ownerDocument || i, s = r.documentElement, o = r.body, e.pageX = n.clientX + (s && s.scrollLeft || o && o.scrollLeft || 0) - (s && s.clientLeft || o && o.clientLeft || 0), e.pageY = n.clientY + (s && s.scrollTop || o && o.scrollTop || 0) - (s && s.clientTop || o && o.clientTop || 0)), !e.relatedTarget && a && (e.relatedTarget = a === e.target ? n.toElement : a), !e.which && u !== t && (e.which = u & 1 ? 1 : u & 2 ? 3 : u & 4 ? 2 : 0), e } }, fix: function(e) { if (e[v.expando]) return e; var t, n, r = e, s = v.event.fixHooks[e.type] || {}, o = s.props ? this.props.concat(s.props) : this.props; e = v.Event(r); for (t = o.length; t;) n = o[--t], e[n] = r[n]; return e.target || (e.target = r.srcElement || i), e.target.nodeType === 3 && (e.target = e.target.parentNode), e.metaKey = !! e.metaKey, s.filter ? s.filter(e, r) : e }, special: { load: { noBubble: !0 }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function(e, t, n) { v.isWindow(this) && (this.onbeforeunload = n) }, teardown: function(e, t) { this.onbeforeunload === t && (this.onbeforeunload = null) } } }, simulate: function(e, t, n, r) { var i = v.extend(new v.Event, n, { type: e, isSimulated: !0, originalEvent: {} }); r ? v.event.trigger(i, null, t) : v.event.dispatch.call(t, i), i.isDefaultPrevented() && n.preventDefault() } }, v.event.handle = v.event.dispatch, v.removeEvent = i.removeEventListener ? function(e, t, n) { e.removeEventListener && e.removeEventListener(t, n, !1) } : function(e, t, n) { var r = "on" + t; e.detachEvent && (typeof e[r] == "undefined" && (e[r] = null), e.detachEvent(r, n)) }, v.Event = function(e, t) { if (!(this instanceof v.Event)) return new v.Event(e, t); e && e.type ? (this.originalEvent = e, this.type = e.type, this.isDefaultPrevented = e.defaultPrevented || e.returnValue === !1 || e.getPreventDefault && e.getPreventDefault() ? tt : et) : this.type = e, t && v.extend(this, t), this.timeStamp = e && e.timeStamp || v.now(), this[v.expando] = !0 }, v.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = tt; var e = this.originalEvent; if (!e) return; e.preventDefault ? e.preventDefault() : e.returnValue = !1 }, stopPropagation: function() { this.isPropagationStopped = tt; var e = this.originalEvent; if (!e) return; e.stopPropagation && e.stopPropagation(), e.cancelBubble = !0 }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = tt, this.stopPropagation() }, isDefaultPrevented: et, isPropagationStopped: et, isImmediatePropagationStopped: et }, v.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function(e, t) { v.event.special[e] = { delegateType: t, bindType: t, handle: function(e) { var n, r = this, i = e.relatedTarget, s = e.handleObj, o = s.selector; if (!i || i !== r && !v.contains(r, i)) e.type = s.origType, n = s.handler.apply(this, arguments), e.type = t; return n } } }), v.support.submitBubbles || (v.event.special.submit = { setup: function() { if (v.nodeName(this, "form")) return !1; v.event.add(this, "click._submit keypress._submit", function(e) { var n = e.target, r = v.nodeName(n, "input") || v.nodeName(n, "button") ? n.form : t; r && !v._data(r, "_submit_attached") && (v.event.add(r, "submit._submit", function(e) { e._submit_bubble = !0 }), v._data(r, "_submit_attached", !0)) }) }, postDispatch: function(e) { e._submit_bubble && (delete e._submit_bubble, this.parentNode && !e.isTrigger && v.event.simulate("submit", this.parentNode, e, !0)) }, teardown: function() { if (v.nodeName(this, "form")) return !1; v.event.remove(this, "._submit") } }), v.support.changeBubbles || (v.event.special.change = { setup: function() { if ($.test(this.nodeName)) { if (this.type === "checkbox" || this.type === "radio") v.event.add(this, "propertychange._change", function(e) { e.originalEvent.propertyName === "checked" && (this._just_changed = !0) }), v.event.add(this, "click._change", function(e) { this._just_changed && !e.isTrigger && (this._just_changed = !1), v.event.simulate("change", this, e, !0) }); return !1 } v.event.add(this, "beforeactivate._change", function(e) { var t = e.target; $.test(t.nodeName) && !v._data(t, "_change_attached") && (v.event.add(t, "change._change", function(e) { this.parentNode && !e.isSimulated && !e.isTrigger && v.event.simulate("change", this.parentNode, e, !0) }), v._data(t, "_change_attached", !0)) }) }, handle: function(e) { var t = e.target; if (this !== t || e.isSimulated || e.isTrigger || t.type !== "radio" && t.type !== "checkbox") return e.handleObj.handler.apply(this, arguments) }, teardown: function() { return v.event.remove(this, "._change"), !$.test(this.nodeName) } }), v.support.focusinBubbles || v.each({ focus: "focusin", blur: "focusout" }, function(e, t) { var n = 0, r = function(e) { v.event.simulate(t, e.target, v.event.fix(e), !0) }; v.event.special[t] = { setup: function() { n++ === 0 && i.addEventListener(e, r, !0) }, teardown: function() { --n === 0 && i.removeEventListener(e, r, !0) } } }), v.fn.extend({ on: function(e, n, r, i, s) { var o, u; if (typeof e == "object") { typeof n != "string" && (r = r || n, n = t); for (u in e) this.on(u, n, r, e[u], s); return this } r == null && i == null ? (i = n, r = n = t) : i == null && (typeof n == "string" ? (i = r, r = t) : (i = r, r = n, n = t)); if (i === !1) i = et; else if (!i) return this; return s === 1 && (o = i, i = function(e) { return v().off(e), o.apply(this, arguments) }, i.guid = o.guid || (o.guid = v.guid++)), this.each(function() { v.event.add(this, e, i, r, n) }) }, one: function(e, t, n, r) { return this.on(e, t, n, r, 1) }, off: function(e, n, r) { var i, s; if (e && e.preventDefault && e.handleObj) return i = e.handleObj, v(e.delegateTarget).off(i.namespace ? i.origType + "." + i.namespace : i.origType, i.selector, i.handler), this; if (typeof e == "object") { for (s in e) this.off(s, n, e[s]); return this } if (n === !1 || typeof n == "function") r = n, n = t; return r === !1 && (r = et), this.each(function() { v.event.remove(this, e, r, n) }) }, bind: function(e, t, n) { return this.on(e, null, t, n) }, unbind: function(e, t) { return this.off(e, null, t) }, live: function(e, t, n) { return v(this.context).on(e, this.selector, t, n), this }, die: function(e, t) { return v(this.context).off(e, this.selector || "**", t), this }, delegate: function(e, t, n, r) { return this.on(t, e, n, r) }, undelegate: function(e, t, n) { return arguments.length === 1 ? this.off(e, "**") : this.off(t, e || "**", n) }, trigger: function(e, t) { return this.each(function() { v.event.trigger(e, t, this) }) }, triggerHandler: function(e, t) { if (this[0]) return v.event.trigger(e, t, this[0], !0) }, toggle: function(e) { var t = arguments, n = e.guid || v.guid++, r = 0, i = function(n) { var i = (v._data(this, "lastToggle" + e.guid) || 0) % r; return v._data(this, "lastToggle" + e.guid, i + 1), n.preventDefault(), t[i].apply(this, arguments) || !1 }; i.guid = n; while (r < t.length) t[r++].guid = n; return this.click(i) }, hover: function(e, t) { return this.mouseenter(e).mouseleave(t || e) } }), v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), function(e, t) { v.fn[t] = function(e, n) { return n == null && (n = e, e = null), arguments.length > 0 ? this.on(t, null, e, n) : this.trigger(t) }, Q.test(t) && (v.event.fixHooks[t] = v.event.keyHooks), G.test(t) && (v.event.fixHooks[t] = v.event.mouseHooks) }), function(e, t) { function nt(e, t, n, r) { n = n || [], t = t || g; var i, s, a, f, l = t.nodeType; if (!e || typeof e != "string") return n; if (l !== 1 && l !== 9) return []; a = o(t); if (!a && !r) if (i = R.exec(e)) if (f = i[1]) { if (l === 9) { s = t.getElementById(f); if (!s || !s.parentNode) return n; if (s.id === f) return n.push(s), n } else if (t.ownerDocument && (s = t.ownerDocument.getElementById(f)) && u(t, s) && s.id === f) return n.push(s), n } else { if (i[2]) return S.apply(n, x.call(t.getElementsByTagName(e), 0)), n; if ((f = i[3]) && Z && t.getElementsByClassName) return S.apply(n, x.call(t.getElementsByClassName(f), 0)), n } return vt(e.replace(j, "$1"), t, n, r, a) } function rt(e) { return function(t) { var n = t.nodeName.toLowerCase(); return n === "input" && t.type === e } } function it(e) { return function(t) { var n = t.nodeName.toLowerCase(); return (n === "input" || n === "button") && t.type === e } } function st(e) { return N(function(t) { return t = +t, N(function(n, r) { var i, s = e([], n.length, t), o = s.length; while (o--) n[i = s[o]] && (n[i] = !(r[i] = n[i])) }) }) } function ot(e, t, n) { if (e === t) return n; var r = e.nextSibling; while (r) { if (r === t) return -1; r = r.nextSibling } return 1 } function ut(e, t) { var n, r, s, o, u, a, f, l = L[d][e + " "]; if (l) return t ? 0 : l.slice(0); u = e, a = [], f = i.preFilter; while (u) { if (!n || (r = F.exec(u))) r && (u = u.slice(r[0].length) || u), a.push(s = []); n = !1; if (r = I.exec(u)) s.push(n = new m(r.shift())), u = u.slice(n.length), n.type = r[0].replace(j, " "); for (o in i.filter)(r = J[o].exec(u)) && (!f[o] || (r = f[o](r))) && (s.push(n = new m(r.shift())), u = u.slice(n.length), n.type = o, n.matches = r); if (!n) break } return t ? u.length : u ? nt.error(e) : L(e, a).slice(0) } function at(e, t, r) { var i = t.dir, s = r && t.dir === "parentNode", o = w++; return t.first ? function(t, n, r) { while (t = t[i]) if (s || t.nodeType === 1) return e(t, n, r) } : function(t, r, u) { if (!u) { var a, f = b + " " + o + " ", l = f + n; while (t = t[i]) if (s || t.nodeType === 1) { if ((a = t[d]) === l) return t.sizset; if (typeof a == "string" && a.indexOf(f) === 0) { if (t.sizset) return t } else { t[d] = l; if (e(t, r, u)) return t.sizset = !0, t; t.sizset = !1 } } } else while (t = t[i]) if (s || t.nodeType === 1) if (e(t, r, u)) return t } } function ft(e) { return e.length > 1 ? function(t, n, r) { var i = e.length; while (i--) if (!e[i](t, n, r)) return !1; return !0 } : e[0] } function lt(e, t, n, r, i) { var s, o = [], u = 0, a = e.length, f = t != null; for (; u < a; u++) if (s = e[u]) if (!n || n(s, r, i)) o.push(s), f && t.push(u); return o } function ct(e, t, n, r, i, s) { return r && !r[d] && (r = ct(r)), i && !i[d] && (i = ct(i, s)), N(function(s, o, u, a) { var f, l, c, h = [], p = [], d = o.length, v = s || dt(t || "*", u.nodeType ? [u] : u, []), m = e && (s || !t) ? lt(v, h, e, u, a) : v, g = n ? i || (s ? e : d || r) ? [] : o : m; n && n(m, g, u, a); if (r) { f = lt(g, p), r(f, [], u, a), l = f.length; while (l--) if (c = f[l]) g[p[l]] = !(m[p[l]] = c) } if (s) { if (i || e) { if (i) { f = [], l = g.length; while (l--)(c = g[l]) && f.push(m[l] = c); i(null, g = [], f, a) } l = g.length; while (l--)(c = g[l]) && (f = i ? T.call(s, c) : h[l]) > -1 && (s[f] = !(o[f] = c)) } } else g = lt(g === o ? g.splice(d, g.length) : g), i ? i(null, o, g, a) : S.apply(o, g) }) } function ht(e) { var t, n, r, s = e.length, o = i.relative[e[0].type], u = o || i.relative[" "], a = o ? 1 : 0, f = at(function(e) { return e === t }, u, !0), l = at(function(e) { return T.call(t, e) > -1 }, u, !0), h = [function(e, n, r) { return !o && (r || n !== c) || ((t = n).nodeType ? f(e, n, r) : l(e, n, r)) }]; for (; a < s; a++) if (n = i.relative[e[a].type]) h = [at(ft(h), n)]; else { n = i.filter[e[a].type].apply(null, e[a].matches); if (n[d]) { r = ++a; for (; r < s; r++) if (i.relative[e[r].type]) break; return ct(a > 1 && ft(h), a > 1 && e.slice(0, a - 1).join("").replace(j, "$1"), n, a < r && ht(e.slice(a, r)), r < s && ht(e = e.slice(r)), r < s && e.join("")) } h.push(n) } return ft(h) } function pt(e, t) { var r = t.length > 0, s = e.length > 0, o = function(u, a, f, l, h) { var p, d, v, m = [], y = 0, w = "0", x = u && [], T = h != null, N = c, C = u || s && i.find.TAG("*", h && a.parentNode || a), k = b += N == null ? 1 : Math.E; T && (c = a !== g && a, n = o.el); for (; (p = C[w]) != null; w++) { if (s && p) { for (d = 0; v = e[d]; d++) if (v(p, a, f)) { l.push(p); break } T && (b = k, n = ++o.el) } r && ((p = !v && p) && y--, u && x.push(p)) } y += w; if (r && w !== y) { for (d = 0; v = t[d]; d++) v(x, m, a, f); if (u) { if (y > 0) while (w--)!x[w] && !m[w] && (m[w] = E.call(l)); m = lt(m) } S.apply(l, m), T && !u && m.length > 0 && y + t.length > 1 && nt.uniqueSort(l) } return T && (b = k, c = N), x }; return o.el = 0, r ? N(o) : o } function dt(e, t, n) { var r = 0, i = t.length; for (; r < i; r++) nt(e, t[r], n); return n } function vt(e, t, n, r, s) { var o, u, f, l, c, h = ut(e), p = h.length; if (!r && h.length === 1) { u = h[0] = h[0].slice(0); if (u.length > 2 && (f = u[0]).type === "ID" && t.nodeType === 9 && !s && i.relative[u[1].type]) { t = i.find.ID(f.matches[0].replace($, ""), t, s)[0]; if (!t) return n; e = e.slice(u.shift().length) } for (o = J.POS.test(e) ? -1 : u.length - 1; o >= 0; o--) { f = u[o]; if (i.relative[l = f.type]) break; if (c = i.find[l]) if (r = c(f.matches[0].replace($, ""), z.test(u[0].type) && t.parentNode || t, s)) { u.splice(o, 1), e = r.length && u.join(""); if (!e) return S.apply(n, x.call(r, 0)), n; break } } } return a(e, h)(r, t, s, n, z.test(e)), n } function mt() {} var n, r, i, s, o, u, a, f, l, c, h = !0, p = "undefined", d = ("sizcache" + Math.random()).replace(".", ""), m = String, g = e.document, y = g.documentElement, b = 0, w = 0, E = [].pop, S = [].push, x = [].slice, T = [].indexOf || function(e) { var t = 0, n = this.length; for (; t < n; t++) if (this[t] === e) return t; return -1 }, N = function(e, t) { return e[d] = t == null || t, e }, C = function() { var e = {}, t = []; return N(function(n, r) { return t.push(n) > i.cacheLength && delete e[t.shift()], e[n + " "] = r }, e) }, k = C(), L = C(), A = C(), O = "[\\x20\\t\\r\\n\\f]", M = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", _ = M.replace("w", "w#"), D = "([*^$|!~]?=)", P = "\\[" + O + "*(" + M + ")" + O + "*(?:" + D + O + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + _ + ")|)|)" + O + "*\\]", H = ":(" + M + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + P + ")|[^:]|\\\\.)*|.*))\\)|)", B = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + O + "*((?:-\\d)?\\d*)" + O + "*\\)|)(?=[^-]|$)", j = new RegExp("^" + O + "+|((?:^|[^\\\\])(?:\\\\.)*)" + O + "+$", "g"), F = new RegExp("^" + O + "*," + O + "*"), I = new RegExp("^" + O + "*([\\x20\\t\\r\\n\\f>+~])" + O + "*"), q = new RegExp(H), R = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, U = /^:not/, z = /[\x20\t\r\n\f]*[+~]/, W = /:not\($/, X = /h\d/i, V = /input|select|textarea|button/i, $ = /\\(?!\\)/g, J = { ID: new RegExp("^#(" + M + ")"), CLASS: new RegExp("^\\.(" + M + ")"), NAME: new RegExp("^\\[name=['\"]?(" + M + ")['\"]?\\]"), TAG: new RegExp("^(" + M.replace("w", "w*") + ")"), ATTR: new RegExp("^" + P), PSEUDO: new RegExp("^" + H), POS: new RegExp(B, "i"), CHILD: new RegExp("^:(only|nth|first|last)-child(?:\\(" + O + "*(even|odd|(([+-]|)(\\d*)n|)" + O + "*(?:([+-]|)" + O + "*(\\d+)|))" + O + "*\\)|)", "i"), needsContext: new RegExp("^" + O + "*[>+~]|" + B, "i") }, K = function(e) { var t = g.createElement("div"); try { return e(t) } catch (n) { return !1 } finally { t = null } }, Q = K(function(e) { return e.appendChild(g.createComment("")), !e.getElementsByTagName("*").length }), G = K(function(e) { return e.innerHTML = "<a href='#'></a>", e.firstChild && typeof e.firstChild.getAttribute !== p && e.firstChild.getAttribute("href") === "#" }), Y = K(function(e) { e.innerHTML = "<select></select>"; var t = typeof e.lastChild.getAttribute("multiple"); return t !== "boolean" && t !== "string" }), Z = K(function(e) { return e.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>", !e.getElementsByClassName || !e.getElementsByClassName("e").length ? !1 : (e.lastChild.className = "e", e.getElementsByClassName("e").length === 2) }), et = K(function(e) { e.id = d + 0, e.innerHTML = "<a name='" + d + "'></a><div name='" + d + "'></div>", y.insertBefore(e, y.firstChild); var t = g.getElementsByName && g.getElementsByName(d).length === 2 + g.getElementsByName(d + 0).length; return r = !g.getElementById(d), y.removeChild(e), t }); try { x.call(y.childNodes, 0)[0].nodeType } catch (tt) { x = function(e) { var t, n = []; for (; t = this[e]; e++) n.push(t); return n } } nt.matches = function(e, t) { return nt(e, null, null, t) }, nt.matchesSelector = function(e, t) { return nt(t, null, null, [e]).length > 0 }, s = nt.getText = function(e) { var t, n = "", r = 0, i = e.nodeType; if (i) { if (i === 1 || i === 9 || i === 11) { if (typeof e.textContent == "string") return e.textContent; for (e = e.firstChild; e; e = e.nextSibling) n += s(e) } else if (i === 3 || i === 4) return e.nodeValue } else for (; t = e[r]; r++) n += s(t); return n }, o = nt.isXML = function(e) { var t = e && (e.ownerDocument || e).documentElement; return t ? t.nodeName !== "HTML" : !1 }, u = nt.contains = y.contains ? function(e, t) { var n = e.nodeType === 9 ? e.documentElement : e, r = t && t.parentNode; return e === r || !! (r && r.nodeType === 1 && n.contains && n.contains(r)) } : y.compareDocumentPosition ? function(e, t) { return t && !! (e.compareDocumentPosition(t) & 16) } : function(e, t) { while (t = t.parentNode) if (t === e) return !0; return !1 }, nt.attr = function(e, t) { var n, r = o(e); return r || (t = t.toLowerCase()), (n = i.attrHandle[t]) ? n(e) : r || Y ? e.getAttribute(t) : (n = e.getAttributeNode(t), n ? typeof e[t] == "boolean" ? e[t] ? t : null : n.specified ? n.value : null : null) }, i = nt.selectors = { cacheLength: 50, createPseudo: N, match: J, attrHandle: G ? {} : { href: function(e) { return e.getAttribute("href", 2) }, type: function(e) { return e.getAttribute("type") } }, find: { ID: r ? function(e, t, n) { if (typeof t.getElementById !== p && !n) { var r = t.getElementById(e); return r && r.parentNode ? [r] : [] } } : function(e, n, r) { if (typeof n.getElementById !== p && !r) { var i = n.getElementById(e); return i ? i.id === e || typeof i.getAttributeNode !== p && i.getAttributeNode("id").value === e ? [i] : t : [] } }, TAG: Q ? function(e, t) { if (typeof t.getElementsByTagName !== p) return t.getElementsByTagName(e) } : function(e, t) { var n = t.getElementsByTagName(e); if (e === "*") { var r, i = [], s = 0; for (; r = n[s]; s++) r.nodeType === 1 && i.push(r); return i } return n }, NAME: et && function(e, t) { if (typeof t.getElementsByName !== p) return t.getElementsByName(name) }, CLASS: Z && function(e, t, n) { if (typeof t.getElementsByClassName !== p && !n) return t.getElementsByClassName(e) } }, relative: { ">": { dir: "parentNode", first: !0 }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: !0 }, "~": { dir: "previousSibling" } }, preFilter: { ATTR: function(e) { return e[1] = e[1].replace($, ""), e[3] = (e[4] || e[5] || "").replace($, ""), e[2] === "~=" && (e[3] = " " + e[3] + " "), e.slice(0, 4) }, CHILD: function(e) { return e[1] = e[1].toLowerCase(), e[1] === "nth" ? (e[2] || nt.error(e[0]), e[3] = +(e[3] ? e[4] + (e[5] || 1) : 2 * (e[2] === "even" || e[2] === "odd")), e[4] = +(e[6] + e[7] || e[2] === "odd")) : e[2] && nt.error(e[0]), e }, PSEUDO: function(e) { var t, n; if (J.CHILD.test(e[0])) return null; if (e[3]) e[2] = e[3]; else if (t = e[4]) q.test(t) && (n = ut(t, !0)) && (n = t.indexOf(")", t.length - n) - t.length) && (t = t.slice(0, n), e[0] = e[0].slice(0, n)), e[2] = t; return e.slice(0, 3) } }, filter: { ID: r ? function(e) { return e = e.replace($, ""), function(t) { return t.getAttribute("id") === e } } : function(e) { return e = e.replace($, ""), function(t) { var n = typeof t.getAttributeNode !== p && t.getAttributeNode("id"); return n && n.value === e } }, TAG: function(e) { return e === "*" ? function() { return !0 } : (e = e.replace($, "").toLowerCase(), function(t) { return t.nodeName && t.nodeName.toLowerCase() === e }) }, CLASS: function(e) { var t = k[d][e + " "]; return t || (t = new RegExp("(^|" + O + ")" + e + "(" + O + "|$)")) && k(e, function(e) { return t.test(e.className || typeof e.getAttribute !== p && e.getAttribute("class") || "") }) }, ATTR: function(e, t, n) { return function(r, i) { var s = nt.attr(r, e); return s == null ? t === "!=" : t ? (s += "", t === "=" ? s === n : t === "!=" ? s !== n : t === "^=" ? n && s.indexOf(n) === 0 : t === "*=" ? n && s.indexOf(n) > -1 : t === "$=" ? n && s.substr(s.length - n.length) === n : t === "~=" ? (" " + s + " ").indexOf(n) > -1 : t === "|=" ? s === n || s.substr(0, n.length + 1) === n + "-" : !1) : !0 } }, CHILD: function(e, t, n, r) { return e === "nth" ? function(e) { var t, i, s = e.parentNode; if (n === 1 && r === 0) return !0; if (s) { i = 0; for (t = s.firstChild; t; t = t.nextSibling) if (t.nodeType === 1) { i++; if (e === t) break } } return i -= r, i === n || i % n === 0 && i / n >= 0 } : function(t) { var n = t; switch (e) { case "only": case "first": while (n = n.previousSibling) if (n.nodeType === 1) return !1; if (e === "first") return !0; n = t; case "last": while (n = n.nextSibling) if (n.nodeType === 1) return !1; return !0 } } }, PSEUDO: function(e, t) { var n, r = i.pseudos[e] || i.setFilters[e.toLowerCase()] || nt.error("unsupported pseudo: " + e); return r[d] ? r(t) : r.length > 1 ? (n = [e, e, "", t], i.setFilters.hasOwnProperty(e.toLowerCase()) ? N(function(e, n) { var i, s = r(e, t), o = s.length; while (o--) i = T.call(e, s[o]), e[i] = !(n[i] = s[o]) }) : function(e) { return r(e, 0, n) }) : r } }, pseudos: { not: N(function(e) { var t = [], n = [], r = a(e.replace(j, "$1")); return r[d] ? N(function(e, t, n, i) { var s, o = r(e, null, i, []), u = e.length; while (u--) if (s = o[u]) e[u] = !(t[u] = s) }) : function(e, i, s) { return t[0] = e, r(t, null, s, n), !n.pop() } }), has: N(function(e) { return function(t) { return nt(e, t).length > 0 } }), contains: N(function(e) { return function(t) { return (t.textContent || t.innerText || s(t)).indexOf(e) > -1 } }), enabled: function(e) { return e.disabled === !1 }, disabled: function(e) { return e.disabled === !0 }, checked: function(e) { var t = e.nodeName.toLowerCase(); return t === "input" && !! e.checked || t === "option" && !! e.selected }, selected: function(e) { return e.parentNode && e.parentNode.selectedIndex, e.selected === !0 }, parent: function(e) { return !i.pseudos.empty(e) }, empty: function(e) { var t; e = e.firstChild; while (e) { if (e.nodeName > "@" || (t = e.nodeType) === 3 || t === 4) return !1; e = e.nextSibling } return !0 }, header: function(e) { return X.test(e.nodeName) }, text: function(e) { var t, n; return e.nodeName.toLowerCase() === "input" && (t = e.type) === "text" && ((n = e.getAttribute("type")) == null || n.toLowerCase() === t) }, radio: rt("radio"), checkbox: rt("checkbox"), file: rt("file"), password: rt("password"), image: rt("image"), submit: it("submit"), reset: it("reset"), button: function(e) { var t = e.nodeName.toLowerCase(); return t === "input" && e.type === "button" || t === "button" }, input: function(e) { return V.test(e.nodeName) }, focus: function(e) { var t = e.ownerDocument; return e === t.activeElement && (!t.hasFocus || t.hasFocus()) && !! (e.type || e.href || ~e.tabIndex) }, active: function(e) { return e === e.ownerDocument.activeElement }, first: st(function() { return [0] }), last: st(function(e, t) { return [t - 1] }), eq: st(function(e, t, n) { return [n < 0 ? n + t : n] }), even: st(function(e, t) { for (var n = 0; n < t; n += 2) e.push(n); return e }), odd: st(function(e, t) { for (var n = 1; n < t; n += 2) e.push(n); return e }), lt: st(function(e, t, n) { for (var r = n < 0 ? n + t : n; --r >= 0;) e.push(r); return e }), gt: st(function(e, t, n) { for (var r = n < 0 ? n + t : n; ++r < t;) e.push(r); return e }) } }, f = y.compareDocumentPosition ? function(e, t) { return e === t ? (l = !0, 0) : (!e.compareDocumentPosition || !t.compareDocumentPosition ? e.compareDocumentPosition : e.compareDocumentPosition(t) & 4) ? -1 : 1 } : function(e, t) { if (e === t) return l = !0, 0; if (e.sourceIndex && t.sourceIndex) return e.sourceIndex - t.sourceIndex; var n, r, i = [], s = [], o = e.parentNode, u = t.parentNode, a = o; if (o === u) return ot(e, t); if (!o) return -1; if (!u) return 1; while (a) i.unshift(a), a = a.parentNode; a = u; while (a) s.unshift(a), a = a.parentNode; n = i.length, r = s.length; for (var f = 0; f < n && f < r; f++) if (i[f] !== s[f]) return ot(i[f], s[f]); return f === n ? ot(e, s[f], -1) : ot(i[f], t, 1) }, [0, 0].sort(f), h = !l, nt.uniqueSort = function(e) { var t, n = [], r = 1, i = 0; l = h, e.sort(f); if (l) { for (; t = e[r]; r++) t === e[r - 1] && (i = n.push(r)); while (i--) e.splice(n[i], 1) } return e }, nt.error = function(e) { throw new Error("Syntax error, unrecognized expression: " + e) }, a = nt.compile = function(e, t) { var n, r = [], i = [], s = A[d][e + " "]; if (!s) { t || (t = ut(e)), n = t.length; while (n--) s = ht(t[n]), s[d] ? r.push(s) : i.push(s); s = A(e, pt(i, r)) } return s }, g.querySelectorAll && function() { var e, t = vt, n = /'|\\/g, r = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, i = [":focus"], s = [":active"], u = y.matchesSelector || y.mozMatchesSelector || y.webkitMatchesSelector || y.oMatchesSelector || y.msMatchesSelector; K(function(e) { e.innerHTML = "<select><option selected=''></option></select>", e.querySelectorAll("[selected]").length || i.push("\\[" + O + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)"), e.querySelectorAll(":checked").length || i.push(":checked") }), K(function(e) { e.innerHTML = "<p test=''></p>", e.querySelectorAll("[test^='']").length && i.push("[*^$]=" + O + "*(?:\"\"|'')"), e.innerHTML = "<input type='hidden'/>", e.querySelectorAll(":enabled").length || i.push(":enabled", ":disabled") }), i = new RegExp(i.join("|")), vt = function(e, r, s, o, u) { if (!o && !u && !i.test(e)) { var a, f, l = !0, c = d, h = r, p = r.nodeType === 9 && e; if (r.nodeType === 1 && r.nodeName.toLowerCase() !== "object") { a = ut(e), (l = r.getAttribute("id")) ? c = l.replace(n, "\\$&") : r.setAttribute("id", c), c = "[id='" + c + "'] ", f = a.length; while (f--) a[f] = c + a[f].join(""); h = z.test(e) && r.parentNode || r, p = a.join(",") } if (p) try { return S.apply(s, x.call(h.querySelectorAll(p), 0)), s } catch (v) {} finally { l || r.removeAttribute("id") } } return t(e, r, s, o, u) }, u && (K(function(t) { e = u.call(t, "div"); try { u.call(t, "[test!='']:sizzle"), s.push("!=", H) } catch (n) {} }), s = new RegExp(s.join("|")), nt.matchesSelector = function(t, n) { n = n.replace(r, "='$1']"); if (!o(t) && !s.test(n) && !i.test(n)) try { var a = u.call(t, n); if (a || e || t.document && t.document.nodeType !== 11) return a } catch (f) {} return nt(n, null, null, [t]).length > 0 }) }(), i.pseudos.nth = i.pseudos.eq, i.filters = mt.prototype = i.pseudos, i.setFilters = new mt, nt.attr = v.attr, v.find = nt, v.expr = nt.selectors, v.expr[":"] = v.expr.pseudos, v.unique = nt.uniqueSort, v.text = nt.getText, v.isXMLDoc = nt.isXML, v.contains = nt.contains }(e); var nt = /Until$/, rt = /^(?:parents|prev(?:Until|All))/, it = /^.[^:#\[\.,]*$/, st = v.expr.match.needsContext, ot = { children: !0, contents: !0, next: !0, prev: !0 }; v.fn.extend({ find: function(e) { var t, n, r, i, s, o, u = this; if (typeof e != "string") return v(e).filter(function() { for (t = 0, n = u.length; t < n; t++) if (v.contains(u[t], this)) return !0 }); o = this.pushStack("", "find", e); for (t = 0, n = this.length; t < n; t++) { r = o.length, v.find(e, this[t], o); if (t > 0) for (i = r; i < o.length; i++) for (s = 0; s < r; s++) if (o[s] === o[i]) { o.splice(i--, 1); break } } return o }, has: function(e) { var t, n = v(e, this), r = n.length; return this.filter(function() { for (t = 0; t < r; t++) if (v.contains(this, n[t])) return !0 }) }, not: function(e) { return this.pushStack(ft(this, e, !1), "not", e) }, filter: function(e) { return this.pushStack(ft(this, e, !0), "filter", e) }, is: function(e) { return !!e && (typeof e == "string" ? st.test(e) ? v(e, this.context).index(this[0]) >= 0 : v.filter(e, this).length > 0 : this.filter(e).length > 0) }, closest: function(e, t) { var n, r = 0, i = this.length, s = [], o = st.test(e) || typeof e != "string" ? v(e, t || this.context) : 0; for (; r < i; r++) { n = this[r]; while (n && n.ownerDocument && n !== t && n.nodeType !== 11) { if (o ? o.index(n) > -1 : v.find.matchesSelector(n, e)) { s.push(n); break } n = n.parentNode } } return s = s.length > 1 ? v.unique(s) : s, this.pushStack(s, "closest", e) }, index: function(e) { return e ? typeof e == "string" ? v.inArray(this[0], v(e)) : v.inArray(e.jquery ? e[0] : e, this) : this[0] && this[0].parentNode ? this.prevAll().length : -1 }, add: function(e, t) { var n = typeof e == "string" ? v(e, t) : v.makeArray(e && e.nodeType ? [e] : e), r = v.merge(this.get(), n); return this.pushStack(ut(n[0]) || ut(r[0]) ? r : v.unique(r)) }, addBack: function(e) { return this.add(e == null ? this.prevObject : this.prevObject.filter(e)) } }), v.fn.andSelf = v.fn.addBack, v.each({ parent: function(e) { var t = e.parentNode; return t && t.nodeType !== 11 ? t : null }, parents: function(e) { return v.dir(e, "parentNode") }, parentsUntil: function(e, t, n) { return v.dir(e, "parentNode", n) }, next: function(e) { return at(e, "nextSibling") }, prev: function(e) { return at(e, "previousSibling") }, nextAll: function(e) { return v.dir(e, "nextSibling") }, prevAll: function(e) { return v.dir(e, "previousSibling") }, nextUntil: function(e, t, n) { return v.dir(e, "nextSibling", n) }, prevUntil: function(e, t, n) { return v.dir(e, "previousSibling", n) }, siblings: function(e) { return v.sibling((e.parentNode || {}).firstChild, e) }, children: function(e) { return v.sibling(e.firstChild) }, contents: function(e) { return v.nodeName(e, "iframe") ? e.contentDocument || e.contentWindow.document : v.merge([], e.childNodes) } }, function(e, t) { v.fn[e] = function(n, r) { var i = v.map(this, t, n); return nt.test(e) || (r = n), r && typeof r == "string" && (i = v.filter(r, i)), i = this.length > 1 && !ot[e] ? v.unique(i) : i, this.length > 1 && rt.test(e) && (i = i.reverse()), this.pushStack(i, e, l.call(arguments).join(",")) } }), v.extend({ filter: function(e, t, n) { return n && (e = ":not(" + e + ")"), t.length === 1 ? v.find.matchesSelector(t[0], e) ? [t[0]] : [] : v.find.matches(e, t) }, dir: function(e, n, r) { var i = [], s = e[n]; while (s && s.nodeType !== 9 && (r === t || s.nodeType !== 1 || !v(s).is(r))) s.nodeType === 1 && i.push(s), s = s[n]; return i }, sibling: function(e, t) { var n = []; for (; e; e = e.nextSibling) e.nodeType === 1 && e !== t && n.push(e); return n } }); var ct = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", ht = / jQuery\d+="(?:null|\d+)"/g, pt = /^\s+/, dt = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, vt = /<([\w:]+)/, mt = /<tbody/i, gt = /<|&#?\w+;/, yt = /<(?:script|style|link)/i, bt = /<(?:script|object|embed|option|style)/i, wt = new RegExp("<(?:" + ct + ")[\\s/>]", "i"), Et = /^(?:checkbox|radio)$/, St = /checked\s*(?:[^=]|=\s*.checked.)/i, xt = /\/(java|ecma)script/i, Tt = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, Nt = { option: [1, "<select multiple='multiple'>", "</select>"], legend: [1, "<fieldset>", "</fieldset>"], thead: [1, "<table>", "</table>"], tr: [2, "<table><tbody>", "</tbody></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], area: [1, "<map>", "</map>"], _default: [0, "", ""] }, Ct = lt(i), kt = Ct.appendChild(i.createElement("div")); Nt.optgroup = Nt.option, Nt.tbody = Nt.tfoot = Nt.colgroup = Nt.caption = Nt.thead, Nt.th = Nt.td, v.support.htmlSerialize || (Nt._default = [1, "X<div>", "</div>"]), v.fn.extend({ text: function(e) { return v.access(this, function(e) { return e === t ? v.text(this) : this.empty().append((this[0] && this[0].ownerDocument || i).createTextNode(e)) }, null, e, arguments.length) }, wrapAll: function(e) { if (v.isFunction(e)) return this.each(function(t) { v(this).wrapAll(e.call(this, t)) }); if (this[0]) { var t = v(e, this[0].ownerDocument).eq(0).clone(!0); this[0].parentNode && t.insertBefore(this[0]), t.map(function() { var e = this; while (e.firstChild && e.firstChild.nodeType === 1) e = e.firstChild; return e }).append(this) } return this }, wrapInner: function(e) { return v.isFunction(e) ? this.each(function(t) { v(this).wrapInner(e.call(this, t)) }) : this.each(function() { var t = v(this), n = t.contents(); n.length ? n.wrapAll(e) : t.append(e) }) }, wrap: function(e) { var t = v.isFunction(e); return this.each(function(n) { v(this).wrapAll(t ? e.call(this, n) : e) }) }, unwrap: function() { return this.parent().each(function() { v.nodeName(this, "body") || v(this).replaceWith(this.childNodes) }).end() }, append: function() { return this.domManip(arguments, !0, function(e) { (this.nodeType === 1 || this.nodeType === 11) && this.appendChild(e) }) }, prepend: function() { return this.domManip(arguments, !0, function(e) { (this.nodeType === 1 || this.nodeType === 11) && this.insertBefore(e, this.firstChild) }) }, before: function() { if (!ut(this[0])) return this.domManip(arguments, !1, function(e) { this.parentNode.insertBefore(e, this) }); if (arguments.length) { var e = v.clean(arguments); return this.pushStack(v.merge(e, this), "before", this.selector) } }, after: function() { if (!ut(this[0])) return this.domManip(arguments, !1, function(e) { this.parentNode.insertBefore(e, this.nextSibling) }); if (arguments.length) { var e = v.clean(arguments); return this.pushStack(v.merge(this, e), "after", this.selector) } }, remove: function(e, t) { var n, r = 0; for (; (n = this[r]) != null; r++) if (!e || v.filter(e, [n]).length)!t && n.nodeType === 1 && (v.cleanData(n.getElementsByTagName("*")), v.cleanData([n])), n.parentNode && n.parentNode.removeChild(n); return this }, empty: function() { var e, t = 0; for (; (e = this[t]) != null; t++) { e.nodeType === 1 && v.cleanData(e.getElementsByTagName("*")); while (e.firstChild) e.removeChild(e.firstChild) } return this }, clone: function(e, t) { return e = e == null ? !1 : e, t = t == null ? e : t, this.map(function() { return v.clone(this, e, t) }) }, html: function(e) { return v.access(this, function(e) { var n = this[0] || {}, r = 0, i = this.length; if (e === t) return n.nodeType === 1 ? n.innerHTML.replace(ht, "") : t; if (typeof e == "string" && !yt.test(e) && (v.support.htmlSerialize || !wt.test(e)) && (v.support.leadingWhitespace || !pt.test(e)) && !Nt[(vt.exec(e) || ["", ""])[1].toLowerCase()]) { e = e.replace(dt, "<$1></$2>"); try { for (; r < i; r++) n = this[r] || {}, n.nodeType === 1 && (v.cleanData(n.getElementsByTagName("*")), n.innerHTML = e); n = 0 } catch (s) {} } n && this.empty().append(e) }, null, e, arguments.length) }, replaceWith: function(e) { return ut(this[0]) ? this.length ? this.pushStack(v(v.isFunction(e) ? e() : e), "replaceWith", e) : this : v.isFunction(e) ? this.each(function(t) { var n = v(this), r = n.html(); n.replaceWith(e.call(this, t, r)) }) : (typeof e != "string" && (e = v(e).detach()), this.each(function() { var t = this.nextSibling, n = this.parentNode; v(this).remove(), t ? v(t).before(e) : v(n).append(e) })) }, detach: function(e) { return this.remove(e, !0) }, domManip: function(e, n, r) { e = [].concat.apply([], e); var i, s, o, u, a = 0, f = e[0], l = [], c = this.length; if (!v.support.checkClone && c > 1 && typeof f == "string" && St.test(f)) return this.each(function() { v(this).domManip(e, n, r) }); if (v.isFunction(f)) return this.each(function(i) { var s = v(this); e[0] = f.call(this, i, n ? s.html() : t), s.domManip(e, n, r) }); if (this[0]) { i = v.buildFragment(e, this, l), o = i.fragment, s = o.firstChild, o.childNodes.length === 1 && (o = s); if (s) { n = n && v.nodeName(s, "tr"); for (u = i.cacheable || c - 1; a < c; a++) r.call(n && v.nodeName(this[a], "table") ? Lt(this[a], "tbody") : this[a], a === u ? o : v.clone(o, !0, !0)) } o = s = null, l.length && v.each(l, function(e, t) { t.src ? v.ajax ? v.ajax({ url: t.src, type: "GET", dataType: "script", async: !1, global: !1, "throws": !0 }) : v.error("no ajax") : v.globalEval((t.text || t.textContent || t.innerHTML || "").replace(Tt, "")), t.parentNode && t.parentNode.removeChild(t) }) } return this } }), v.buildFragment = function(e, n, r) { var s, o, u, a = e[0]; return n = n || i, n = !n.nodeType && n[0] || n, n = n.ownerDocument || n, e.length === 1 && typeof a == "string" && a.length < 512 && n === i && a.charAt(0) === "<" && !bt.test(a) && (v.support.checkClone || !St.test(a)) && (v.support.html5Clone || !wt.test(a)) && (o = !0, s = v.fragments[a], u = s !== t), s || (s = n.createDocumentFragment(), v.clean(e, n, s, r), o && (v.fragments[a] = u && s)), { fragment: s, cacheable: o } }, v.fragments = {}, v.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function(e, t) { v.fn[e] = function(n) { var r, i = 0, s = [], o = v(n), u = o.length, a = this.length === 1 && this[0].parentNode; if ((a == null || a && a.nodeType === 11 && a.childNodes.length === 1) && u === 1) return o[t](this[0]), this; for (; i < u; i++) r = (i > 0 ? this.clone(!0) : this).get(), v(o[i])[t](r), s = s.concat(r); return this.pushStack(s, e, o.selector) } }), v.extend({ clone: function(e, t, n) { var r, i, s, o; v.support.html5Clone || v.isXMLDoc(e) || !wt.test("<" + e.nodeName + ">") ? o = e.cloneNode(!0) : (kt.innerHTML = e.outerHTML, kt.removeChild(o = kt.firstChild)); if ((!v.support.noCloneEvent || !v.support.noCloneChecked) && (e.nodeType === 1 || e.nodeType === 11) && !v.isXMLDoc(e)) { Ot(e, o), r = Mt(e), i = Mt(o); for (s = 0; r[s]; ++s) i[s] && Ot(r[s], i[s]) } if (t) { At(e, o); if (n) { r = Mt(e), i = Mt(o); for (s = 0; r[s]; ++s) At(r[s], i[s]) } } return r = i = null, o }, clean: function(e, t, n, r) { var s, o, u, a, f, l, c, h, p, d, m, g, y = t === i && Ct, b = []; if (!t || typeof t.createDocumentFragment == "undefined") t = i; for (s = 0; (u = e[s]) != null; s++) { typeof u == "number" && (u += ""); if (!u) continue; if (typeof u == "string") if (!gt.test(u)) u = t.createTextNode(u); else { y = y || lt(t), c = t.createElement("div"), y.appendChild(c), u = u.replace(dt, "<$1></$2>"), a = (vt.exec(u) || ["", ""])[1].toLowerCase(), f = Nt[a] || Nt._default, l = f[0], c.innerHTML = f[1] + u + f[2]; while (l--) c = c.lastChild; if (!v.support.tbody) { h = mt.test(u), p = a === "table" && !h ? c.firstChild && c.firstChild.childNodes : f[1] === "<table>" && !h ? c.childNodes : []; for (o = p.length - 1; o >= 0; --o) v.nodeName(p[o], "tbody") && !p[o].childNodes.length && p[o].parentNode.removeChild(p[o]) }!v.support.leadingWhitespace && pt.test(u) && c.insertBefore(t.createTextNode(pt.exec(u)[0]), c.firstChild), u = c.childNodes, c.parentNode.removeChild(c) } u.nodeType ? b.push(u) : v.merge(b, u) } c && (u = c = y = null); if (!v.support.appendChecked) for (s = 0; (u = b[s]) != null; s++) v.nodeName(u, "input") ? _t(u) : typeof u.getElementsByTagName != "undefined" && v.grep(u.getElementsByTagName("input"), _t); if (n) { m = function(e) { if (!e.type || xt.test(e.type)) return r ? r.push(e.parentNode ? e.parentNode.removeChild(e) : e) : n.appendChild(e) }; for (s = 0; (u = b[s]) != null; s++) if (!v.nodeName(u, "script") || !m(u)) n.appendChild(u), typeof u.getElementsByTagName != "undefined" && (g = v.grep(v.merge([], u.getElementsByTagName("script")), m), b.splice.apply(b, [s + 1, 0].concat(g)), s += g.length) } return b }, cleanData: function(e, t) { var n, r, i, s, o = 0, u = v.expando, a = v.cache, f = v.support.deleteExpando, l = v.event.special; for (; (i = e[o]) != null; o++) if (t || v.acceptData(i)) { r = i[u], n = r && a[r]; if (n) { if (n.events) for (s in n.events) l[s] ? v.event.remove(i, s) : v.removeEvent(i, s, n.handle); a[r] && (delete a[r], f ? delete i[u] : i.removeAttribute ? i.removeAttribute(u) : i[u] = null, v.deletedIds.push(r)) } } } }), function() { var e, t; v.uaMatch = function(e) { e = e.toLowerCase(); var t = /(chrome)[ \/]([\w.]+)/.exec(e) || /(webkit)[ \/]([\w.]+)/.exec(e) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e) || /(msie) ([\w.]+)/.exec(e) || e.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e) || []; return { browser: t[1] || "", version: t[2] || "0" } }, e = v.uaMatch(o.userAgent), t = {}, e.browser && (t[e.browser] = !0, t.version = e.version), t.chrome ? t.webkit = !0 : t.webkit && (t.safari = !0), v.browser = t, v.sub = function() { function e(t, n) { return new e.fn.init(t, n) } v.extend(!0, e, this), e.superclass = this, e.fn = e.prototype = this(), e.fn.constructor = e, e.sub = this.sub, e.fn.init = function(r, i) { return i && i instanceof v && !(i instanceof e) && (i = e(i)), v.fn.init.call(this, r, i, t) }, e.fn.init.prototype = e.fn; var t = e(i); return e } }(); var Dt, Pt, Ht, Bt = /alpha\([^)]*\)/i, jt = /opacity=([^)]*)/, Ft = /^(top|right|bottom|left)$/, It = /^(none|table(?!-c[ea]).+)/, qt = /^margin/, Rt = new RegExp("^(" + m + ")(.*)$", "i"), Ut = new RegExp("^(" + m + ")(?!px)[a-z%]+$", "i"), zt = new RegExp("^([-+])=(" + m + ")", "i"), Wt = { BODY: "block" }, Xt = { position: "absolute", visibility: "hidden", display: "block" }, Vt = { letterSpacing: 0, fontWeight: 400 }, $t = ["Top", "Right", "Bottom", "Left"], Jt = ["Webkit", "O", "Moz", "ms"], Kt = v.fn.toggle; v.fn.extend({ css: function(e, n) { return v.access(this, function(e, n, r) { return r !== t ? v.style(e, n, r) : v.css(e, n) }, e, n, arguments.length > 1) }, show: function() { return Yt(this, !0) }, hide: function() { return Yt(this) }, toggle: function(e, t) { var n = typeof e == "boolean"; return v.isFunction(e) && v.isFunction(t) ? Kt.apply(this, arguments) : this.each(function() { (n ? e : Gt(this)) ? v(this).show() : v(this).hide() }) } }), v.extend({ cssHooks: { opacity: { get: function(e, t) { if (t) { var n = Dt(e, "opacity"); return n === "" ? "1" : n } } } }, cssNumber: { fillOpacity: !0, fontWeight: !0, lineHeight: !0, opacity: !0, orphans: !0, widows: !0, zIndex: !0, zoom: !0 }, cssProps: { "float": v.support.cssFloat ? "cssFloat" : "styleFloat" }, style: function(e, n, r, i) { if (!e || e.nodeType === 3 || e.nodeType === 8 || !e.style) return; var s, o, u, a = v.camelCase(n), f = e.style; n = v.cssProps[a] || (v.cssProps[a] = Qt(f, a)), u = v.cssHooks[n] || v.cssHooks[a]; if (r === t) return u && "get" in u && (s = u.get(e, !1, i)) !== t ? s : f[n]; o = typeof r, o === "string" && (s = zt.exec(r)) && (r = (s[1] + 1) * s[2] + parseFloat(v.css(e, n)), o = "number"); if (r == null || o === "number" && isNaN(r)) return; o === "number" && !v.cssNumber[a] && (r += "px"); if (!u || !("set" in u) || (r = u.set(e, r, i)) !== t) try { f[n] = r } catch (l) {} }, css: function(e, n, r, i) { var s, o, u, a = v.camelCase(n); return n = v.cssProps[a] || (v.cssProps[a] = Qt(e.style, a)), u = v.cssHooks[n] || v.cssHooks[a], u && "get" in u && (s = u.get(e, !0, i)), s === t && (s = Dt(e, n)), s === "normal" && n in Vt && (s = Vt[n]), r || i !== t ? (o = parseFloat(s), r || v.isNumeric(o) ? o || 0 : s) : s }, swap: function(e, t, n) { var r, i, s = {}; for (i in t) s[i] = e.style[i], e.style[i] = t[i]; r = n.call(e); for (i in t) e.style[i] = s[i]; return r } }), e.getComputedStyle ? Dt = function(t, n) { var r, i, s, o, u = e.getComputedStyle(t, null), a = t.style; return u && (r = u.getPropertyValue(n) || u[n], r === "" && !v.contains(t.ownerDocument, t) && (r = v.style(t, n)), Ut.test(r) && qt.test(n) && (i = a.width, s = a.minWidth, o = a.maxWidth, a.minWidth = a.maxWidth = a.width = r, r = u.width, a.width = i, a.minWidth = s, a.maxWidth = o)), r } : i.documentElement.currentStyle && (Dt = function(e, t) { var n, r, i = e.currentStyle && e.currentStyle[t], s = e.style; return i == null && s && s[t] && (i = s[t]), Ut.test(i) && !Ft.test(t) && (n = s.left, r = e.runtimeStyle && e.runtimeStyle.left, r && (e.runtimeStyle.left = e.currentStyle.left), s.left = t === "fontSize" ? "1em" : i, i = s.pixelLeft + "px", s.left = n, r && (e.runtimeStyle.left = r)), i === "" ? "auto" : i }), v.each(["height", "width"], function(e, t) { v.cssHooks[t] = { get: function(e, n, r) { if (n) return e.offsetWidth === 0 && It.test(Dt(e, "display")) ? v.swap(e, Xt, function() { return tn(e, t, r) }) : tn(e, t, r) }, set: function(e, n, r) { return Zt(e, n, r ? en(e, t, r, v.support.boxSizing && v.css(e, "boxSizing") === "border-box") : 0) } } }), v.support.opacity || (v.cssHooks.opacity = { get: function(e, t) { return jt.test((t && e.currentStyle ? e.currentStyle.filter : e.style.filter) || "") ? .01 * parseFloat(RegExp.$1) + "" : t ? "1" : "" }, set: function(e, t) { var n = e.style, r = e.currentStyle, i = v.isNumeric(t) ? "alpha(opacity=" + t * 100 + ")" : "", s = r && r.filter || n.filter || ""; n.zoom = 1; if (t >= 1 && v.trim(s.replace(Bt, "")) === "" && n.removeAttribute) { n.removeAttribute("filter"); if (r && !r.filter) return } n.filter = Bt.test(s) ? s.replace(Bt, i) : s + " " + i } }), v(function() { v.support.reliableMarginRight || (v.cssHooks.marginRight = { get: function(e, t) { return v.swap(e, { display: "inline-block" }, function() { if (t) return Dt(e, "marginRight") }) } }), !v.support.pixelPosition && v.fn.position && v.each(["top", "left"], function(e, t) { v.cssHooks[t] = { get: function(e, n) { if (n) { var r = Dt(e, t); return Ut.test(r) ? v(e).position()[t] + "px" : r } } } }) }), v.expr && v.expr.filters && (v.expr.filters.hidden = function(e) { return e.offsetWidth === 0 && e.offsetHeight === 0 || !v.support.reliableHiddenOffsets && (e.style && e.style.display || Dt(e, "display")) === "none" }, v.expr.filters.visible = function(e) { return !v.expr.filters.hidden(e) }), v.each({ margin: "", padding: "", border: "Width" }, function(e, t) { v.cssHooks[e + t] = { expand: function(n) { var r, i = typeof n == "string" ? n.split(" ") : [n], s = {}; for (r = 0; r < 4; r++) s[e + $t[r] + t] = i[r] || i[r - 2] || i[0]; return s } }, qt.test(e) || (v.cssHooks[e + t].set = Zt) }); var rn = /%20/g, sn = /\[\]$/, on = /\r?\n/g, un = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, an = /^(?:select|textarea)/i; v.fn.extend({ serialize: function() { return v.param(this.serializeArray()) }, serializeArray: function() { return this.map(function() { return this.elements ? v.makeArray(this.elements) : this }).filter(function() { return this.name && !this.disabled && (this.checked || an.test(this.nodeName) || un.test(this.type)) }).map(function(e, t) { var n = v(this).val(); return n == null ? null : v.isArray(n) ? v.map(n, function(e, n) { return { name: t.name, value: e.replace(on, "\r\n") } }) : { name: t.name, value: n.replace(on, "\r\n") } }).get() } }), v.param = function(e, n) { var r, i = [], s = function(e, t) { t = v.isFunction(t) ? t() : t == null ? "" : t, i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t) }; n === t && (n = v.ajaxSettings && v.ajaxSettings.traditional); if (v.isArray(e) || e.jquery && !v.isPlainObject(e)) v.each(e, function() { s(this.name, this.value) }); else for (r in e) fn(r, e[r], n, s); return i.join("&").replace(rn, "+") }; var ln, cn, hn = /#.*$/, pn = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, dn = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, vn = /^(?:GET|HEAD)$/, mn = /^\/\//, gn = /\?/, yn = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, bn = /([?&])_=[^&]*/, wn = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, En = v.fn.load, Sn = {}, xn = {}, Tn = ["*/"] + ["*"]; try { cn = s.href } catch (Nn) { cn = i.createElement("a"), cn.href = "", cn = cn.href } ln = wn.exec(cn.toLowerCase()) || [], v.fn.load = function(e, n, r) { if (typeof e != "string" && En) return En.apply(this, arguments); if (!this.length) return this; var i, s, o, u = this, a = e.indexOf(" "); return a >= 0 && (i = e.slice(a, e.length), e = e.slice(0, a)), v.isFunction(n) ? (r = n, n = t) : n && typeof n == "object" && (s = "POST"), v.ajax({ url: e, type: s, dataType: "html", data: n, complete: function(e, t) { r && u.each(r, o || [e.responseText, t, e]) } }).done(function(e) { o = arguments, u.html(i ? v("<div>").append(e.replace(yn, "")).find(i) : e) }), this }, v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(e, t) { v.fn[t] = function(e) { return this.on(t, e) } }), v.each(["get", "post"], function(e, n) { v[n] = function(e, r, i, s) { return v.isFunction(r) && (s = s || i, i = r, r = t), v.ajax({ type: n, url: e, data: r, success: i, dataType: s }) } }), v.extend({ getScript: function(e, n) { return v.get(e, t, n, "script") }, getJSON: function(e, t, n) { return v.get(e, t, n, "json") }, ajaxSetup: function(e, t) { return t ? Ln(e, v.ajaxSettings) : (t = e, e = v.ajaxSettings), Ln(e, t), e }, ajaxSettings: { url: cn, isLocal: dn.test(ln[1]), global: !0, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: !0, async: !0, accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": Tn }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, converters: { "* text": e.String, "text html": !0, "text json": v.parseJSON, "text xml": v.parseXML }, flatOptions: { context: !0, url: !0 } }, ajaxPrefilter: Cn(Sn), ajaxTransport: Cn(xn), ajax: function(e, n) { function T(e, n, s, a) { var l, y, b, w, S, T = n; if (E === 2) return; E = 2, u && clearTimeout(u), o = t, i = a || "", x.readyState = e > 0 ? 4 : 0, s && (w = An(c, x, s)); if (e >= 200 && e < 300 || e === 304) c.ifModified && (S = x.getResponseHeader("Last-Modified"), S && (v.lastModified[r] = S), S = x.getResponseHeader("Etag"), S && (v.etag[r] = S)), e === 304 ? (T = "notmodified", l = !0) : (l = On(c, w), T = l.state, y = l.data, b = l.error, l = !b); else { b = T; if (!T || e) T = "error", e < 0 && (e = 0) } x.status = e, x.statusText = (n || T) + "", l ? d.resolveWith(h, [y, T, x]) : d.rejectWith(h, [x, T, b]), x.statusCode(g), g = t, f && p.trigger("ajax" + (l ? "Success" : "Error"), [x, c, l ? y : b]), m.fireWith(h, [x, T]), f && (p.trigger("ajaxComplete", [x, c]), --v.active || v.event.trigger("ajaxStop")) } typeof e == "object" && (n = e, e = t), n = n || {}; var r, i, s, o, u, a, f, l, c = v.ajaxSetup({}, n), h = c.context || c, p = h !== c && (h.nodeType || h instanceof v) ? v(h) : v.event, d = v.Deferred(), m = v.Callbacks("once memory"), g = c.statusCode || {}, b = {}, w = {}, E = 0, S = "canceled", x = { readyState: 0, setRequestHeader: function(e, t) { if (!E) { var n = e.toLowerCase(); e = w[n] = w[n] || e, b[e] = t } return this }, getAllResponseHeaders: function() { return E === 2 ? i : null }, getResponseHeader: function(e) { var n; if (E === 2) { if (!s) { s = {}; while (n = pn.exec(i)) s[n[1].toLowerCase()] = n[2] } n = s[e.toLowerCase()] } return n === t ? null : n }, overrideMimeType: function(e) { return E || (c.mimeType = e), this }, abort: function(e) { return e = e || S, o && o.abort(e), T(0, e), this } }; d.promise(x), x.success = x.done, x.error = x.fail, x.complete = m.add, x.statusCode = function(e) { if (e) { var t; if (E < 2) for (t in e) g[t] = [g[t], e[t]]; else t = e[x.status], x.always(t) } return this }, c.url = ((e || c.url) + "").replace(hn, "").replace(mn, ln[1] + "//"), c.dataTypes = v.trim(c.dataType || "*").toLowerCase().split(y), c.crossDomain == null && (a = wn.exec(c.url.toLowerCase()), c.crossDomain = !(!a || a[1] === ln[1] && a[2] === ln[2] && (a[3] || (a[1] === "http:" ? 80 : 443)) == (ln[3] || (ln[1] === "http:" ? 80 : 443)))), c.data && c.processData && typeof c.data != "string" && (c.data = v.param(c.data, c.traditional)), kn(Sn, c, n, x); if (E === 2) return x; f = c.global, c.type = c.type.toUpperCase(), c.hasContent = !vn.test(c.type), f && v.active++ === 0 && v.event.trigger("ajaxStart"); if (!c.hasContent) { c.data && (c.url += (gn.test(c.url) ? "&" : "?") + c.data, delete c.data), r = c.url; if (c.cache === !1) { var N = v.now(), C = c.url.replace(bn, "$1_=" + N); c.url = C + (C === c.url ? (gn.test(c.url) ? "&" : "?") + "_=" + N : "") } }(c.data && c.hasContent && c.contentType !== !1 || n.contentType) && x.setRequestHeader("Content-Type", c.contentType), c.ifModified && (r = r || c.url, v.lastModified[r] && x.setRequestHeader("If-Modified-Since", v.lastModified[r]), v.etag[r] && x.setRequestHeader("If-None-Match", v.etag[r])), x.setRequestHeader("Accept", c.dataTypes[0] && c.accepts[c.dataTypes[0]] ? c.accepts[c.dataTypes[0]] + (c.dataTypes[0] !== "*" ? ", " + Tn + "; q=0.01" : "") : c.accepts["*"]); for (l in c.headers) x.setRequestHeader(l, c.headers[l]); if (!c.beforeSend || c.beforeSend.call(h, x, c) !== !1 && E !== 2) { S = "abort"; for (l in { success: 1, error: 1, complete: 1 }) x[l](c[l]); o = kn(xn, c, n, x); if (!o) T(-1, "No Transport"); else { x.readyState = 1, f && p.trigger("ajaxSend", [x, c]), c.async && c.timeout > 0 && (u = setTimeout(function() { x.abort("timeout") }, c.timeout)); try { E = 1, o.send(b, T) } catch (k) { if (!(E < 2)) throw k; T(-1, k) } } return x } return x.abort() }, active: 0, lastModified: {}, etag: {} }); var Mn = [], _n = /\?/, Dn = /(=)\?(?=&|$)|\?\?/, Pn = v.now(); v.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var e = Mn.pop() || v.expando + "_" + Pn++; return this[e] = !0, e } }), v.ajaxPrefilter("json jsonp", function(n, r, i) { var s, o, u, a = n.data, f = n.url, l = n.jsonp !== !1, c = l && Dn.test(f), h = l && !c && typeof a == "string" && !(n.contentType || "").indexOf("application/x-www-form-urlencoded") && Dn.test(a); if (n.dataTypes[0] === "jsonp" || c || h) return s = n.jsonpCallback = v.isFunction(n.jsonpCallback) ? n.jsonpCallback() : n.jsonpCallback, o = e[s], c ? n.url = f.replace(Dn, "$1" + s) : h ? n.data = a.replace(Dn, "$1" + s) : l && (n.url += (_n.test(f) ? "&" : "?") + n.jsonp + "=" + s), n.converters["script json"] = function() { return u || v.error(s + " was not called"), u[0] }, n.dataTypes[0] = "json", e[s] = function() { u = arguments }, i.always(function() { e[s] = o, n[s] && (n.jsonpCallback = r.jsonpCallback, Mn.push(s)), u && v.isFunction(o) && o(u[0]), u = o = t }), "script" }), v.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function(e) { return v.globalEval(e), e } } }), v.ajaxPrefilter("script", function(e) { e.cache === t && (e.cache = !1), e.crossDomain && (e.type = "GET", e.global = !1) }), v.ajaxTransport("script", function(e) { if (e.crossDomain) { var n, r = i.head || i.getElementsByTagName("head")[0] || i.documentElement; return { send: function(s, o) { n = i.createElement("script"), n.async = "async", e.scriptCharset && (n.charset = e.scriptCharset), n.src = e.url, n.onload = n.onreadystatechange = function(e, i) { if (i || !n.readyState || /loaded|complete/.test(n.readyState)) n.onload = n.onreadystatechange = null, r && n.parentNode && r.removeChild(n), n = t, i || o(200, "success") }, r.insertBefore(n, r.firstChild) }, abort: function() { n && n.onload(0, 1) } } } }); var Hn, Bn = e.ActiveXObject ? function() { for (var e in Hn) Hn[e](0, 1) } : !1, jn = 0; v.ajaxSettings.xhr = e.ActiveXObject ? function() { return !this.isLocal && Fn() || In() } : Fn, function(e) { v.extend(v.support, { ajax: !! e, cors: !! e && "withCredentials" in e }) }(v.ajaxSettings.xhr()), v.support.ajax && v.ajaxTransport(function(n) { if (!n.crossDomain || v.support.cors) { var r; return { send: function(i, s) { var o, u, a = n.xhr(); n.username ? a.open(n.type, n.url, n.async, n.username, n.password) : a.open(n.type, n.url, n.async); if (n.xhrFields) for (u in n.xhrFields) a[u] = n.xhrFields[u]; n.mimeType && a.overrideMimeType && a.overrideMimeType(n.mimeType), !n.crossDomain && !i["X-Requested-With"] && (i["X-Requested-With"] = "XMLHttpRequest"); try { for (u in i) a.setRequestHeader(u, i[u]) } catch (f) {} a.send(n.hasContent && n.data || null), r = function(e, i) { var u, f, l, c, h; try { if (r && (i || a.readyState === 4)) { r = t, o && (a.onreadystatechange = v.noop, Bn && delete Hn[o]); if (i) a.readyState !== 4 && a.abort(); else { u = a.status, l = a.getAllResponseHeaders(), c = {}, h = a.responseXML, h && h.documentElement && (c.xml = h); try { c.text = a.responseText } catch (p) {} try { f = a.statusText } catch (p) { f = "" }!u && n.isLocal && !n.crossDomain ? u = c.text ? 200 : 404 : u === 1223 && (u = 204) } } } catch (d) { i || s(-1, d) } c && s(u, f, c, l) }, n.async ? a.readyState === 4 ? setTimeout(r, 0) : (o = ++jn, Bn && (Hn || (Hn = {}, v(e).unload(Bn)), Hn[o] = r), a.onreadystatechange = r) : r() }, abort: function() { r && r(0, 1) } } } }); var qn, Rn, Un = /^(?:toggle|show|hide)$/, zn = new RegExp("^(?:([-+])=|)(" + m + ")([a-z%]*)$", "i"), Wn = /queueHooks$/, Xn = [Gn], Vn = { "*": [function(e, t) { var n, r, i = this.createTween(e, t), s = zn.exec(t), o = i.cur(), u = +o || 0, a = 1, f = 20; if (s) { n = +s[2], r = s[3] || (v.cssNumber[e] ? "" : "px"); if (r !== "px" && u) { u = v.css(i.elem, e, !0) || n || 1; do a = a || ".5", u /= a, v.style(i.elem, e, u + r); while (a !== (a = i.cur() / o) && a !== 1 && --f) } i.unit = r, i.start = u, i.end = s[1] ? u + (s[1] + 1) * n : n } return i }] }; v.Animation = v.extend(Kn, { tweener: function(e, t) { v.isFunction(e) ? (t = e, e = ["*"]) : e = e.split(" "); var n, r = 0, i = e.length; for (; r < i; r++) n = e[r], Vn[n] = Vn[n] || [], Vn[n].unshift(t) }, prefilter: function(e, t) { t ? Xn.unshift(e) : Xn.push(e) } }), v.Tween = Yn, Yn.prototype = { constructor: Yn, init: function(e, t, n, r, i, s) { this.elem = e, this.prop = n, this.easing = i || "swing", this.options = t, this.start = this.now = this.cur(), this.end = r, this.unit = s || (v.cssNumber[n] ? "" : "px") }, cur: function() { var e = Yn.propHooks[this.prop]; return e && e.get ? e.get(this) : Yn.propHooks._default.get(this) }, run: function(e) { var t, n = Yn.propHooks[this.prop]; return this.options.duration ? this.pos = t = v.easing[this.easing](e, this.options.duration * e, 0, 1, this.options.duration) : this.pos = t = e, this.now = (this.end - this.start) * t + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), n && n.set ? n.set(this) : Yn.propHooks._default.set(this), this } }, Yn.prototype.init.prototype = Yn.prototype, Yn.propHooks = { _default: { get: function(e) { var t; return e.elem[e.prop] == null || !! e.elem.style && e.elem.style[e.prop] != null ? (t = v.css(e.elem, e.prop, !1, ""), !t || t === "auto" ? 0 : t) : e.elem[e.prop] }, set: function(e) { v.fx.step[e.prop] ? v.fx.step[e.prop](e) : e.elem.style && (e.elem.style[v.cssProps[e.prop]] != null || v.cssHooks[e.prop]) ? v.style(e.elem, e.prop, e.now + e.unit) : e.elem[e.prop] = e.now } } }, Yn.propHooks.scrollTop = Yn.propHooks.scrollLeft = { set: function(e) { e.elem.nodeType && e.elem.parentNode && (e.elem[e.prop] = e.now) } }, v.each(["toggle", "show", "hide"], function(e, t) { var n = v.fn[t]; v.fn[t] = function(r, i, s) { return r == null || typeof r == "boolean" || !e && v.isFunction(r) && v.isFunction(i) ? n.apply(this, arguments) : this.animate(Zn(t, !0), r, i, s) } }), v.fn.extend({ fadeTo: function(e, t, n, r) { return this.filter(Gt).css("opacity", 0).show().end().animate({ opacity: t }, e, n, r) }, animate: function(e, t, n, r) { var i = v.isEmptyObject(e), s = v.speed(t, n, r), o = function() { var t = Kn(this, v.extend({}, e), s); i && t.stop(!0) }; return i || s.queue === !1 ? this.each(o) : this.queue(s.queue, o) }, stop: function(e, n, r) { var i = function(e) { var t = e.stop; delete e.stop, t(r) }; return typeof e != "string" && (r = n, n = e, e = t), n && e !== !1 && this.queue(e || "fx", []), this.each(function() { var t = !0, n = e != null && e + "queueHooks", s = v.timers, o = v._data(this); if (n) o[n] && o[n].stop && i(o[n]); else for (n in o) o[n] && o[n].stop && Wn.test(n) && i(o[n]); for (n = s.length; n--;) s[n].elem === this && (e == null || s[n].queue === e) && (s[n].anim.stop(r), t = !1, s.splice(n, 1)); (t || !r) && v.dequeue(this, e) }) } }), v.each({ slideDown: Zn("show"), slideUp: Zn("hide"), slideToggle: Zn("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function(e, t) { v.fn[e] = function(e, n, r) { return this.animate(t, e, n, r) } }), v.speed = function(e, t, n) { var r = e && typeof e == "object" ? v.extend({}, e) : { complete: n || !n && t || v.isFunction(e) && e, duration: e, easing: n && t || t && !v.isFunction(t) && t }; r.duration = v.fx.off ? 0 : typeof r.duration == "number" ? r.duration : r.duration in v.fx.speeds ? v.fx.speeds[r.duration] : v.fx.speeds._default; if (r.queue == null || r.queue === !0) r.queue = "fx"; return r.old = r.complete, r.complete = function() { v.isFunction(r.old) && r.old.call(this), r.queue && v.dequeue(this, r.queue) }, r }, v.easing = { linear: function(e) { return e }, swing: function(e) { return.5 - Math.cos(e * Math.PI) / 2 } }, v.timers = [], v.fx = Yn.prototype.init, v.fx.tick = function() { var e, n = v.timers, r = 0; qn = v.now(); for (; r < n.length; r++) e = n[r], !e() && n[r] === e && n.splice(r--, 1); n.length || v.fx.stop(), qn = t }, v.fx.timer = function(e) { e() && v.timers.push(e) && !Rn && (Rn = setInterval(v.fx.tick, v.fx.interval)) }, v.fx.interval = 13, v.fx.stop = function() { clearInterval(Rn), Rn = null }, v.fx.speeds = { slow: 600, fast: 200, _default: 400 }, v.fx.step = {}, v.expr && v.expr.filters && (v.expr.filters.animated = function(e) { return v.grep(v.timers, function(t) { return e === t.elem }).length }); var er = /^(?:body|html)$/i; v.fn.offset = function(e) { if (arguments.length) return e === t ? this : this.each(function(t) { v.offset.setOffset(this, e, t) }); var n, r, i, s, o, u, a, f = { top: 0, left: 0 }, l = this[0], c = l && l.ownerDocument; if (!c) return; return (r = c.body) === l ? v.offset.bodyOffset(l) : (n = c.documentElement, v.contains(n, l) ? (typeof l.getBoundingClientRect != "undefined" && (f = l.getBoundingClientRect()), i = tr(c), s = n.clientTop || r.clientTop || 0, o = n.clientLeft || r.clientLeft || 0, u = i.pageYOffset || n.scrollTop, a = i.pageXOffset || n.scrollLeft, { top: f.top + u - s, left: f.left + a - o }) : f) }, v.offset = { bodyOffset: function(e) { var t = e.offsetTop, n = e.offsetLeft; return v.support.doesNotIncludeMarginInBodyOffset && (t += parseFloat(v.css(e, "marginTop")) || 0, n += parseFloat(v.css(e, "marginLeft")) || 0), { top: t, left: n } }, setOffset: function(e, t, n) { var r = v.css(e, "position"); r === "static" && (e.style.position = "relative"); var i = v(e), s = i.offset(), o = v.css(e, "top"), u = v.css(e, "left"), a = (r === "absolute" || r === "fixed") && v.inArray("auto", [o, u]) > -1, f = {}, l = {}, c, h; a ? (l = i.position(), c = l.top, h = l.left) : (c = parseFloat(o) || 0, h = parseFloat(u) || 0), v.isFunction(t) && (t = t.call(e, n, s)), t.top != null && (f.top = t.top - s.top + c), t.left != null && (f.left = t.left - s.left + h), "using" in t ? t.using.call(e, f) : i.css(f) } }, v.fn.extend({ position: function() { if (!this[0]) return; var e = this[0], t = this.offsetParent(), n = this.offset(), r = er.test(t[0].nodeName) ? { top: 0, left: 0 } : t.offset(); return n.top -= parseFloat(v.css(e, "marginTop")) || 0, n.left -= parseFloat(v.css(e, "marginLeft")) || 0, r.top += parseFloat(v.css(t[0], "borderTopWidth")) || 0, r.left += parseFloat(v.css(t[0], "borderLeftWidth")) || 0, { top: n.top - r.top, left: n.left - r.left } }, offsetParent: function() { return this.map(function() { var e = this.offsetParent || i.body; while (e && !er.test(e.nodeName) && v.css(e, "position") === "static") e = e.offsetParent; return e || i.body }) } }), v.each({ scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function(e, n) { var r = /Y/.test(n); v.fn[e] = function(i) { return v.access(this, function(e, i, s) { var o = tr(e); if (s === t) return o ? n in o ? o[n] : o.document.documentElement[i] : e[i]; o ? o.scrollTo(r ? v(o).scrollLeft() : s, r ? s : v(o).scrollTop()) : e[i] = s }, e, i, arguments.length, null) } }), v.each({ Height: "height", Width: "width" }, function(e, n) { v.each({ padding: "inner" + e, content: n, "": "outer" + e }, function(r, i) { v.fn[i] = function(i, s) { var o = arguments.length && (r || typeof i != "boolean"), u = r || (i === !0 || s === !0 ? "margin" : "border"); return v.access(this, function(n, r, i) { var s; return v.isWindow(n) ? n.document.documentElement["client" + e] : n.nodeType === 9 ? (s = n.documentElement, Math.max(n.body["scroll" + e], s["scroll" + e], n.body["offset" + e], s["offset" + e], s["client" + e])) : i === t ? v.css(n, r, i, u) : v.style(n, r, i, u) }, n, o ? i : t, o, null) } }) }), e.jQuery = e.$ = v, typeof define == "function" && define.amd && define.amd.jQuery && define("jquery", [], function() { return v }) })(window);
src/components/HomePage/HomePage.js
mkuipers/terra-mystica
/* * React.js Starter Kit * Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; import React from 'react'; export default class HomePage extends React.Component { render() { return ( <div className="ContentPage" dangerouslySetInnerHTML={{__html: this.props.body}} /> ); } } HomePage.propTypes = { body: React.PropTypes.string.isRequired };
examples/js/pagination/default-pagination-table.js
pvoznyuk/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(70); export default class DefaultPaginationTable extends React.Component { constructor(props) { super(props); } render() { return ( <div> <BootstrapTable data={ products } pagination> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> </div> ); } }
ajax/libs/react-inlinesvg/0.6.2/react-inlinesvg.js
dakshshah96/cdnjs
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ReactInlineSVG = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = require('object-assign'); var emptyObject = require('fbjs/lib/emptyObject'); var _invariant = require('fbjs/lib/invariant'); if ("production" !== 'production') { var warning = require('fbjs/lib/warning'); } var MIXINS_KEY = 'mixins'; // Helper function to allow the creation of anonymous functions which do not // have .name set to the name of the variable being assigned to. function identity(fn) { return fn; } var ReactPropTypeLocationNames; if ("production" !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } else { ReactPropTypeLocationNames = {}; } function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) { /** * Policies that describe methods in `ReactClassInterface`. */ var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: 'DEFINE_MANY', /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: 'DEFINE_MANY', /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: 'DEFINE_MANY', /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: 'DEFINE_MANY', /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: 'DEFINE_MANY', // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: 'DEFINE_MANY_MERGED', /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: 'DEFINE_MANY_MERGED', /** * @return {object} * @optional */ getChildContext: 'DEFINE_MANY_MERGED', /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @required */ render: 'DEFINE_ONCE', // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: 'DEFINE_MANY', /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: 'DEFINE_MANY', /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: 'DEFINE_MANY', /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: 'DEFINE_ONCE', /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: 'DEFINE_MANY', /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: 'DEFINE_MANY', /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: 'DEFINE_MANY', // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: 'OVERRIDE_BASE' }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function(Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function(Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function(Constructor, childContextTypes) { if ("production" !== 'production') { validateTypeDef(Constructor, childContextTypes, 'childContext'); } Constructor.childContextTypes = _assign( {}, Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(Constructor, contextTypes) { if ("production" !== 'production') { validateTypeDef(Constructor, contextTypes, 'context'); } Constructor.contextTypes = _assign( {}, Constructor.contextTypes, contextTypes ); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function(Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction( Constructor.getDefaultProps, getDefaultProps ); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function(Constructor, propTypes) { if ("production" !== 'production') { validateTypeDef(Constructor, propTypes, 'prop'); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function() {} }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an _invariant so components // don't show up in prod but only in __DEV__ if ("production" !== 'production') { warning( typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName ); } } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { _invariant( specPolicy === 'OVERRIDE_BASE', 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ); } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { _invariant( specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED', 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ); } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if ("production" !== 'production') { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; if ("production" !== 'production') { warning( isMixinValid, "%s: You're attempting to include a mixin that is either null " + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec ); } } return; } _invariant( typeof spec !== 'function', "ReactClass: You're attempting to " + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.' ); _invariant( !isValidElement(spec), "ReactClass: You're attempting to " + 'use a component as a mixin. Instead, just use a regular object.' ); var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. _invariant( isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY'), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if ("production" !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; _invariant( !isReserved, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name ); var isInherited = name in Constructor; _invariant( !isInherited, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name ); Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { _invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.' ); for (var key in two) { if (two.hasOwnProperty(key)) { _invariant( one[key] === undefined, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ); one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if ("production" !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function(newThis) { for ( var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ ) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { if ("production" !== 'production') { warning( false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName ); } } else if (!args.length) { if ("production" !== 'production') { warning( false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName ); } return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } var IsMountedPreMixin = { componentDidMount: function() { this.__isMounted = true; } }; var IsMountedPostMixin = { componentWillUnmount: function() { this.__isMounted = false; } }; /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function(newState, callback) { this.updater.enqueueReplaceState(this, newState, callback); }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { if ("production" !== 'production') { warning( this.__didWarnIsMounted, '%s: isMounted is deprecated. Instead, make sure to clean up ' + 'subscriptions and pending requests in componentWillUnmount to ' + 'prevent memory leaks.', (this.constructor && this.constructor.displayName) || this.name || 'Component' ); this.__didWarnIsMounted = true; } return !!this.__isMounted; } }; var ReactClassComponent = function() {}; _assign( ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin ); /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ function createClass(spec) { // To keep our warnings more understandable, we'll use a little hack here to // ensure that Constructor.name !== 'Constructor'. This makes sure we don't // unnecessarily identify a class without displayName as 'Constructor'. var Constructor = identity(function(props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if ("production" !== 'production') { warning( this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory' ); } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if ("production" !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if ( initialState === undefined && this.getInitialState._isMockFunction ) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } _invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent' ); this.state = initialState; }); Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, IsMountedPreMixin); mixSpecIntoComponent(Constructor, spec); mixSpecIntoComponent(Constructor, IsMountedPostMixin); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if ("production" !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } _invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ); if ("production" !== 'production') { warning( !Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component' ); warning( !Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component' ); } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; } return createClass; } module.exports = factory; },{"fbjs/lib/emptyObject":3,"fbjs/lib/invariant":4,"fbjs/lib/warning":5,"object-assign":16}],2:[function(require,module,exports){ "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; },{}],3:[function(require,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyObject = {}; if ("production" !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; },{}],4:[function(require,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if ("production" !== 'production') { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; },{}],5:[function(require,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. * */ 'use strict'; var emptyFunction = require('./emptyFunction'); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("production" !== 'production') { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; },{"./emptyFunction":2}],6:[function(require,module,exports){ 'use strict'; var Response = require('./response'); var extractResponseProps = require('./utils/extractResponseProps'); var extend = require('xtend'); function RequestError(message, props) { var err = new Error(message); err.name = 'RequestError'; this.name = err.name; this.message = err.message; if (err.stack) { this.stack = err.stack; } this.toString = function() { return this.message; }; for (var k in props) { if (props.hasOwnProperty(k)) { this[k] = props[k]; } } } RequestError.prototype = extend(Error.prototype); RequestError.prototype.constructor = RequestError; RequestError.create = function(message, req, props) { var err = new RequestError(message, props); Response.call(err, extractResponseProps(req)); return err; }; module.exports = RequestError; },{"./response":9,"./utils/extractResponseProps":11,"xtend":52}],7:[function(require,module,exports){ 'use strict'; var cleanURL = require('../plugins/cleanurl'), XHR = require('./xhr'), delay = require('./utils/delay'), RequestError = require('./error'), Response = require('./response'), Request = require('./request'), extend = require('xtend'), once = require('./utils/once'); var i, createError = RequestError.create; function factory(defaults, plugins) { defaults = defaults || {}; plugins = plugins || []; function http(req, cb) { var xhr, plugin, done, k, timeoutId, supportsLoadAndErrorEvents; req = new Request(extend(defaults, req)); for (i = 0; i < plugins.length; i++) { plugin = plugins[i]; if (plugin.processRequest) { plugin.processRequest(req); } } // Give the plugins a chance to create the XHR object for (i = 0; i < plugins.length; i++) { plugin = plugins[i]; if (plugin.createXHR) { xhr = plugin.createXHR(req); break; // First come, first serve } } xhr = xhr || new XHR(); req.xhr = xhr; // Use a single completion callback. This can be called with or without // an error. If no error is passed, the request will be examined to see // if it was successful. done = once(delay(function(rawError) { clearTimeout(timeoutId); xhr.onload = xhr.onerror = xhr.onabort = xhr.onreadystatechange = xhr.ontimeout = xhr.onprogress = null; var err = getError(req, rawError); var res = err || Response.fromRequest(req); for (i = 0; i < plugins.length; i++) { plugin = plugins[i]; if (plugin.processResponse) { plugin.processResponse(res); } } // Invoke callbacks if (err && req.onerror) req.onerror(err); if (!err && req.onload) req.onload(res); if (cb) cb(err, err ? undefined : res); })); supportsLoadAndErrorEvents = ('onload' in xhr) && ('onerror' in xhr); xhr.onload = function() { done(); }; xhr.onerror = done; xhr.onabort = function() { done(); }; // We'd rather use `onload`, `onerror`, and `onabort` since they're the // only way to reliably detect successes and failures but, if they // aren't available, we fall back to using `onreadystatechange`. xhr.onreadystatechange = function() { if (xhr.readyState !== 4) return; if (req.aborted) return done(); if (!supportsLoadAndErrorEvents) { // Assume a status of 0 is an error. This could be a false // positive, but there's no way to tell when using // `onreadystatechange` ): // See matthewwithanm/react-inlinesvg#10. // Some browsers don't like you reading XHR properties when the // XHR has been aborted. In case we've gotten here as a result // of that (either our calling `about()` in the timeout handler // or the user calling it directly even though they shouldn't), // be careful about accessing it. var status; try { status = xhr.status; } catch (err) {} var err = status === 0 ? new Error('Internal XHR Error') : null; return done(err); } }; // IE sometimes fails if you don't specify every handler. // See http://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment xhr.ontimeout = function() { /* noop */ }; xhr.onprogress = function() { /* noop */ }; xhr.open(req.method, req.url); if (req.timeout) { // If we use the normal XHR timeout mechanism (`xhr.timeout` and // `xhr.ontimeout`), `onreadystatechange` will be triggered before // `ontimeout`. There's no way to recognize that it was triggered by // a timeout, and we'd be unable to dispatch the right error. timeoutId = setTimeout(function() { req.timedOut = true; done(); try { xhr.abort(); } catch (err) {} }, req.timeout); } for (k in req.headers) { if (req.headers.hasOwnProperty(k)) { xhr.setRequestHeader(k, req.headers[k]); } } xhr.send(req.body); return req; } var method, methods = ['get', 'post', 'put', 'head', 'patch', 'delete'], verb = function(method) { return function(req, cb) { req = new Request(req); req.method = method; return http(req, cb); }; }; for (i = 0; i < methods.length; i++) { method = methods[i]; http[method] = verb(method); } http.plugins = function() { return plugins; }; http.defaults = function(newValues) { if (newValues) { return factory(extend(defaults, newValues), plugins); } return defaults; }; http.use = function() { var newPlugins = Array.prototype.slice.call(arguments, 0); return factory(defaults, plugins.concat(newPlugins)); }; http.bare = function() { return factory(); }; http.Request = Request; http.Response = Response; http.RequestError = RequestError; return http; } module.exports = factory({}, [cleanURL]); /** * Analyze the request to see if it represents an error. If so, return it! An * original error object can be passed as a hint. */ function getError(req, err) { if (req.aborted) return createError('Request aborted', req, {name: 'Abort'}); if (req.timedOut) return createError('Request timeout', req, {name: 'Timeout'}); var xhr = req.xhr; var type = Math.floor(xhr.status / 100); var kind; switch (type) { case 0: case 2: // These don't represent errors unless the function was passed an // error object explicitly. if (!err) return; return createError(err.message, req); case 4: // Sometimes 4XX statuses aren't errors. if (xhr.status === 404 && !req.errorOn404) return; kind = 'Client'; break; case 5: kind = 'Server'; break; default: kind = 'HTTP'; } var msg = kind + ' Error: ' + 'The server returned a status of ' + xhr.status + ' for the request "' + req.method.toUpperCase() + ' ' + req.url + '"'; return createError(msg, req); } },{"../plugins/cleanurl":14,"./error":6,"./request":8,"./response":9,"./utils/delay":10,"./utils/once":12,"./xhr":13,"xtend":52}],8:[function(require,module,exports){ 'use strict'; function Request(optsOrUrl) { var opts = typeof optsOrUrl === 'string' ? {url: optsOrUrl} : optsOrUrl || {}; this.method = opts.method ? opts.method.toUpperCase() : 'GET'; this.url = opts.url; this.headers = opts.headers || {}; this.body = opts.body; this.timeout = opts.timeout || 0; this.errorOn404 = opts.errorOn404 != null ? opts.errorOn404 : true; this.onload = opts.onload; this.onerror = opts.onerror; } Request.prototype.abort = function() { if (this.aborted) return; this.aborted = true; this.xhr.abort(); return this; }; Request.prototype.header = function(name, value) { var k; for (k in this.headers) { if (this.headers.hasOwnProperty(k)) { if (name.toLowerCase() === k.toLowerCase()) { if (arguments.length === 1) { return this.headers[k]; } delete this.headers[k]; break; } } } if (value != null) { this.headers[name] = value; return value; } }; module.exports = Request; },{}],9:[function(require,module,exports){ 'use strict'; var Request = require('./request'); var extractResponseProps = require('./utils/extractResponseProps'); function Response(props) { this.request = props.request; this.xhr = props.xhr; this.headers = props.headers || {}; this.status = props.status || 0; this.text = props.text; this.body = props.body; this.contentType = props.contentType; this.isHttpError = props.status >= 400; } Response.prototype.header = Request.prototype.header; Response.fromRequest = function(req) { return new Response(extractResponseProps(req)); }; module.exports = Response; },{"./request":8,"./utils/extractResponseProps":11}],10:[function(require,module,exports){ 'use strict'; // Wrap a function in a `setTimeout` call. This is used to guarantee async // behavior, which can avoid unexpected errors. module.exports = function(fn) { return function() { var args = Array.prototype.slice.call(arguments, 0), newFunc = function() { return fn.apply(null, args); }; setTimeout(newFunc, 0); }; }; },{}],11:[function(require,module,exports){ 'use strict'; var extend = require('xtend'); module.exports = function(req) { var xhr = req.xhr; var props = {request: req, xhr: xhr}; // Try to create the response from the request. If the request was aborted, // accesssing properties of the XHR may throw an error, so we wrap in a // try/catch. try { var lines, i, m, headers = {}; if (xhr.getAllResponseHeaders) { lines = xhr.getAllResponseHeaders().split('\n'); for (i = 0; i < lines.length; i++) { if ((m = lines[i].match(/\s*([^\s]+):\s+([^\s]+)/))) { headers[m[1]] = m[2]; } } } props = extend(props, { status: xhr.status, contentType: xhr.contentType || (xhr.getResponseHeader && xhr.getResponseHeader('Content-Type')), headers: headers, text: xhr.responseText, body: xhr.response || xhr.responseText }); } catch (err) {} return props; }; },{"xtend":52}],12:[function(require,module,exports){ 'use strict'; // A "once" utility. module.exports = function(fn) { var result, called = false; return function() { if (!called) { called = true; result = fn.apply(this, arguments); } return result; }; }; },{}],13:[function(require,module,exports){ module.exports = window.XMLHttpRequest; },{}],14:[function(require,module,exports){ 'use strict'; module.exports = { processRequest: function(req) { req.url = req.url.replace(/[^%]+/g, function(s) { return encodeURI(s); }); } }; },{}],15:[function(require,module,exports){ 'use strict'; var urllite = require('urllite/lib/core'), once = require('../lib/utils/once'); var warningShown = false; var supportsXHR = once(function() { return ( typeof window !== 'undefined' && window !== null && window.XMLHttpRequest && 'withCredentials' in new window.XMLHttpRequest() ); }); // This plugin creates a Microsoft `XDomainRequest` in supporting browsers when // the URL being requested is on a different domain. This is necessary to // support IE9, which only supports CORS via its proprietary `XDomainRequest` // object. We need to check the URL because `XDomainRequest` *doesn't* work for // same domain requests (unless your server sends CORS headers). // `XDomainRequest` also has other limitations (no custom headers), so we try to // catch those and error. module.exports = { createXHR: function(req) { var a, b, k; if (typeof window === 'undefined' || window === null) { return; } a = urllite(req.url); b = urllite(window.location.href); // Don't do anything for same-domain requests. if (!a.host) { return; } if (a.protocol === b.protocol && a.host === b.host && a.port === b.port) { return; } // Show a warning if there are custom headers. We do this even in // browsers that won't use XDomainRequest so that users know there's an // issue right away, instead of if/when they test in IE9. if (!warningShown && req.headers) { for (k in req.headers) { if (req.headers.hasOwnProperty(k)) { warningShown = true; if (window && window.console && window.console.warn) { window.console.warn('Request headers are ignored in old IE when using the oldiexdomain plugin.'); } break; } } } // Don't do anything if we can't do anything (: // Don't do anything if the browser supports proper XHR. if (window.XDomainRequest && !supportsXHR()) { // We've come this far. Might as well make an XDomainRequest. var xdr = new window.XDomainRequest(); xdr.setRequestHeader = function() {}; // Ignore request headers. return xdr; } } }; },{"../lib/utils/once":12,"urllite/lib/core":50}],16:[function(require,module,exports){ /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; },{}],17:[function(require,module,exports){ var wrappy = require('wrappy') module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }) }) function once (fn) { var f = function () { if (f.called) return f.value f.called = true return f.value = fn.apply(this, arguments) } f.called = false return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true return f.value = fn.apply(this, arguments) } var name = fn.name || 'Function wrapped with `once`' f.onceError = name + " shouldn't be called more than once" f.called = false return f } },{"wrappy":51}],18:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],19:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; if ("production" !== 'production') { var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret'); var loggedTypeFailures = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if ("production" !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } module.exports = checkPropTypes; },{"./lib/ReactPropTypesSecret":24,"fbjs/lib/invariant":4,"fbjs/lib/warning":5}],20:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; // React 15.5 references this module, and assumes PropTypes are still callable in production. // Therefore we re-export development-only version with all the PropTypes checks here. // However if one is migrating to the `prop-types` npm library, they will go through the // `index.js` entry point, and it will branch depending on the environment. var factory = require('./factoryWithTypeCheckers'); module.exports = function(isValidElement) { // It is still allowed in 15.5. var throwOnDirectAccess = false; return factory(isValidElement, throwOnDirectAccess); }; },{"./factoryWithTypeCheckers":22}],21:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var emptyFunction = require('fbjs/lib/emptyFunction'); var invariant = require('fbjs/lib/invariant'); var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret'); module.exports = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret) { // It is still safe when called from React. return; } invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); }; shim.isRequired = shim; function getShim() { return shim; }; // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; },{"./lib/ReactPropTypesSecret":24,"fbjs/lib/emptyFunction":2,"fbjs/lib/invariant":4}],22:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var emptyFunction = require('fbjs/lib/emptyFunction'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret'); var checkPropTypes = require('./checkPropTypes'); module.exports = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if ("production" !== 'production') { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); } else if ("production" !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { warning( false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { "production" !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { "production" !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { warning( false, 'Invalid argument supplid to oneOfType. Expected an array of check functions, but ' + 'received %s at index %s.', getPostfixForTypeWarning(checker), i ); return emptyFunction.thatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; },{"./checkPropTypes":19,"./lib/ReactPropTypesSecret":24,"fbjs/lib/emptyFunction":2,"fbjs/lib/invariant":4,"fbjs/lib/warning":5}],23:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ if ("production" !== 'production') { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = require('./factoryWithTypeCheckers')(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = require('./factoryWithThrowingShims')(); } },{"./factoryWithThrowingShims":21,"./factoryWithTypeCheckers":22}],24:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; },{}],25:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; },{}],26:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'); var invariant = require('fbjs/lib/invariant'); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? "production" !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0; 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. * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { // Casting as any so that flow ignores the actual implementation and trusts // it to match the type we declared 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, fourArgumentPooler: fourArgumentPooler }; module.exports = PooledClass; },{"./reactProdInvariant":47,"fbjs/lib/invariant":4}],27:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = require('object-assign'); var ReactBaseClasses = require('./ReactBaseClasses'); var ReactChildren = require('./ReactChildren'); var ReactDOMFactories = require('./ReactDOMFactories'); var ReactElement = require('./ReactElement'); var ReactPropTypes = require('./ReactPropTypes'); var ReactVersion = require('./ReactVersion'); var createReactClass = require('./createClass'); var onlyChild = require('./onlyChild'); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if ("production" !== 'production') { var lowPriorityWarning = require('./lowPriorityWarning'); var canDefineProperty = require('./canDefineProperty'); var ReactElementValidator = require('./ReactElementValidator'); var didWarnPropTypesDeprecated = false; createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var __spread = _assign; var createMixin = function (mixin) { return mixin; }; if ("production" !== 'production') { var warnedForSpread = false; var warnedForCreateMixin = false; __spread = function () { lowPriorityWarning(warnedForSpread, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.'); warnedForSpread = true; return _assign.apply(null, arguments); }; createMixin = function (mixin) { lowPriorityWarning(warnedForCreateMixin, 'React.createMixin is deprecated and should not be used. ' + 'In React v16.0, it will be removed. ' + 'You can use this mixin directly instead. ' + 'See https://fb.me/createmixin-was-never-implemented for more info.'); warnedForCreateMixin = true; return mixin; }; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactBaseClasses.Component, PureComponent: ReactBaseClasses.PureComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: createReactClass, createFactory: createFactory, createMixin: createMixin, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Deprecated hook for JSX spread, don't use this for anything. __spread: __spread }; if ("production" !== 'production') { var warnedForCreateClass = false; if (canDefineProperty) { Object.defineProperty(React, 'PropTypes', { get: function () { lowPriorityWarning(didWarnPropTypesDeprecated, 'Accessing PropTypes via the main React package is deprecated,' + ' and will be removed in React v16.0.' + ' Use the latest available v15.* prop-types package from npm instead.' + ' For info on usage, compatibility, migration and more, see ' + 'https://fb.me/prop-types-docs'); didWarnPropTypesDeprecated = true; return ReactPropTypes; } }); Object.defineProperty(React, 'createClass', { get: function () { lowPriorityWarning(warnedForCreateClass, 'Accessing createClass via the main React package is deprecated,' + ' and will be removed in React v16.0.' + " Use a plain JavaScript class instead. If you're not yet " + 'ready to migrate, create-react-class v15.* is available ' + 'on npm as a temporary, drop-in replacement. ' + 'For more info see https://fb.me/react-create-class'); warnedForCreateClass = true; return createReactClass; } }); } // React.DOM factories are deprecated. Wrap these methods so that // invocations of the React.DOM namespace and alert users to switch // to the `react-dom-factories` package. React.DOM = {}; var warnedForFactories = false; Object.keys(ReactDOMFactories).forEach(function (factory) { React.DOM[factory] = function () { if (!warnedForFactories) { lowPriorityWarning(false, 'Accessing factories like React.DOM.%s has been deprecated ' + 'and will be removed in v16.0+. Use the ' + 'react-dom-factories package instead. ' + ' Version 1.0 provides a drop-in replacement.' + ' For more info, see https://fb.me/react-dom-factories', factory); warnedForFactories = true; } return ReactDOMFactories[factory].apply(ReactDOMFactories, arguments); }; }); } module.exports = React; },{"./ReactBaseClasses":28,"./ReactChildren":29,"./ReactDOMFactories":32,"./ReactElement":33,"./ReactElementValidator":35,"./ReactPropTypes":38,"./ReactVersion":40,"./canDefineProperty":41,"./createClass":43,"./lowPriorityWarning":45,"./onlyChild":46,"object-assign":16}],28:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'), _assign = require('object-assign'); var ReactNoopUpdateQueue = require('./ReactNoopUpdateQueue'); var canDefineProperty = require('./canDefineProperty'); var emptyObject = require('fbjs/lib/emptyObject'); var invariant = require('fbjs/lib/invariant'); var lowPriorityWarning = require('./lowPriorityWarning'); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * 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) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? "production" !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0; this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback, 'setState'); } }; /** * 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) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback, 'forceUpdate'); } }; /** * 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" !== 'production') { var deprecatedAPIs = { 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).'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { lowPriorityWarning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } /** * Base class helpers for the updating state of a component. */ function ReactPureComponent(props, context, updater) { // Duplicated from ReactComponent. this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } function ComponentDummy() {} ComponentDummy.prototype = ReactComponent.prototype; ReactPureComponent.prototype = new ComponentDummy(); ReactPureComponent.prototype.constructor = ReactPureComponent; // Avoid an extra prototype jump for these methods. _assign(ReactPureComponent.prototype, ReactComponent.prototype); ReactPureComponent.prototype.isPureReactComponent = true; module.exports = { Component: ReactComponent, PureComponent: ReactPureComponent }; },{"./ReactNoopUpdateQueue":36,"./canDefineProperty":41,"./lowPriorityWarning":45,"./reactProdInvariant":47,"fbjs/lib/emptyObject":3,"fbjs/lib/invariant":4,"object-assign":16}],29:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var PooledClass = require('./PooledClass'); var ReactElement = require('./ReactElement'); var emptyFunction = require('fbjs/lib/emptyFunction'); var traverseAllChildren = require('./traverseAllChildren'); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } /** * 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.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func, context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach * * 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, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; },{"./PooledClass":26,"./ReactElement":33,"./traverseAllChildren":48,"fbjs/lib/emptyFunction":2}],30:[function(require,module,exports){ /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'); var ReactCurrentOwner = require('./ReactCurrentOwner'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); function isNative(fn) { // Based on isNative() from Lodash var funcToString = Function.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var reIsNative = RegExp('^' + funcToString // Take an example native function source for comparison .call(hasOwnProperty // Strip regex characters so we can use it for regex ).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&' // Remove hasOwnProperty from the template to make it generic ).replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); try { var source = funcToString.call(fn); return reIsNative.test(source); } catch (err) { return false; } } var canUseCollections = // Array.from typeof Array.from === 'function' && // Map typeof Map === 'function' && isNative(Map) && // Map.prototype.keys Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) && // Set typeof Set === 'function' && isNative(Set) && // Set.prototype.keys Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys); var setItem; var getItem; var removeItem; var getItemIDs; var addRoot; var removeRoot; var getRootIDs; if (canUseCollections) { var itemMap = new Map(); var rootIDSet = new Set(); setItem = function (id, item) { itemMap.set(id, item); }; getItem = function (id) { return itemMap.get(id); }; removeItem = function (id) { itemMap['delete'](id); }; getItemIDs = function () { return Array.from(itemMap.keys()); }; addRoot = function (id) { rootIDSet.add(id); }; removeRoot = function (id) { rootIDSet['delete'](id); }; getRootIDs = function () { return Array.from(rootIDSet.keys()); }; } else { var itemByKey = {}; var rootByKey = {}; // Use non-numeric keys to prevent V8 performance issues: // https://github.com/facebook/react/pull/7232 var getKeyFromID = function (id) { return '.' + id; }; var getIDFromKey = function (key) { return parseInt(key.substr(1), 10); }; setItem = function (id, item) { var key = getKeyFromID(id); itemByKey[key] = item; }; getItem = function (id) { var key = getKeyFromID(id); return itemByKey[key]; }; removeItem = function (id) { var key = getKeyFromID(id); delete itemByKey[key]; }; getItemIDs = function () { return Object.keys(itemByKey).map(getIDFromKey); }; addRoot = function (id) { var key = getKeyFromID(id); rootByKey[key] = true; }; removeRoot = function (id) { var key = getKeyFromID(id); delete rootByKey[key]; }; getRootIDs = function () { return Object.keys(rootByKey).map(getIDFromKey); }; } var unmountedIDs = []; function purgeDeep(id) { var item = getItem(id); if (item) { var childIDs = item.childIDs; removeItem(id); childIDs.forEach(purgeDeep); } } function describeComponentFrame(name, source, ownerName) { return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : ''); } function getDisplayName(element) { if (element == null) { return '#empty'; } else if (typeof element === 'string' || typeof element === 'number') { return '#text'; } else if (typeof element.type === 'string') { return element.type; } else { return element.type.displayName || element.type.name || 'Unknown'; } } function describeID(id) { var name = ReactComponentTreeHook.getDisplayName(id); var element = ReactComponentTreeHook.getElement(id); var ownerID = ReactComponentTreeHook.getOwnerID(id); var ownerName; if (ownerID) { ownerName = ReactComponentTreeHook.getDisplayName(ownerID); } "production" !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0; return describeComponentFrame(name, element && element._source, ownerName); } var ReactComponentTreeHook = { onSetChildren: function (id, nextChildIDs) { var item = getItem(id); !item ? "production" !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0; item.childIDs = nextChildIDs; for (var i = 0; i < nextChildIDs.length; i++) { var nextChildID = nextChildIDs[i]; var nextChild = getItem(nextChildID); !nextChild ? "production" !== 'production' ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0; !(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? "production" !== 'production' ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0; !nextChild.isMounted ? "production" !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0; if (nextChild.parentID == null) { nextChild.parentID = id; // TODO: This shouldn't be necessary but mounting a new root during in // componentWillMount currently causes not-yet-mounted components to // be purged from our tree data so their parent id is missing. } !(nextChild.parentID === id) ? "production" !== 'production' ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0; } }, onBeforeMountComponent: function (id, element, parentID) { var item = { element: element, parentID: parentID, text: null, childIDs: [], isMounted: false, updateCount: 0 }; setItem(id, item); }, onBeforeUpdateComponent: function (id, element) { var item = getItem(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.element = element; }, onMountComponent: function (id) { var item = getItem(id); !item ? "production" !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0; item.isMounted = true; var isRoot = item.parentID === 0; if (isRoot) { addRoot(id); } }, onUpdateComponent: function (id) { var item = getItem(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.updateCount++; }, onUnmountComponent: function (id) { var item = getItem(id); if (item) { // We need to check if it exists. // `item` might not exist if it is inside an error boundary, and a sibling // error boundary child threw while mounting. Then this instance never // got a chance to mount, but it still gets an unmounting event during // the error boundary cleanup. item.isMounted = false; var isRoot = item.parentID === 0; if (isRoot) { removeRoot(id); } } unmountedIDs.push(id); }, purgeUnmountedComponents: function () { if (ReactComponentTreeHook._preventPurging) { // Should only be used for testing. return; } for (var i = 0; i < unmountedIDs.length; i++) { var id = unmountedIDs[i]; purgeDeep(id); } unmountedIDs.length = 0; }, isMounted: function (id) { var item = getItem(id); return item ? item.isMounted : false; }, getCurrentStackAddendum: function (topElement) { var info = ''; if (topElement) { var name = getDisplayName(topElement); var owner = topElement._owner; info += describeComponentFrame(name, topElement._source, owner && owner.getName()); } var currentOwner = ReactCurrentOwner.current; var id = currentOwner && currentOwner._debugID; info += ReactComponentTreeHook.getStackAddendumByID(id); return info; }, getStackAddendumByID: function (id) { var info = ''; while (id) { info += describeID(id); id = ReactComponentTreeHook.getParentID(id); } return info; }, getChildIDs: function (id) { var item = getItem(id); return item ? item.childIDs : []; }, getDisplayName: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element) { return null; } return getDisplayName(element); }, getElement: function (id) { var item = getItem(id); return item ? item.element : null; }, getOwnerID: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element || !element._owner) { return null; } return element._owner._debugID; }, getParentID: function (id) { var item = getItem(id); return item ? item.parentID : null; }, getSource: function (id) { var item = getItem(id); var element = item ? item.element : null; var source = element != null ? element._source : null; return source; }, getText: function (id) { var element = ReactComponentTreeHook.getElement(id); if (typeof element === 'string') { return element; } else if (typeof element === 'number') { return '' + element; } else { return null; } }, getUpdateCount: function (id) { var item = getItem(id); return item ? item.updateCount : 0; }, getRootIDs: getRootIDs, getRegisteredIDs: getItemIDs, pushNonStandardWarningStack: function (isCreatingElement, currentSource) { if (typeof console.reactStack !== 'function') { return; } var stack = []; var currentOwner = ReactCurrentOwner.current; var id = currentOwner && currentOwner._debugID; try { if (isCreatingElement) { stack.push({ name: id ? ReactComponentTreeHook.getDisplayName(id) : null, fileName: currentSource ? currentSource.fileName : null, lineNumber: currentSource ? currentSource.lineNumber : null }); } while (id) { var element = ReactComponentTreeHook.getElement(id); var parentID = ReactComponentTreeHook.getParentID(id); var ownerID = ReactComponentTreeHook.getOwnerID(id); var ownerName = ownerID ? ReactComponentTreeHook.getDisplayName(ownerID) : null; var source = element && element._source; stack.push({ name: ownerName, fileName: source ? source.fileName : null, lineNumber: source ? source.lineNumber : null }); id = parentID; } } catch (err) { // Internal state is messed up. // Stop building the stack (it's just a nice to have). } console.reactStack(stack); }, popNonStandardWarningStack: function () { if (typeof console.reactStackEnd !== 'function') { return; } console.reactStackEnd(); } }; module.exports = ReactComponentTreeHook; },{"./ReactCurrentOwner":31,"./reactProdInvariant":47,"fbjs/lib/invariant":4,"fbjs/lib/warning":5}],31:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; },{}],32:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactElement = require('./ReactElement'); /** * Create a factory that creates HTML tag elements. * * @private */ var createDOMFactory = ReactElement.createFactory; if ("production" !== 'production') { var ReactElementValidator = require('./ReactElementValidator'); createDOMFactory = ReactElementValidator.createFactory; } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * * @public */ var ReactDOMFactories = { a: createDOMFactory('a'), abbr: createDOMFactory('abbr'), address: createDOMFactory('address'), area: createDOMFactory('area'), article: createDOMFactory('article'), aside: createDOMFactory('aside'), audio: createDOMFactory('audio'), b: createDOMFactory('b'), base: createDOMFactory('base'), bdi: createDOMFactory('bdi'), bdo: createDOMFactory('bdo'), big: createDOMFactory('big'), blockquote: createDOMFactory('blockquote'), body: createDOMFactory('body'), br: createDOMFactory('br'), button: createDOMFactory('button'), canvas: createDOMFactory('canvas'), caption: createDOMFactory('caption'), cite: createDOMFactory('cite'), code: createDOMFactory('code'), col: createDOMFactory('col'), colgroup: createDOMFactory('colgroup'), data: createDOMFactory('data'), datalist: createDOMFactory('datalist'), dd: createDOMFactory('dd'), del: createDOMFactory('del'), details: createDOMFactory('details'), dfn: createDOMFactory('dfn'), dialog: createDOMFactory('dialog'), div: createDOMFactory('div'), dl: createDOMFactory('dl'), dt: createDOMFactory('dt'), em: createDOMFactory('em'), embed: createDOMFactory('embed'), fieldset: createDOMFactory('fieldset'), figcaption: createDOMFactory('figcaption'), figure: createDOMFactory('figure'), footer: createDOMFactory('footer'), form: createDOMFactory('form'), h1: createDOMFactory('h1'), h2: createDOMFactory('h2'), h3: createDOMFactory('h3'), h4: createDOMFactory('h4'), h5: createDOMFactory('h5'), h6: createDOMFactory('h6'), head: createDOMFactory('head'), header: createDOMFactory('header'), hgroup: createDOMFactory('hgroup'), hr: createDOMFactory('hr'), html: createDOMFactory('html'), i: createDOMFactory('i'), iframe: createDOMFactory('iframe'), img: createDOMFactory('img'), input: createDOMFactory('input'), ins: createDOMFactory('ins'), kbd: createDOMFactory('kbd'), keygen: createDOMFactory('keygen'), label: createDOMFactory('label'), legend: createDOMFactory('legend'), li: createDOMFactory('li'), link: createDOMFactory('link'), main: createDOMFactory('main'), map: createDOMFactory('map'), mark: createDOMFactory('mark'), menu: createDOMFactory('menu'), menuitem: createDOMFactory('menuitem'), meta: createDOMFactory('meta'), meter: createDOMFactory('meter'), nav: createDOMFactory('nav'), noscript: createDOMFactory('noscript'), object: createDOMFactory('object'), ol: createDOMFactory('ol'), optgroup: createDOMFactory('optgroup'), option: createDOMFactory('option'), output: createDOMFactory('output'), p: createDOMFactory('p'), param: createDOMFactory('param'), picture: createDOMFactory('picture'), pre: createDOMFactory('pre'), progress: createDOMFactory('progress'), q: createDOMFactory('q'), rp: createDOMFactory('rp'), rt: createDOMFactory('rt'), ruby: createDOMFactory('ruby'), s: createDOMFactory('s'), samp: createDOMFactory('samp'), script: createDOMFactory('script'), section: createDOMFactory('section'), select: createDOMFactory('select'), small: createDOMFactory('small'), source: createDOMFactory('source'), span: createDOMFactory('span'), strong: createDOMFactory('strong'), style: createDOMFactory('style'), sub: createDOMFactory('sub'), summary: createDOMFactory('summary'), sup: createDOMFactory('sup'), table: createDOMFactory('table'), tbody: createDOMFactory('tbody'), td: createDOMFactory('td'), textarea: createDOMFactory('textarea'), tfoot: createDOMFactory('tfoot'), th: createDOMFactory('th'), thead: createDOMFactory('thead'), time: createDOMFactory('time'), title: createDOMFactory('title'), tr: createDOMFactory('tr'), track: createDOMFactory('track'), u: createDOMFactory('u'), ul: createDOMFactory('ul'), 'var': createDOMFactory('var'), video: createDOMFactory('video'), wbr: createDOMFactory('wbr'), // SVG circle: createDOMFactory('circle'), clipPath: createDOMFactory('clipPath'), defs: createDOMFactory('defs'), ellipse: createDOMFactory('ellipse'), g: createDOMFactory('g'), image: createDOMFactory('image'), line: createDOMFactory('line'), linearGradient: createDOMFactory('linearGradient'), mask: createDOMFactory('mask'), path: createDOMFactory('path'), pattern: createDOMFactory('pattern'), polygon: createDOMFactory('polygon'), polyline: createDOMFactory('polyline'), radialGradient: createDOMFactory('radialGradient'), rect: createDOMFactory('rect'), stop: createDOMFactory('stop'), svg: createDOMFactory('svg'), text: createDOMFactory('text'), tspan: createDOMFactory('tspan') }; module.exports = ReactDOMFactories; },{"./ReactElement":33,"./ReactElementValidator":35}],33:[function(require,module,exports){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = require('object-assign'); var ReactCurrentOwner = require('./ReactCurrentOwner'); var warning = require('fbjs/lib/warning'); var canDefineProperty = require('./canDefineProperty'); var hasOwnProperty = Object.prototype.hasOwnProperty; var REACT_ELEMENT_TYPE = require('./ReactElementSymbol'); var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown; function hasValidRef(config) { if ("production" !== 'production') { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { if ("production" !== 'production') { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; "production" !== 'production' ? warning(false, '%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)', displayName) : void 0; } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; "production" !== 'production' ? warning(false, '%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)', displayName) : void 0; } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if ("production" !== 'production') { // The validation flag is currently mutative. We put it 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. element._store = {}; // 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. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._source = source; } if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement */ ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; } if (hasValidKey(config)) { key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, 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]; } if ("production" !== 'production') { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if ("production" !== 'production') { if (key || ref) { if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; /** * Return a function that produces ReactElements of a given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory */ 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`. // 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.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; /** * Clone and return a new ReactElement using element as the starting point. * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement */ 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; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { 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 ReactElement(element.type, key, ref, self, source, owner, props); }; /** * Verifies the object is a ReactElement. * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; module.exports = ReactElement; },{"./ReactCurrentOwner":31,"./ReactElementSymbol":34,"./canDefineProperty":41,"fbjs/lib/warning":5,"object-assign":16}],34:[function(require,module,exports){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; module.exports = REACT_ELEMENT_TYPE; },{}],35:[function(require,module,exports){ /** * Copyright 2014-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. * */ /** * 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 ReactCurrentOwner = require('./ReactCurrentOwner'); var ReactComponentTreeHook = require('./ReactComponentTreeHook'); var ReactElement = require('./ReactElement'); var checkReactTypeSpec = require('./checkReactTypeSpec'); var canDefineProperty = require('./canDefineProperty'); var getIteratorFn = require('./getIteratorFn'); var warning = require('fbjs/lib/warning'); var lowPriorityWarning = require('./lowPriorityWarning'); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } function getSourceInfoErrorAddendum(elementProps) { if (elementProps !== null && elementProps !== undefined && elementProps.__source !== undefined) { var source = elementProps.__source; var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return ' Check your code at ' + fileName + ':' + lineNumber + '.'; } 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 = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = ' Check the top-level render call using <' + parentName + '>.'; } } return info; } /** * 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. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {}); var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (memoizer[currentComponentErrorInfo]) { return; } memoizer[currentComponentErrorInfo] = true; // 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 childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } "production" !== 'production' ? warning(false, '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', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0; } /** * 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 (typeof node !== 'object') { return; } 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. if (node._store) { 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); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkReactTypeSpec(componentClass.propTypes, element.props, 'prop', name, element, null); } if (typeof componentClass.getDefaultProps === 'function') { "production" !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { if (typeof type !== 'function' && typeof type !== 'string') { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in."; } var sourceInfo = getSourceInfoErrorAddendum(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } info += ReactComponentTreeHook.getCurrentStackAddendum(); var currentSource = props !== null && props !== undefined && props.__source !== undefined ? props.__source : null; ReactComponentTreeHook.pushNonStandardWarningStack(true, currentSource); "production" !== 'production' ? warning(false, 'React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', type == null ? type : typeof type, info) : void 0; ReactComponentTreeHook.popNonStandardWarningStack(); } } 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; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { 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" !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { lowPriorityWarning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.'); Object.defineProperty(this, 'type', { value: type }); return type; } }); } } 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; },{"./ReactComponentTreeHook":30,"./ReactCurrentOwner":31,"./ReactElement":33,"./canDefineProperty":41,"./checkReactTypeSpec":42,"./getIteratorFn":44,"./lowPriorityWarning":45,"fbjs/lib/warning":5}],36:[function(require,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var warning = require('fbjs/lib/warning'); function warnNoop(publicInstance, callerName) { if ("production" !== 'production') { var constructor = publicInstance.constructor; "production" !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * 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) {}, /** * 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 {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { warnNoop(publicInstance, 'forceUpdate'); }, /** * 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) { warnNoop(publicInstance, 'replaceState'); }, /** * 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) { warnNoop(publicInstance, 'setState'); } }; module.exports = ReactNoopUpdateQueue; },{"fbjs/lib/warning":5}],37:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypeLocationNames = {}; if ("production" !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; },{}],38:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _require = require('./ReactElement'), isValidElement = _require.isValidElement; var factory = require('prop-types/factory'); module.exports = factory(isValidElement); },{"./ReactElement":33,"prop-types/factory":20}],39:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; },{}],40:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; module.exports = '15.6.1'; },{}],41:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var canDefineProperty = false; if ("production" !== 'production') { try { // $FlowFixMe https://github.com/facebook/flow/issues/285 Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; },{}],42:[function(require,module,exports){ (function (process){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'); var ReactPropTypeLocationNames = require('./ReactPropTypeLocationNames'); var ReactPropTypesSecret = require('./ReactPropTypesSecret'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && "production" === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = require('./ReactComponentTreeHook'); } var loggedTypeFailures = {}; /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?object} element The React element that is being type-checked * @param {?number} debugID The React component instance that is being type-checked * @private */ function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof typeSpecs[typeSpecName] === 'function') ? "production" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0; error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } "production" !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0; 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 componentStackInfo = ''; if ("production" !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = require('./ReactComponentTreeHook'); } if (debugID !== null) { componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID); } else if (element !== null) { componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element); } } "production" !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0; } } } } module.exports = checkReactTypeSpec; }).call(this,require('_process')) },{"./ReactComponentTreeHook":30,"./ReactPropTypeLocationNames":37,"./ReactPropTypesSecret":39,"./reactProdInvariant":47,"_process":18,"fbjs/lib/invariant":4,"fbjs/lib/warning":5}],43:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _require = require('./ReactBaseClasses'), Component = _require.Component; var _require2 = require('./ReactElement'), isValidElement = _require2.isValidElement; var ReactNoopUpdateQueue = require('./ReactNoopUpdateQueue'); var factory = require('create-react-class/factory'); module.exports = factory(Component, isValidElement, ReactNoopUpdateQueue); },{"./ReactBaseClasses":28,"./ReactElement":33,"./ReactNoopUpdateQueue":36,"create-react-class/factory":1}],44:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /* 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; },{}],45:[function(require,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. * */ 'use strict'; /** * Forked from fbjs/warning: * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js * * Only change is we use console.warn instead of console.error, * and do nothing when 'console' is not supported. * This really simplifies the code. * --- * 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 lowPriorityWarning = function () {}; if ("production" !== 'production') { var printWarning = function (format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { 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) {} }; lowPriorityWarning = function (condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } module.exports = lowPriorityWarning; },{}],46:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'); var ReactElement = require('./ReactElement'); var invariant = require('fbjs/lib/invariant'); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only * * 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 {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? "production" !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0; return children; } module.exports = onlyChild; },{"./ReactElement":33,"./reactProdInvariant":47,"fbjs/lib/invariant":4}],47:[function(require,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; },{}],48:[function(require,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'); var ReactCurrentOwner = require('./ReactCurrentOwner'); var REACT_ELEMENT_TYPE = require('./ReactElementSymbol'); var getIteratorFn = require('./getIteratorFn'); var invariant = require('fbjs/lib/invariant'); var KeyEscapeUtils = require('./KeyEscapeUtils'); var warning = require('fbjs/lib/warning'); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * This is inlined from ReactElement since this file is shared between * isomorphic and renderers. We could extract this to a * */ /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * 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) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @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, 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' || // The following is inlined from ReactElement. This means we can optimize // some checks. React Fiber also inlines this logic for similar purposes. type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) { 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); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, 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 = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if ("production" !== 'production') { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } "production" !== 'production' ? 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.%s', mapsAsChildrenAddendum) : void 0; 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 = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if ("production" !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = " It looks like you're using an element created by a different " + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); !false ? "production" !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } 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, '', callback, traverseContext); } module.exports = traverseAllChildren; },{"./KeyEscapeUtils":25,"./ReactCurrentOwner":31,"./ReactElementSymbol":34,"./getIteratorFn":44,"./reactProdInvariant":47,"fbjs/lib/invariant":4,"fbjs/lib/warning":5}],49:[function(require,module,exports){ 'use strict'; module.exports = require('./lib/React'); },{"./lib/React":27}],50:[function(require,module,exports){ (function() { var URL, URL_PATTERN, defaults, urllite, __hasProp = {}.hasOwnProperty; URL_PATTERN = /^(?:(?:([^:\/?\#]+:)\/+|(\/\/))(?:([a-z0-9-\._~%]+)(?::([a-z0-9-\._~%]+))?@)?(([a-z0-9-\._~%!$&'()*+,;=]+)(?::([0-9]+))?)?)?([^?\#]*?)(\?[^\#]*)?(\#.*)?$/; urllite = function(raw, opts) { return urllite.URL.parse(raw, opts); }; urllite.URL = URL = (function() { function URL(props) { var k, v, _ref; for (k in defaults) { if (!__hasProp.call(defaults, k)) continue; v = defaults[k]; this[k] = (_ref = props[k]) != null ? _ref : v; } this.host || (this.host = this.hostname && this.port ? "" + this.hostname + ":" + this.port : this.hostname ? this.hostname : ''); this.origin || (this.origin = this.protocol ? "" + this.protocol + "//" + this.host : ''); this.isAbsolutePathRelative = !this.host && this.pathname.charAt(0) === '/'; this.isPathRelative = !this.host && this.pathname.charAt(0) !== '/'; this.isRelative = this.isSchemeRelative || this.isAbsolutePathRelative || this.isPathRelative; this.isAbsolute = !this.isRelative; } URL.parse = function(raw) { var m, pathname, protocol; m = raw.toString().match(URL_PATTERN); pathname = m[8] || ''; protocol = m[1]; return new urllite.URL({ protocol: protocol, username: m[3], password: m[4], hostname: m[6], port: m[7], pathname: protocol && pathname.charAt(0) !== '/' ? "/" + pathname : pathname, search: m[9], hash: m[10], isSchemeRelative: m[2] != null }); }; return URL; })(); defaults = { protocol: '', username: '', password: '', host: '', hostname: '', port: '', pathname: '', search: '', hash: '', origin: '', isSchemeRelative: false }; module.exports = urllite; }).call(this); },{}],51:[function(require,module,exports){ // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. module.exports = wrappy function wrappy (fn, cb) { if (fn && cb) return wrappy(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k] }) return wrapper function wrapper() { var args = new Array(arguments.length) for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } var ret = fn.apply(this, args) var cb = args[args.length-1] if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k] }) } return ret } } },{}],52:[function(require,module,exports){ module.exports = extend function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key] } } } return target } },{}],53:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _once = require('once'); var _once2 = _interopRequireDefault(_once); var _httpplease = require('httpplease'); var _httpplease2 = _interopRequireDefault(_httpplease); var _oldiexdomain = require('httpplease/plugins/oldiexdomain'); var _oldiexdomain2 = _interopRequireDefault(_oldiexdomain); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var http = _httpplease2.default.use(_oldiexdomain2.default); var Status = { PENDING: 'pending', LOADING: 'loading', LOADED: 'loaded', FAILED: 'failed', UNSUPPORTED: 'unsupported' }; var getRequestsByUrl = {}; var loadedIcons = {}; var createGetOrUseCacheForUrl = function createGetOrUseCacheForUrl(url, callback) { if (loadedIcons[url]) { var params = loadedIcons[url]; setTimeout(function () { return callback(params[0], params[1]); }, 0); } if (!getRequestsByUrl[url]) { getRequestsByUrl[url] = []; http.get(url, function (err, res) { getRequestsByUrl[url].forEach(function (cb) { loadedIcons[url] = [err, res]; cb(err, res); }); }); } getRequestsByUrl[url].push(callback); }; var supportsInlineSVG = (0, _once2.default)(function () { if (!document) { return false; } var div = document.createElement('div'); div.innerHTML = '<svg />'; return div.firstChild && div.firstChild.namespaceURI === 'http://www.w3.org/2000/svg'; }); var isSupportedEnvironment = (0, _once2.default)(function () { return ((typeof window !== 'undefined' && window !== null ? window.XMLHttpRequest : false) || (typeof window !== 'undefined' && window !== null ? window.XDomainRequest : false)) && supportsInlineSVG(); }); var uniquifyIDs = function () { var mkAttributePattern = function mkAttributePattern(attr) { return '(?:(?:\\s|\\:)' + attr + ')'; }; var idPattern = new RegExp('(?:(' + mkAttributePattern('id') + ')="([^"]+)")|(?:(' + mkAttributePattern('href') + '|' + mkAttributePattern('role') + '|' + mkAttributePattern('arcrole') + ')="\\#([^"]+)")|(?:="url\\(\\#([^\\)]+)\\)")', 'g'); return function (svgText, svgID) { var uniquifyID = function uniquifyID(id) { return id + '___' + svgID; }; return svgText.replace(idPattern, function (m, p1, p2, p3, p4, p5) { //eslint-disable-line consistent-return if (p2) { return p1 + '="' + uniquifyID(p2) + '"'; } else if (p4) { return p3 + '="#' + uniquifyID(p4) + '"'; } else if (p5) { return '="url(#' + uniquifyID(p5) + ')"'; } }); }; }(); var getHash = function getHash(str) { var chr = void 0; var hash = 0; var i = void 0; var j = void 0; var ref = void 0; if (!str) { return hash; } for (i = j = 0, ref = str.length; ref >= 0 ? j < ref : j > ref; i = ref >= 0 ? ++j : --j) { chr = str.charCodeAt(i); hash = (hash << 5) - hash + chr; hash &= hash; } return hash; }; var InlineSVGError = function (_Error) { _inherits(InlineSVGError, _Error); function InlineSVGError(message) { var _ret; _classCallCheck(this, InlineSVGError); var _this = _possibleConstructorReturn(this, (InlineSVGError.__proto__ || Object.getPrototypeOf(InlineSVGError)).call(this)); _this.name = 'InlineSVGError'; _this.isSupportedBrowser = true; _this.isConfigurationError = false; _this.isUnsupportedBrowserError = false; _this.message = message; return _ret = _this, _possibleConstructorReturn(_this, _ret); } return InlineSVGError; }(Error); var createError = function createError(message, attrs) { var err = new InlineSVGError(message); Object.keys(attrs).forEach(function (k) { err[k] = attrs[k]; }); return err; }; var unsupportedBrowserError = function unsupportedBrowserError(message) { var newMessage = message; if (newMessage === null) { newMessage = 'Unsupported Browser'; } return createError(newMessage, { isSupportedBrowser: false, isUnsupportedBrowserError: true }); }; var configurationError = function configurationError(message) { return createError(message, { isConfigurationError: true }); }; var InlineSVG = function (_React$PureComponent) { _inherits(InlineSVG, _React$PureComponent); function InlineSVG(props) { _classCallCheck(this, InlineSVG); var _this2 = _possibleConstructorReturn(this, (InlineSVG.__proto__ || Object.getPrototypeOf(InlineSVG)).call(this, props)); _this2.state = { status: Status.PENDING }; _this2.handleLoad = _this2.handleLoad.bind(_this2); _this2.isActive = false; return _this2; } _createClass(InlineSVG, [{ key: 'componentWillMount', value: function componentWillMount() { this.isActive = true; } }, { key: 'componentDidMount', value: function componentDidMount() { if (this.state.status === Status.PENDING) { if (this.props.supportTest()) { if (this.props.src) { this.startLoad(); } else { this.fail(configurationError('Missing source')); } } else { this.fail(unsupportedBrowserError()); } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.isActive = false; } }, { key: 'fail', value: function fail(error) { var _this3 = this; var status = error.isUnsupportedBrowserError ? Status.UNSUPPORTED : Status.FAILED; if (this.isActive) { this.setState({ status: status }, function () { if (typeof _this3.props.onError === 'function') { _this3.props.onError(error); } }); } } }, { key: 'handleLoad', value: function handleLoad(err, res) { var _this4 = this; if (err) { this.fail(err); return; } if (this.isActive) { this.setState({ loadedText: res.text, status: Status.LOADED }, function () { return typeof _this4.props.onLoad === 'function' ? _this4.props.onLoad() : null; }); } } }, { key: 'startLoad', value: function startLoad() { if (this.isActive) { this.setState({ status: Status.LOADING }, this.load); } } }, { key: 'load', value: function load() { var match = this.props.src.match(/data:image\/svg[^,]*?(;base64)?,(.*)/); if (match) { return this.handleLoad(null, { text: match[1] ? atob(match[2]) : decodeURIComponent(match[2]) }); } if (this.props.cacheGetRequests) { return createGetOrUseCacheForUrl(this.props.src, this.handleLoad); } return http.get(this.props.src, this.handleLoad); } }, { key: 'getClassName', value: function getClassName() { var className = 'isvg ' + this.state.status; if (this.props.className) { className += ' ' + this.props.className; } return className; } }, { key: 'processSVG', value: function processSVG(svgText) { if (this.props.uniquifyIDs) { return uniquifyIDs(svgText, getHash(this.props.src)); } return svgText; } }, { key: 'renderContents', value: function renderContents() { switch (this.state.status) { case Status.UNSUPPORTED: case Status.FAILED: return this.props.children; default: return this.props.preloader; } } }, { key: 'render', value: function render() { return this.props.wrapper({ style: this.props.style, className: this.getClassName(), dangerouslySetInnerHTML: this.state.loadedText ? { __html: this.processSVG(this.state.loadedText) } : undefined }, this.renderContents()); } }]); return InlineSVG; }(_react2.default.PureComponent); InlineSVG.propTypes = { cacheGetRequests: _propTypes2.default.bool, children: _propTypes2.default.node, className: _propTypes2.default.string, onError: _propTypes2.default.func, onLoad: _propTypes2.default.func, preloader: _propTypes2.default.func, src: _propTypes2.default.string.isRequired, style: _propTypes2.default.object, supportTest: _propTypes2.default.func, uniquifyIDs: _propTypes2.default.bool, wrapper: _propTypes2.default.func }; InlineSVG.defaultProps = { wrapper: _react2.default.createFactory('span'), supportTest: isSupportedEnvironment, uniquifyIDs: true, cacheGetRequests: false }; exports.default = InlineSVG; module.exports = exports['default']; },{"httpplease":7,"httpplease/plugins/oldiexdomain":15,"once":17,"prop-types":23,"react":49}]},{},[53])(53) });
Examples/UIExplorer/js/NavigationExperimental/NavigationCardStack-NavigationHeader-Tabs-example.js
Purii/react-native
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; const NavigationExampleRow = require('./NavigationExampleRow'); const React = require('react'); const ReactNative = require('react-native'); /** * Basic example that shows how to use <NavigationCardStack /> to build * an app with composite navigation system. */ const { Component, PropTypes, } = React; const { NavigationExperimental, ScrollView, StyleSheet, Text, TouchableOpacity, View, } = ReactNative; const { CardStack: NavigationCardStack, Header: NavigationHeader, PropTypes: NavigationPropTypes, StateUtils: NavigationStateUtils, } = NavigationExperimental; // First Step. // Define what app navigation state will look like. function createAppNavigationState(): Object { return { // Three tabs. tabs: { index: 0, routes: [ {key: 'apple'}, {key: 'banana'}, {key: 'orange'}, ], }, // Scenes for the `apple` tab. apple: { index: 0, routes: [{key: 'Apple Home'}], }, // Scenes for the `banana` tab. banana: { index: 0, routes: [{key: 'Banana Home'}], }, // Scenes for the `orange` tab. orange: { index: 0, routes: [{key: 'Orange Home'}], }, }; } // Next step. // Define what app navigation state shall be updated. function updateAppNavigationState( state: Object, action: Object, ): Object { let {type} = action; if (type === 'BackAction') { type = 'pop'; } switch (type) { case 'push': { // Push a route into the scenes stack. const route: Object = action.route; const {tabs} = state; const tabKey = tabs.routes[tabs.index].key; const scenes = state[tabKey]; const nextScenes = NavigationStateUtils.push(scenes, route); if (scenes !== nextScenes) { return { ...state, [tabKey]: nextScenes, }; } break; } case 'pop': { // Pops a route from the scenes stack. const {tabs} = state; const tabKey = tabs.routes[tabs.index].key; const scenes = state[tabKey]; const nextScenes = NavigationStateUtils.pop(scenes); if (scenes !== nextScenes) { return { ...state, [tabKey]: nextScenes, }; } break; } case 'selectTab': { // Switches the tab. const tabKey: string = action.tabKey; const tabs = NavigationStateUtils.jumpTo(state.tabs, tabKey); if (tabs !== state.tabs) { return { ...state, tabs, }; } } } return state; } // Next step. // Defines a helper function that creates a HOC (higher-order-component) // which provides a function `navigate` through component props. The // `navigate` function will be used to invoke navigation changes. // This serves a convenient way for a component to navigate. function createAppNavigationContainer(ComponentClass) { const key = '_yourAppNavigationContainerNavigateCall'; class Container extends Component { static contextTypes = { [key]: PropTypes.func, }; static childContextTypes = { [key]: PropTypes.func.isRequired, }; static propTypes = { navigate: PropTypes.func, }; getChildContext(): Object { return { [key]: this.context[key] || this.props.navigate, }; } render(): React.Element { const navigate = this.context[key] || this.props.navigate; return <ComponentClass {...this.props} navigate={navigate} />; } } return Container; } // Next step. // Define a component for your application that owns the navigation state. class YourApplication extends Component { static propTypes = { onExampleExit: PropTypes.func, }; // This sets up the initial navigation state. constructor(props, context) { super(props, context); // This sets up the initial navigation state. this.state = createAppNavigationState(); this._navigate = this._navigate.bind(this); } render(): React.Element { // User your own navigator (see next step). return ( <YourNavigator appNavigationState={this.state} navigate={this._navigate} /> ); } // This public method is optional. If exists, the UI explorer will call it // the "back button" is pressed. Normally this is the cases for Android only. handleBackAction(): boolean { return this._navigate({type: 'pop'}); } // This handles the navigation state changes. You're free and responsible // to define the API that changes that navigation state. In this exmaple, // we'd simply use a `updateAppNavigationState` to update the navigation // state. _navigate(action: Object): void { if (action.type === 'exit') { // Exits the example. `this.props.onExampleExit` is provided // by the UI Explorer. this.props.onExampleExit && this.props.onExampleExit(); return; } const state = updateAppNavigationState( this.state, action, ); // `updateAppNavigationState` (which uses NavigationStateUtils) gives you // back the same `state` if nothing has changed. You could use // that to avoid redundant re-rendering. if (this.state !== state) { this.setState(state); } } } // Next step. // Define your own controlled navigator. const YourNavigator = createAppNavigationContainer(class extends Component { static propTypes = { appNavigationState: PropTypes.shape({ apple: NavigationPropTypes.navigationState.isRequired, banana: NavigationPropTypes.navigationState.isRequired, orange: NavigationPropTypes.navigationState.isRequired, tabs: NavigationPropTypes.navigationState.isRequired, }), navigate: PropTypes.func.isRequired, }; // This sets up the methods (e.g. Pop, Push) for navigation. constructor(props: any, context: any) { super(props, context); this._back = this._back.bind(this); this._renderHeader = this._renderHeader.bind(this); this._renderScene = this._renderScene.bind(this); } // Now use the `NavigationCardStack` to render the scenes. render(): React.Element { const {appNavigationState} = this.props; const {tabs} = appNavigationState; const tabKey = tabs.routes[tabs.index].key; const scenes = appNavigationState[tabKey]; return ( <View style={styles.navigator}> <NavigationCardStack key={'stack_' + tabKey} onNavigateBack={this._back} navigationState={scenes} renderHeader={this._renderHeader} renderScene={this._renderScene} style={styles.navigatorCardStack} /> <YourTabs navigationState={tabs} /> </View> ); } // Render the header. // The detailed spec of `sceneProps` is defined at `NavigationTypeDefinition` // as type `NavigationSceneRendererProps`. _renderHeader(sceneProps: Object): React.Element { return ( <YourHeader {...sceneProps} /> ); } // Render a scene for route. // The detailed spec of `sceneProps` is defined at `NavigationTypeDefinition` // as type `NavigationSceneRendererProps`. _renderScene(sceneProps: Object): React.Element { return ( <YourScene {...sceneProps} /> ); } _back() { this.props.navigate({type: 'pop'}); } }); // Next step. // Define your own header. const YourHeader = createAppNavigationContainer(class extends Component { static propTypes = { ...NavigationPropTypes.SceneRendererProps, navigate: PropTypes.func.isRequired, }; constructor(props: Object, context: any) { super(props, context); this._back = this._back.bind(this); this._renderTitleComponent = this._renderTitleComponent.bind(this); } render(): React.Element { return ( <NavigationHeader {...this.props} renderTitleComponent={this._renderTitleComponent} onNavigateBack={this._back} /> ); } _back(): void { this.props.navigate({type: 'pop'}); } _renderTitleComponent(props: Object): React.Element { return ( <NavigationHeader.Title> {props.scene.route.key} </NavigationHeader.Title> ); } }); // Next step. // Define your own scene. const YourScene = createAppNavigationContainer(class extends Component { static propTypes = { ...NavigationPropTypes.SceneRendererProps, navigate: PropTypes.func.isRequired, }; constructor(props: Object, context: any) { super(props, context); this._exit = this._exit.bind(this); this._popRoute = this._popRoute.bind(this); this._pushRoute = this._pushRoute.bind(this); } render(): React.Element { return ( <ScrollView> <NavigationExampleRow text="Push Route" onPress={this._pushRoute} /> <NavigationExampleRow text="Pop Route" onPress={this._popRoute} /> <NavigationExampleRow text="Exit Header + Scenes + Tabs Example" onPress={this._exit} /> </ScrollView> ); } _pushRoute(): void { // Just push a route with a new unique key. const route = {key: '[' + this.props.scenes.length + ']-' + Date.now()}; this.props.navigate({type: 'push', route}); } _popRoute(): void { this.props.navigate({type: 'pop'}); } _exit(): void { this.props.navigate({type: 'exit'}); } }); // Next step. // Define your own tabs. const YourTabs = createAppNavigationContainer(class extends Component { static propTypes = { navigationState: NavigationPropTypes.navigationState.isRequired, navigate: PropTypes.func.isRequired, }; constructor(props: Object, context: any) { super(props, context); } render(): React.Element { return ( <View style={styles.tabs}> {this.props.navigationState.routes.map(this._renderTab, this)} </View> ); } _renderTab(route: Object, index: number): React.Element { return ( <YourTab key={route.key} route={route} selected={this.props.navigationState.index === index} /> ); } }); // Next step. // Define your own Tab const YourTab = createAppNavigationContainer(class extends Component { static propTypes = { navigate: PropTypes.func.isRequired, route: NavigationPropTypes.navigationRoute.isRequired, selected: PropTypes.bool.isRequired, }; constructor(props: Object, context: any) { super(props, context); this._onPress = this._onPress.bind(this); } render(): React.Element { const style = [styles.tabText]; if (this.props.selected) { style.push(styles.tabSelected); } return ( <TouchableOpacity style={styles.tab} onPress={this._onPress}> <Text style={style}> {this.props.route.key} </Text> </TouchableOpacity> ); } _onPress() { this.props.navigate({type: 'selectTab', tabKey: this.props.route.key}); } }); const styles = StyleSheet.create({ navigator: { flex: 1, }, navigatorCardStack: { flex: 20, }, tabs: { flex: 1, flexDirection: 'row', }, tab: { alignItems: 'center', backgroundColor: '#fff', flex: 1, justifyContent: 'center', }, tabText: { color: '#222', fontWeight: '500', }, tabSelected: { color: 'blue', }, }); module.exports = YourApplication;
ajax/libs/react-instantsearch/4.5.0/Dom.js
ahocevar/cdnjs
/*! ReactInstantSearch 4.5.0 | © Algolia, inc. | https://community.algolia.com/react-instantsearch */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Dom = {}),global.React)); }(this, (function (exports,React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } function nextTick(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; var title = 'browser'; var platform = 'browser'; var browser = true; var env = {}; var argv = []; var version = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; var config = {}; function noop() {} var on = noop; var addListener = noop; var once = noop; var off = noop; var removeListener = noop; var removeAllListeners = noop; var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); } function cwd() { return '/'; } function chdir(dir) { throw new Error('process.chdir is not supported'); } function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { return new Date().getTime(); }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp) { var clocktime = performanceNow.call(performance) * 1e-3; var seconds = Math.floor(clocktime); var nanoseconds = Math.floor(clocktime % 1 * 1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds < 0) { seconds--; nanoseconds += 1e9; } } return [seconds, nanoseconds]; } var startTime = new Date(); function uptime() { var currentTime = new Date(); var dif = currentTime - startTime; return dif / 1000; } var process = { nextTick: nextTick, title: title, browser: browser, env: env, argv: argv, version: version, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime }; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function commonjsRequire () { throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /** * 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 makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; var emptyFunction_1 = emptyFunction; function invariant(condition, format, a, b, c, d, e, f) { if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } var invariant_1 = invariant; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /** * 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. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret; var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret_1) { // It is still safe when called from React. return; } invariant_1( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); } shim.isRequired = shim; function getShim() { return shim; } // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim }; ReactPropTypes.checkPropTypes = emptyFunction_1; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var propTypes = createCommonjsModule(function (module) { /** * 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. */ { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = factoryWithThrowingShims(); } }); /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } var _isPrototype = isPrototype; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var _overArg = overArg; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = _overArg(Object.keys, Object); var _nativeKeys = nativeKeys; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto$1.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$1.call(object, key) && key != 'constructor') { result.push(key); } } return result; } var _baseKeys = baseKeys; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var _freeGlobal = freeGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = _freeGlobal || freeSelf || Function('return this')(); var _root = root; /** Built-in value references. */ var Symbol$1 = _root.Symbol; var _Symbol = Symbol$1; /** Used for built-in method references. */ var objectProto$2 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$2.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto$2.toString; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty$2.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var _getRawTag = getRawTag; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$3.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } var _objectToString = objectToString; /** `Object#toString` result references. */ var nullTag = '[object Null]'; var undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag$1 && symToStringTag$1 in Object(value)) ? _getRawTag(value) : _objectToString(value); } var _baseGetTag = baseGetTag; /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } var isObject_1 = isObject; /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]'; var funcTag = '[object Function]'; var genTag = '[object GeneratorFunction]'; var proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject_1(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = _baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_1 = isFunction; /** Used to detect overreaching core-js shims. */ var coreJsData = _root['__core-js_shared__']; var _coreJsData = coreJsData; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } var _isMasked = isMasked; /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } var _toSource = toSource; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto$1 = Function.prototype; var objectProto$4 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$1 = funcProto$1.toString; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$4.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$3).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject_1(value) || _isMasked(value)) { return false; } var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; return pattern.test(_toSource(value)); } var _baseIsNative = baseIsNative; /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } var _getValue = getValue; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = _getValue(object, key); return _baseIsNative(value) ? value : undefined; } var _getNative = getNative; /* Built-in method references that are verified to be native. */ var DataView = _getNative(_root, 'DataView'); var _DataView = DataView; /* Built-in method references that are verified to be native. */ var Map = _getNative(_root, 'Map'); var _Map = Map; /* Built-in method references that are verified to be native. */ var Promise$1 = _getNative(_root, 'Promise'); var _Promise = Promise$1; /* Built-in method references that are verified to be native. */ var Set = _getNative(_root, 'Set'); var _Set = Set; /* Built-in method references that are verified to be native. */ var WeakMap = _getNative(_root, 'WeakMap'); var _WeakMap = WeakMap; /** `Object#toString` result references. */ var mapTag = '[object Map]'; var objectTag = '[object Object]'; var promiseTag = '[object Promise]'; var setTag = '[object Set]'; var weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = _toSource(_DataView); var mapCtorString = _toSource(_Map); var promiseCtorString = _toSource(_Promise); var setCtorString = _toSource(_Set); var weakMapCtorString = _toSource(_WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag) || (_Map && getTag(new _Map) != mapTag) || (_Promise && getTag(_Promise.resolve()) != promiseTag) || (_Set && getTag(new _Set) != setTag) || (_WeakMap && getTag(new _WeakMap) != weakMapTag)) { getTag = function(value) { var result = _baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? _toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } var _getTag = getTag; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } var isObjectLike_1 = isObjectLike; /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike_1(value) && _baseGetTag(value) == argsTag; } var _baseIsArguments = baseIsArguments; /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$4 = objectProto$5.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto$5.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { return isObjectLike_1(value) && hasOwnProperty$4.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; var isArguments_1 = isArguments; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; var isArray_1 = isArray; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } var isLength_1 = isLength; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength_1(value.length) && !isFunction_1(value); } var isArrayLike_1 = isArrayLike; /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } var stubFalse_1 = stubFalse; var isBuffer_1 = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse_1; module.exports = isBuffer; }); /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]'; var arrayTag = '[object Array]'; var boolTag = '[object Boolean]'; var dateTag = '[object Date]'; var errorTag = '[object Error]'; var funcTag$1 = '[object Function]'; var mapTag$1 = '[object Map]'; var numberTag = '[object Number]'; var objectTag$1 = '[object Object]'; var regexpTag = '[object RegExp]'; var setTag$1 = '[object Set]'; var stringTag = '[object String]'; var weakMapTag$1 = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]'; var dataViewTag$1 = '[object DataView]'; var float32Tag = '[object Float32Array]'; var float64Tag = '[object Float64Array]'; var int8Tag = '[object Int8Array]'; var int16Tag = '[object Int16Array]'; var int32Tag = '[object Int32Array]'; var uint8Tag = '[object Uint8Array]'; var uint8ClampedTag = '[object Uint8ClampedArray]'; var uint16Tag = '[object Uint16Array]'; var uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$1] = typedArrayTags[numberTag] = typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = typedArrayTags[setTag$1] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag$1] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; } var _baseIsTypedArray = baseIsTypedArray; /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } var _baseUnary = baseUnary; var _nodeUtil = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && _freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; }); /* Node.js helper references. */ var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; var isTypedArray_1 = isTypedArray; /** `Object#toString` result references. */ var mapTag$2 = '[object Map]'; var setTag$2 = '[object Set]'; /** Used for built-in method references. */ var objectProto$6 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$5 = objectProto$6.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike_1(value) && (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) { return !value.length; } var tag = _getTag(value); if (tag == mapTag$2 || tag == setTag$2) { return !value.size; } if (_isPrototype(value)) { return !_baseKeys(value).length; } for (var key in value) { if (hasOwnProperty$5.call(value, key)) { return false; } } return true; } var isEmpty_1 = isEmpty; /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } var _arrayMap = arrayMap; /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } var _listCacheClear = listCacheClear; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } var eq_1 = eq; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq_1(array[length][0], key)) { return length; } } return -1; } var _assocIndexOf = assocIndexOf; /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } var _listCacheDelete = listCacheDelete; /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = _assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } var _listCacheGet = listCacheGet; /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return _assocIndexOf(this.__data__, key) > -1; } var _listCacheHas = listCacheHas; /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } var _listCacheSet = listCacheSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = _listCacheClear; ListCache.prototype['delete'] = _listCacheDelete; ListCache.prototype.get = _listCacheGet; ListCache.prototype.has = _listCacheHas; ListCache.prototype.set = _listCacheSet; var _ListCache = ListCache; /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new _ListCache; this.size = 0; } var _stackClear = stackClear; /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } var _stackDelete = stackDelete; /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } var _stackGet = stackGet; /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } var _stackHas = stackHas; /* Built-in method references that are verified to be native. */ var nativeCreate = _getNative(Object, 'create'); var _nativeCreate = nativeCreate; /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; this.size = 0; } var _hashClear = hashClear; /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } var _hashDelete = hashDelete; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto$7 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$6 = objectProto$7.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (_nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty$6.call(data, key) ? data[key] : undefined; } var _hashGet = hashGet; /** Used for built-in method references. */ var objectProto$8 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$7 = objectProto$8.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key); } var _hashHas = hashHas; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; return this; } var _hashSet = hashSet; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = _hashClear; Hash.prototype['delete'] = _hashDelete; Hash.prototype.get = _hashGet; Hash.prototype.has = _hashHas; Hash.prototype.set = _hashSet; var _Hash = Hash; /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new _Hash, 'map': new (_Map || _ListCache), 'string': new _Hash }; } var _mapCacheClear = mapCacheClear; /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } var _isKeyable = isKeyable; /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } var _getMapData = getMapData; /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = _getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } var _mapCacheDelete = mapCacheDelete; /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return _getMapData(this, key).get(key); } var _mapCacheGet = mapCacheGet; /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return _getMapData(this, key).has(key); } var _mapCacheHas = mapCacheHas; /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = _getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } var _mapCacheSet = mapCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = _mapCacheClear; MapCache.prototype['delete'] = _mapCacheDelete; MapCache.prototype.get = _mapCacheGet; MapCache.prototype.has = _mapCacheHas; MapCache.prototype.set = _mapCacheSet; var _MapCache = MapCache; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof _ListCache) { var pairs = data.__data__; if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new _MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } var _stackSet = stackSet; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new _ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = _stackClear; Stack.prototype['delete'] = _stackDelete; Stack.prototype.get = _stackGet; Stack.prototype.has = _stackHas; Stack.prototype.set = _stackSet; var _Stack = Stack; /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } var _arrayEach = arrayEach; var defineProperty = (function() { try { var func = _getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); var _defineProperty = defineProperty; /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && _defineProperty) { _defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } var _baseAssignValue = baseAssignValue; /** Used for built-in method references. */ var objectProto$9 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$8 = objectProto$9.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty$8.call(object, key) && eq_1(objValue, value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignValue = assignValue; /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { _baseAssignValue(object, key, newValue); } else { _assignValue(object, key, newValue); } } return object; } var _copyObject = copyObject; /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } var _baseTimes = baseTimes; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER$1 : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } var _isIndex = isIndex; /** Used for built-in method references. */ var objectProto$10 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$9 = objectProto$10.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty$9.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. _isIndex(key, length) ))) { result.push(key); } } return result; } var _arrayLikeKeys = arrayLikeKeys; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); } var keys_1 = keys; /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && _copyObject(source, keys_1(source), object); } var _baseAssign = baseAssign; /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } var _nativeKeysIn = nativeKeysIn; /** Used for built-in method references. */ var objectProto$11 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$10 = objectProto$11.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject_1(object)) { return _nativeKeysIn(object); } var isProto = _isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty$10.call(object, key)))) { result.push(key); } } return result; } var _baseKeysIn = baseKeysIn; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn$1(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object); } var keysIn_1 = keysIn$1; /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && _copyObject(source, keysIn_1(source), object); } var _baseAssignIn = baseAssignIn; var _cloneBuffer = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; }); /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } var _copyArray = copyArray; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } var _arrayFilter = arrayFilter; /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } var stubArray_1 = stubArray; /** Used for built-in method references. */ var objectProto$12 = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable$1 = objectProto$12.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { if (object == null) { return []; } object = Object(object); return _arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable$1.call(object, symbol); }); }; var _getSymbols = getSymbols; /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return _copyObject(source, _getSymbols(source), object); } var _copySymbols = copySymbols; /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } var _arrayPush = arrayPush; /** Built-in value references. */ var getPrototype = _overArg(Object.getPrototypeOf, Object); var _getPrototype = getPrototype; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols$1 = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) { var result = []; while (object) { _arrayPush(result, _getSymbols(object)); object = _getPrototype(object); } return result; }; var _getSymbolsIn = getSymbolsIn; /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return _copyObject(source, _getSymbolsIn(source), object); } var _copySymbolsIn = copySymbolsIn; /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); } var _baseGetAllKeys = baseGetAllKeys; /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return _baseGetAllKeys(object, keys_1, _getSymbols); } var _getAllKeys = getAllKeys; /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn); } var _getAllKeysIn = getAllKeysIn; /** Used for built-in method references. */ var objectProto$13 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$11 = objectProto$13.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty$11.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } var _initCloneArray = initCloneArray; /** Built-in value references. */ var Uint8Array = _root.Uint8Array; var _Uint8Array = Uint8Array; /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new _Uint8Array(result).set(new _Uint8Array(arrayBuffer)); return result; } var _cloneArrayBuffer = cloneArrayBuffer; /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } var _cloneDataView = cloneDataView; /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } var _addMapEntry = addMapEntry; /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } var _arrayReduce = arrayReduce; /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } var _mapToArray = mapToArray; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(_mapToArray(map), CLONE_DEEP_FLAG) : _mapToArray(map); return _arrayReduce(array, _addMapEntry, new map.constructor); } var _cloneMap = cloneMap; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } var _cloneRegExp = cloneRegExp; /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } var _addSetEntry = addSetEntry; /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } var _setToArray = setToArray; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$1 = 1; /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(_setToArray(set), CLONE_DEEP_FLAG$1) : _setToArray(set); return _arrayReduce(array, _addSetEntry, new set.constructor); } var _cloneSet = cloneSet; /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol ? _Symbol.prototype : undefined; var symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } var _cloneSymbol = cloneSymbol; /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } var _cloneTypedArray = cloneTypedArray; /** `Object#toString` result references. */ var boolTag$1 = '[object Boolean]'; var dateTag$1 = '[object Date]'; var mapTag$3 = '[object Map]'; var numberTag$1 = '[object Number]'; var regexpTag$1 = '[object RegExp]'; var setTag$3 = '[object Set]'; var stringTag$1 = '[object String]'; var symbolTag = '[object Symbol]'; var arrayBufferTag$1 = '[object ArrayBuffer]'; var dataViewTag$2 = '[object DataView]'; var float32Tag$1 = '[object Float32Array]'; var float64Tag$1 = '[object Float64Array]'; var int8Tag$1 = '[object Int8Array]'; var int16Tag$1 = '[object Int16Array]'; var int32Tag$1 = '[object Int32Array]'; var uint8Tag$1 = '[object Uint8Array]'; var uint8ClampedTag$1 = '[object Uint8ClampedArray]'; var uint16Tag$1 = '[object Uint16Array]'; var uint32Tag$1 = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag$1: return _cloneArrayBuffer(object); case boolTag$1: case dateTag$1: return new Ctor(+object); case dataViewTag$2: return _cloneDataView(object, isDeep); case float32Tag$1: case float64Tag$1: case int8Tag$1: case int16Tag$1: case int32Tag$1: case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: return _cloneTypedArray(object, isDeep); case mapTag$3: return _cloneMap(object, isDeep, cloneFunc); case numberTag$1: case stringTag$1: return new Ctor(object); case regexpTag$1: return _cloneRegExp(object); case setTag$3: return _cloneSet(object, isDeep, cloneFunc); case symbolTag: return _cloneSymbol(object); } } var _initCloneByTag = initCloneByTag; /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject_1(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); var _baseCreate = baseCreate; /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !_isPrototype(object)) ? _baseCreate(_getPrototype(object)) : {}; } var _initCloneObject = initCloneObject; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$2 = 1; var CLONE_FLAT_FLAG = 2; var CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag$2 = '[object Arguments]'; var arrayTag$1 = '[object Array]'; var boolTag$2 = '[object Boolean]'; var dateTag$2 = '[object Date]'; var errorTag$1 = '[object Error]'; var funcTag$2 = '[object Function]'; var genTag$1 = '[object GeneratorFunction]'; var mapTag$4 = '[object Map]'; var numberTag$2 = '[object Number]'; var objectTag$2 = '[object Object]'; var regexpTag$2 = '[object RegExp]'; var setTag$4 = '[object Set]'; var stringTag$2 = '[object String]'; var symbolTag$1 = '[object Symbol]'; var weakMapTag$2 = '[object WeakMap]'; var arrayBufferTag$2 = '[object ArrayBuffer]'; var dataViewTag$3 = '[object DataView]'; var float32Tag$2 = '[object Float32Array]'; var float64Tag$2 = '[object Float64Array]'; var int8Tag$2 = '[object Int8Array]'; var int16Tag$2 = '[object Int16Array]'; var int32Tag$2 = '[object Int32Array]'; var uint8Tag$2 = '[object Uint8Array]'; var uint8ClampedTag$2 = '[object Uint8ClampedArray]'; var uint16Tag$2 = '[object Uint16Array]'; var uint32Tag$2 = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] = cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] = cloneableTags[boolTag$2] = cloneableTags[dateTag$2] = cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] = cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] = cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] = cloneableTags[numberTag$2] = cloneableTags[objectTag$2] = cloneableTags[regexpTag$2] = cloneableTags[setTag$4] = cloneableTags[stringTag$2] = cloneableTags[symbolTag$1] = cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] = cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true; cloneableTags[errorTag$1] = cloneableTags[funcTag$2] = cloneableTags[weakMapTag$2] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG$2, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject_1(value)) { return value; } var isArr = isArray_1(value); if (isArr) { result = _initCloneArray(value); if (!isDeep) { return _copyArray(value, result); } } else { var tag = _getTag(value), isFunc = tag == funcTag$2 || tag == genTag$1; if (isBuffer_1(value)) { return _cloneBuffer(value, isDeep); } if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : _initCloneObject(value); if (!isDeep) { return isFlat ? _copySymbolsIn(value, _baseAssignIn(result, value)) : _copySymbols(value, _baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = _initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new _Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); var keysFunc = isFull ? (isFlat ? _getAllKeysIn : _getAllKeys) : (isFlat ? keysIn : keys_1); var props = isArr ? undefined : keysFunc(value); _arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var _baseClone = baseClone; /** `Object#toString` result references. */ var symbolTag$2 = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$2); } var isSymbol_1 = isSymbol; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; var reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray_1(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } var _isKey = isKey; /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || _MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = _MapCache; var memoize_1 = memoize; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize_1(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var _memoizeCapped = memoizeCapped; /** Used to match property names within property paths. */ var reLeadingDot = /^\./; var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = _memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); var _stringToPath = stringToPath; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined; var symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray_1(value)) { // Recursively convert values (susceptible to call stack limits). return _arrayMap(value, baseToString) + ''; } if (isSymbol_1(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } var _baseToString = baseToString; /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : _baseToString(value); } var toString_1 = toString; /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray_1(value)) { return value; } return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); } var _castPath = castPath; /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } var last_1 = last; /** Used as references for various `Number` constants. */ var INFINITY$1 = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol_1(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; } var _toKey = toKey; /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = _castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[_toKey(path[index++])]; } return (index && index == length) ? object : undefined; } var _baseGet = baseGet; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } var _baseSlice = baseSlice; /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1)); } var _parent = parent; /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = _castPath(path, object); object = _parent(object, path); return object == null || delete object[_toKey(last_1(path))]; } var _baseUnset = baseUnset; /** `Object#toString` result references. */ var objectTag$3 = '[object Object]'; /** Used for built-in method references. */ var funcProto$2 = Function.prototype; var objectProto$14 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$2 = funcProto$2.toString; /** Used to check objects for own properties. */ var hasOwnProperty$12 = objectProto$14.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString$2.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) { return false; } var proto = _getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$12.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString; } var isPlainObject_1 = isPlainObject; /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject_1(value) ? undefined : value; } var _customOmitClone = customOmitClone; /** Built-in value references. */ var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } var _isFlattenable = isFlattenable; /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = _isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { _arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } var _baseFlatten = baseFlatten; /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? _baseFlatten(array, 1) : []; } var flatten_1 = flatten; /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } var _apply = apply; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return _apply(func, this, otherArgs); }; } var _overRest = overRest; /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } var constant_1 = constant; /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } var identity_1 = identity; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !_defineProperty ? identity_1 : function(func, string) { return _defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant_1(string), 'writable': true }); }; var _baseSetToString = baseSetToString; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800; var HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } var _shortOut = shortOut; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = _shortOut(_baseSetToString); var _setToString = setToString; /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return _setToString(_overRest(func, undefined, flatten_1), func + ''); } var _flatRest = flatRest; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$3 = 1; var CLONE_FLAT_FLAG$1 = 2; var CLONE_SYMBOLS_FLAG$1 = 4; /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = _flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = _arrayMap(paths, function(path) { path = _castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); _copyObject(object, _getAllKeysIn(object), result); if (isDeep) { result = _baseClone(result, CLONE_DEEP_FLAG$3 | CLONE_FLAT_FLAG$1 | CLONE_SYMBOLS_FLAG$1, _customOmitClone); } var length = paths.length; while (length--) { _baseUnset(result, paths[length]); } return result; }); var omit_1 = omit; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED$2); return this; } var _setCacheAdd = setCacheAdd; /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } var _setCacheHas = setCacheHas; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new _MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; SetCache.prototype.has = _setCacheHas; var _SetCache = SetCache; /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } var _baseFindIndex = baseFindIndex; /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } var _baseIsNaN = baseIsNaN; /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } var _strictIndexOf = strictIndexOf; /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex); } var _baseIndexOf = baseIndexOf; /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && _baseIndexOf(array, value, 0) > -1; } var _arrayIncludes = arrayIncludes; /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } var _arrayIncludesWith = arrayIncludesWith; /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } var _cacheHas = cacheHas; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? _arrayIncludesWith : _arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = _arrayMap(array, _baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new _SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? _cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? _cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } var _baseIntersection = baseIntersection; /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return _setToString(_overRest(func, start, identity_1), func + ''); } var _baseRest = baseRest; /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike_1(value) && isArrayLike_1(value); } var isArrayLikeObject_1 = isArrayLikeObject; /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject_1(value) ? value : []; } var _castArrayLikeObject = castArrayLikeObject; /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = _baseRest(function(arrays) { var mapped = _arrayMap(arrays, _castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? _baseIntersection(mapped) : []; }); var intersection_1 = intersection; /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } var _createBaseFor = createBaseFor; /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = _createBaseFor(); var _baseFor = baseFor; /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && _baseFor(object, iteratee, keys_1); } var _baseForOwn = baseForOwn; /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity_1; } var _castFunction = castFunction; /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && _baseForOwn(object, _castFunction(iteratee)); } var forOwn_1 = forOwn; /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike_1(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } var _createBaseEach = createBaseEach; /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = _createBaseEach(_baseForOwn); var _baseEach = baseEach; /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray_1(collection) ? _arrayEach : _baseEach; return func(collection, _castFunction(iteratee)); } var forEach_1 = forEach; /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; _baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } var _baseFilter = baseFilter; /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } var _arraySome = arraySome; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; var COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!_arraySome(other, function(othValue, othIndex) { if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } var _equalArrays = equalArrays; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$1 = 1; var COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ var boolTag$3 = '[object Boolean]'; var dateTag$3 = '[object Date]'; var errorTag$2 = '[object Error]'; var mapTag$5 = '[object Map]'; var numberTag$3 = '[object Number]'; var regexpTag$3 = '[object RegExp]'; var setTag$5 = '[object Set]'; var stringTag$3 = '[object String]'; var symbolTag$3 = '[object Symbol]'; var arrayBufferTag$3 = '[object ArrayBuffer]'; var dataViewTag$4 = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined; var symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag$4: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag$3: if ((object.byteLength != other.byteLength) || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { return false; } return true; case boolTag$3: case dateTag$3: case numberTag$3: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq_1(+object, +other); case errorTag$2: return object.name == other.name && object.message == other.message; case regexpTag$3: case stringTag$3: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag$5: var convert = _mapToArray; case setTag$5: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; convert || (convert = _setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag$3: if (symbolValueOf$1) { return symbolValueOf$1.call(object) == symbolValueOf$1.call(other); } } return false; } var _equalByTag = equalByTag; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$2 = 1; /** Used for built-in method references. */ var objectProto$15 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$13 = objectProto$15.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, objProps = _getAllKeys(object), objLength = objProps.length, othProps = _getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty$13.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } var _equalObjects = equalObjects; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$3 = 1; /** `Object#toString` result references. */ var argsTag$3 = '[object Arguments]'; var arrayTag$2 = '[object Array]'; var objectTag$4 = '[object Object]'; /** Used for built-in method references. */ var objectProto$16 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$14 = objectProto$16.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray_1(object), othIsArr = isArray_1(other), objTag = objIsArr ? arrayTag$2 : _getTag(object), othTag = othIsArr ? arrayTag$2 : _getTag(other); objTag = objTag == argsTag$3 ? objectTag$4 : objTag; othTag = othTag == argsTag$3 ? objectTag$4 : othTag; var objIsObj = objTag == objectTag$4, othIsObj = othTag == objectTag$4, isSameTag = objTag == othTag; if (isSameTag && isBuffer_1(object)) { if (!isBuffer_1(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new _Stack); return (objIsArr || isTypedArray_1(object)) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { var objIsWrapped = objIsObj && hasOwnProperty$14.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty$14.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new _Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new _Stack); return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); } var _baseIsEqualDeep = baseIsEqualDeep; /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } var _baseIsEqual = baseIsEqual; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$4 = 1; var COMPARE_UNORDERED_FLAG$2 = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result )) { return false; } } } return true; } var _baseIsMatch = baseIsMatch; /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject_1(value); } var _isStrictComparable = isStrictComparable; /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys_1(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, _isStrictComparable(value)]; } return result; } var _getMatchData = getMatchData; /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } var _matchesStrictComparable = matchesStrictComparable; /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = _getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return _matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || _baseIsMatch(object, source, matchData); }; } var _baseMatches = baseMatches; /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : _baseGet(object, path); return result === undefined ? defaultValue : result; } var get_1 = get; /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } var _baseHasIn = baseHasIn; /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = _castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = _toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); } var _hasPath = hasPath; /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && _hasPath(object, path, _baseHasIn); } var hasIn_1 = hasIn; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$5 = 1; var COMPARE_UNORDERED_FLAG$3 = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (_isKey(path) && _isStrictComparable(srcValue)) { return _matchesStrictComparable(_toKey(path), srcValue); } return function(object) { var objValue = get_1(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); }; } var _baseMatchesProperty = baseMatchesProperty; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } var _baseProperty = baseProperty; /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return _baseGet(object, path); }; } var _basePropertyDeep = basePropertyDeep; /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); } var property_1 = property; /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity_1; } if (typeof value == 'object') { return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value); } return property_1(value); } var _baseIteratee = baseIteratee; /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray_1(collection) ? _arrayFilter : _baseFilter; return func(collection, _baseIteratee(predicate, 3)); } var filter_1 = filter; /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike_1(collection) ? Array(collection.length) : []; _baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } var _baseMap = baseMap; /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray_1(collection) ? _arrayMap : _baseMap; return func(collection, _baseIteratee(iteratee, 3)); } var map_1 = map; /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } var _baseReduce = baseReduce; /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray_1(collection) ? _arrayReduce : _baseReduce, initAccum = arguments.length < 3; return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEach); } var reduce_1 = reduce; /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol_1(value)) { return NAN; } if (isObject_1(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject_1(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } var toNumber_1 = toNumber; /** Used as references for various `Number` constants. */ var INFINITY$2 = 1 / 0; var MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber_1(value); if (value === INFINITY$2 || value === -INFINITY$2) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } var toFinite_1 = toFinite; /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite_1(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } var toInteger_1 = toInteger; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$1 = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$1(length + index, 0); } return _baseIndexOf(array, value, index); } var indexOf_1 = indexOf; /** `Object#toString` result references. */ var numberTag$4 = '[object Number]'; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike_1(value) && _baseGetTag(value) == numberTag$4); } var isNumber_1 = isNumber; /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN$1(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber_1(value) && value != +value; } var _isNaN = isNaN$1; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return _baseIsEqual(value, other); } var isEqual_1 = isEqual; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } var isUndefined_1 = isUndefined; /** `Object#toString` result references. */ var stringTag$4 = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$4); } var isString_1 = isString; /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike_1(collection)) { var iteratee = _baseIteratee(predicate, 3); collection = keys_1(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } var _createFind = createFind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$2 = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$2(length + index, 0); } return _baseFindIndex(array, _baseIteratee(predicate, 3), index); } var findIndex_1 = findIndex; /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = _createFind(findIndex_1); var find_1 = find; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : _baseSlice(array, start, end); } var _castSlice = castSlice; /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsEndIndex = charsEndIndex; /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsStartIndex = charsStartIndex; /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } var _asciiToArray = asciiToArray; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff'; var rsComboMarksRange = '\\u0300-\\u036f'; var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; var rsComboSymbolsRange = '\\u20d0-\\u20ff'; var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; var rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } var _hasUnicode = hasUnicode; /** Used to compose unicode character classes. */ var rsAstralRange$1 = '\\ud800-\\udfff'; var rsComboMarksRange$1 = '\\u0300-\\u036f'; var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff'; var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1; var rsVarRange$1 = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange$1 + ']'; var rsCombo = '[' + rsComboRange$1 + ']'; var rsFitz = '\\ud83c[\\udffb-\\udfff]'; var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; var rsNonAstral = '[^' + rsAstralRange$1 + ']'; var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; var rsZWJ$1 = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?'; var rsOptVar = '[' + rsVarRange$1 + ']?'; var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; var rsSeq = rsOptVar + reOptMod + rsOptJoin; var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } var _unicodeToArray = unicodeToArray; /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return _hasUnicode(string) ? _unicodeToArray(string) : _asciiToArray(string); } var _stringToArray = stringToArray; /** Used to match leading and trailing whitespace. */ var reTrim$1 = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString_1(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim$1, ''); } if (!string || !(chars = _baseToString(chars))) { return string; } var strSymbols = _stringToArray(string), chrSymbols = _stringToArray(chars), start = _charsStartIndex(strSymbols, chrSymbols), end = _charsEndIndex(strSymbols, chrSymbols) + 1; return _castSlice(strSymbols, start, end).join(''); } var trim_1 = trim; /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject_1(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike_1(object) && _isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq_1(object[index], value); } return false; } var _isIterateeCall = isIterateeCall; /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return _baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && _isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } var _createAssigner = createAssigner; /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = _createAssigner(function(object, source, srcIndex, customizer) { _copyObject(source, keysIn_1(source), object, customizer); }); var assignInWith_1 = assignInWith; /** Used for built-in method references. */ var objectProto$17 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$15 = objectProto$17.hasOwnProperty; /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq_1(objValue, objectProto$17[key]) && !hasOwnProperty$15.call(object, key))) { return srcValue; } return objValue; } var _customDefaultsAssignIn = customDefaultsAssignIn; /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = _baseRest(function(args) { args.push(undefined, _customDefaultsAssignIn); return _apply(assignInWith_1, undefined, args); }); var defaults_1 = defaults; /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq_1(object[key], value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignMergeValue = assignMergeValue; /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return _copyObject(value, keysIn_1(value)); } var toPlainObject_1 = toPlainObject; /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { _assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray_1(srcValue), isBuff = !isArr && isBuffer_1(srcValue), isTyped = !isArr && !isBuff && isTypedArray_1(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray_1(objValue)) { newValue = objValue; } else if (isArrayLikeObject_1(objValue)) { newValue = _copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = _cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = _cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject_1(srcValue) || isArguments_1(srcValue)) { newValue = objValue; if (isArguments_1(objValue)) { newValue = toPlainObject_1(objValue); } else if (!isObject_1(objValue) || (srcIndex && isFunction_1(objValue))) { newValue = _initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } _assignMergeValue(object, key, newValue); } var _baseMergeDeep = baseMergeDeep; /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } _baseFor(source, function(srcValue, key) { if (isObject_1(srcValue)) { stack || (stack = new _Stack); _baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } _assignMergeValue(object, key, newValue); } }, keysIn_1); } var _baseMerge = baseMerge; /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = _createAssigner(function(object, source, srcIndex) { _baseMerge(object, source, srcIndex); }); var merge_1 = merge; function valToNumber(v) { if (isNumber_1(v)) { return v; } else if (isString_1(v)) { return parseFloat(v); } else if (isArray_1(v)) { return map_1(v, valToNumber); } throw new Error('The value should be a number, a parseable string or an array of those.'); } var valToNumber_1 = valToNumber; function filterState(state, filters) { var partialState = {}; var attributeFilters = filter_1(filters, function(f) { return f.indexOf('attribute:') !== -1; }); var attributes = map_1(attributeFilters, function(aF) { return aF.split(':')[1]; }); if (indexOf_1(attributes, '*') === -1) { forEach_1(attributes, function(attr) { if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) { if (!partialState.facetsRefinements) partialState.facetsRefinements = {}; partialState.facetsRefinements[attr] = state.facetsRefinements[attr]; } if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) { if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {}; partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr]; } if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) { if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {}; partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr]; } var numericRefinements = state.getNumericRefinements(attr); if (!isEmpty_1(numericRefinements)) { if (!partialState.numericRefinements) partialState.numericRefinements = {}; partialState.numericRefinements[attr] = state.numericRefinements[attr]; } }); } else { if (!isEmpty_1(state.numericRefinements)) { partialState.numericRefinements = state.numericRefinements; } if (!isEmpty_1(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements; if (!isEmpty_1(state.disjunctiveFacetsRefinements)) { partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements; } if (!isEmpty_1(state.hierarchicalFacetsRefinements)) { partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements; } } var searchParameters = filter_1( filters, function(f) { return f.indexOf('attribute:') === -1; } ); forEach_1( searchParameters, function(parameterKey) { partialState[parameterKey] = state[parameterKey]; } ); return partialState; } var filterState_1 = filterState; /** * Functions to manipulate refinement lists * * The RefinementList is not formally defined through a prototype but is based * on a specific structure. * * @module SearchParameters.refinementList * * @typedef {string[]} SearchParameters.refinementList.Refinements * @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList */ var lib = { /** * Adds a refinement to a RefinementList * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement, if the value is not a string it will be converted * @return {RefinementList} a new and updated refinement list */ addRefinement: function addRefinement(refinementList, attribute, value) { if (lib.isRefined(refinementList, attribute, value)) { return refinementList; } var valueAsString = '' + value; var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString); var mod = {}; mod[attribute] = facetRefinement; return defaults_1({}, mod, refinementList); }, /** * Removes refinement(s) for an attribute: * - if the value is specified removes the refinement for the value on the attribute * - if no value is specified removes all the refinements for this attribute * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} [value] the value of the refinement * @return {RefinementList} a new and updated refinement lst */ removeRefinement: function removeRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) { return lib.clearRefinement(refinementList, attribute); } var valueAsString = '' + value; return lib.clearRefinement(refinementList, function(v, f) { return attribute === f && valueAsString === v; }); }, /** * Toggles the refinement value for an attribute. * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement * @return {RefinementList} a new and updated list */ toggleRefinement: function toggleRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) throw new Error('toggleRefinement should be used with a value'); if (lib.isRefined(refinementList, attribute, value)) { return lib.removeRefinement(refinementList, attribute, value); } return lib.addRefinement(refinementList, attribute, value); }, /** * Clear all or parts of a RefinementList. Depending on the arguments, three * kinds of behavior can happen: * - if no attribute is provided: clears the whole list * - if an attribute is provided as a string: clears the list for the specific attribute * - if an attribute is provided as a function: discards the elements for which the function returns true * @param {RefinementList} refinementList the initial list * @param {string} [attribute] the attribute or function to discard * @param {string} [refinementType] optional parameter to give more context to the attribute function * @return {RefinementList} a new and updated refinement list */ clearRefinement: function clearRefinement(refinementList, attribute, refinementType) { if (isUndefined_1(attribute)) { return {}; } else if (isString_1(attribute)) { return omit_1(refinementList, attribute); } else if (isFunction_1(attribute)) { return reduce_1(refinementList, function(memo, values, key) { var facetList = filter_1(values, function(value) { return !attribute(value, key, refinementType); }); if (!isEmpty_1(facetList)) memo[key] = facetList; return memo; }, {}); } }, /** * Test if the refinement value is used for the attribute. If no refinement value * is provided, test if the refinementList contains any refinement for the * given attribute. * @param {RefinementList} refinementList the list of refinement * @param {string} attribute name of the attribute * @param {string} [refinementValue] value of the filter/refinement * @return {boolean} */ isRefined: function isRefined(refinementList, attribute, refinementValue) { var indexOf = indexOf_1; var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (isUndefined_1(refinementValue) || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return indexOf(refinementList[attribute], refinementValueAsString) !== -1; } }; var RefinementList = lib; /** * like _.find but using _.isEqual to be able to use it * to find arrays. * @private * @param {any[]} array array to search into * @param {any} searchedValue the value we're looking for * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find_1(array, function(currentValue) { return isEqual_1(currentValue, searchedValue); }); } /** * The facet list is the structure used to store the list of values used to * filter a single attribute. * @typedef {string[]} SearchParameters.FacetList */ /** * Structure to store numeric filters with the operator as the key. The supported operators * are `=`, `>`, `<`, `>=`, `<=` and `!=`. * @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList */ /** * SearchParameters is the data structure that contains all the information * usable for making a search to Algolia API. It doesn't do the search itself, * nor does it contains logic about the parameters. * It is an immutable object, therefore it has been created in a way that each * changes does not change the object itself but returns a copy with the * modification. * This object should probably not be instantiated outside of the helper. It will * be provided when needed. This object is documented for reference as you'll * get it from events generated by the {@link AlgoliaSearchHelper}. * If need be, instantiate the Helper from the factory function {@link SearchParameters.make} * @constructor * @classdesc contains all the parameters of a search * @param {object|SearchParameters} newParameters existing parameters or partial object * for the properties of a new SearchParameters * @see SearchParameters.make * @example <caption>SearchParameters of the first query in * <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption> { "query": "", "disjunctiveFacets": [ "customerReviewCount", "category", "salePrice_range", "manufacturer" ], "maxValuesPerFacet": 30, "page": 0, "hitsPerPage": 10, "facets": [ "type", "shipping" ] } */ function SearchParameters(newParameters) { var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {}; /** * Targeted index. This parameter is mandatory. * @member {string} */ this.index = params.index || ''; // Query /** * Query string of the instant search. The empty string is a valid query. * @member {string} * @see https://www.algolia.com/doc/rest#param-query */ this.query = params.query || ''; // Facets /** * This attribute contains the list of all the conjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.facets = params.facets || []; /** * This attribute contains the list of all the disjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.disjunctiveFacets = params.disjunctiveFacets || []; /** * This attribute contains the list of all the hierarchical facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * Hierarchical facets are a sub type of disjunctive facets that * let you filter faceted attributes hierarchically. * @member {string[]|object[]} */ this.hierarchicalFacets = params.hierarchicalFacets || []; // Refinements /** * This attribute contains all the filters that need to be * applied on the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsRefinements = params.facetsRefinements || {}; /** * This attribute contains all the filters that need to be * excluded from the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters excluded for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsExcludes = params.facetsExcludes || {}; /** * This attribute contains all the filters that need to be * applied on the disjunctive facets. Each facet must be properly * defined in the `disjunctiveFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {}; /** * This attribute contains all the filters that need to be * applied on the numeric attributes. * * The key is the name of the attribute, and the value is the * filters to apply to this attribute. * * When querying algolia, the values stored in this attribute will * be translated into the `numericFilters` attribute. * @member {Object.<string, SearchParameters.OperatorList>} */ this.numericRefinements = params.numericRefinements || {}; /** * This attribute contains all the tags used to refine the query. * * When querying algolia, the values stored in this attribute will * be translated into the `tagFilters` attribute. * @member {string[]} */ this.tagRefinements = params.tagRefinements || []; /** * This attribute contains all the filters that need to be * applied on the hierarchical facets. Each facet must be properly * defined in the `hierarchicalFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. The FacetList values * are structured as a string that contain the values for each level * separated by the configured separator. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {}; /** * Contains the numeric filters in the raw format of the Algolia API. Setting * this parameter is not compatible with the usage of numeric filters methods. * @see https://www.algolia.com/doc/javascript#numericFilters * @member {string} */ this.numericFilters = params.numericFilters; /** * Contains the tag filters in the raw format of the Algolia API. Setting this * parameter is not compatible with the of the add/remove/toggle methods of the * tag api. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.tagFilters = params.tagFilters; /** * Contains the optional tag filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalTagFilters = params.optionalTagFilters; /** * Contains the optional facet filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalFacetFilters = params.optionalFacetFilters; // Misc. parameters /** * Number of hits to be returned by the search API * @member {number} * @see https://www.algolia.com/doc/rest#param-hitsPerPage */ this.hitsPerPage = params.hitsPerPage; /** * Number of values for each faceted attribute * @member {number} * @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet */ this.maxValuesPerFacet = params.maxValuesPerFacet; /** * The current page number * @member {number} * @see https://www.algolia.com/doc/rest#param-page */ this.page = params.page || 0; /** * How the query should be treated by the search engine. * Possible values: prefixAll, prefixLast, prefixNone * @see https://www.algolia.com/doc/rest#param-queryType * @member {string} */ this.queryType = params.queryType; /** * How the typo tolerance behave in the search engine. * Possible values: true, false, min, strict * @see https://www.algolia.com/doc/rest#param-typoTolerance * @member {string} */ this.typoTolerance = params.typoTolerance; /** * Number of characters to wait before doing one character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo * @member {number} */ this.minWordSizefor1Typo = params.minWordSizefor1Typo; /** * Number of characters to wait before doing a second character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos * @member {number} */ this.minWordSizefor2Typos = params.minWordSizefor2Typos; /** * Configure the precision of the proximity ranking criterion * @see https://www.algolia.com/doc/rest#param-minProximity */ this.minProximity = params.minProximity; /** * Should the engine allow typos on numerics. * @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens * @member {boolean} */ this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens; /** * Should the plurals be ignored * @see https://www.algolia.com/doc/rest#param-ignorePlurals * @member {boolean} */ this.ignorePlurals = params.ignorePlurals; /** * Restrict which attribute is searched. * @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes * @member {string} */ this.restrictSearchableAttributes = params.restrictSearchableAttributes; /** * Enable the advanced syntax. * @see https://www.algolia.com/doc/rest#param-advancedSyntax * @member {boolean} */ this.advancedSyntax = params.advancedSyntax; /** * Enable the analytics * @see https://www.algolia.com/doc/rest#param-analytics * @member {boolean} */ this.analytics = params.analytics; /** * Tag of the query in the analytics. * @see https://www.algolia.com/doc/rest#param-analyticsTags * @member {string} */ this.analyticsTags = params.analyticsTags; /** * Enable the synonyms * @see https://www.algolia.com/doc/rest#param-synonyms * @member {boolean} */ this.synonyms = params.synonyms; /** * Should the engine replace the synonyms in the highlighted results. * @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight * @member {boolean} */ this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight; /** * Add some optional words to those defined in the dashboard * @see https://www.algolia.com/doc/rest#param-optionalWords * @member {string} */ this.optionalWords = params.optionalWords; /** * Possible values are "lastWords" "firstWords" "allOptional" "none" (default) * @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults * @member {string} */ this.removeWordsIfNoResults = params.removeWordsIfNoResults; /** * List of attributes to retrieve * @see https://www.algolia.com/doc/rest#param-attributesToRetrieve * @member {string} */ this.attributesToRetrieve = params.attributesToRetrieve; /** * List of attributes to highlight * @see https://www.algolia.com/doc/rest#param-attributesToHighlight * @member {string} */ this.attributesToHighlight = params.attributesToHighlight; /** * Code to be embedded on the left part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPreTag * @member {string} */ this.highlightPreTag = params.highlightPreTag; /** * Code to be embedded on the right part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPostTag * @member {string} */ this.highlightPostTag = params.highlightPostTag; /** * List of attributes to snippet * @see https://www.algolia.com/doc/rest#param-attributesToSnippet * @member {string} */ this.attributesToSnippet = params.attributesToSnippet; /** * Enable the ranking informations in the response, set to 1 to activate * @see https://www.algolia.com/doc/rest#param-getRankingInfo * @member {number} */ this.getRankingInfo = params.getRankingInfo; /** * Remove duplicates based on the index setting attributeForDistinct * @see https://www.algolia.com/doc/rest#param-distinct * @member {boolean|number} */ this.distinct = params.distinct; /** * Center of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundLatLng * @member {string} */ this.aroundLatLng = params.aroundLatLng; /** * Center of the search, retrieve from the user IP. * @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP * @member {boolean} */ this.aroundLatLngViaIP = params.aroundLatLngViaIP; /** * Radius of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundRadius * @member {number} */ this.aroundRadius = params.aroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundPrecision * @member {number} */ this.minimumAroundRadius = params.minimumAroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-minimumAroundRadius * @member {number} */ this.aroundPrecision = params.aroundPrecision; /** * Geo search inside a box. * @see https://www.algolia.com/doc/rest#param-insideBoundingBox * @member {string} */ this.insideBoundingBox = params.insideBoundingBox; /** * Geo search inside a polygon. * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.insidePolygon = params.insidePolygon; /** * Allows to specify an ellipsis character for the snippet when we truncate the text * (added before and after if truncated). * The default value is an empty string and we recommend to set it to "…" * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.snippetEllipsisText = params.snippetEllipsisText; /** * Allows to specify some attributes name on which exact won't be applied. * Attributes are separated with a comma (for example "name,address" ), you can also use a * JSON string array encoding (for example encodeURIComponent('["name","address"]') ). * By default the list is empty. * @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes * @member {string|string[]} */ this.disableExactOnAttributes = params.disableExactOnAttributes; /** * Applies 'exact' on single word queries if the word contains at least 3 characters * and is not a stop word. * Can take two values: true or false. * By default, its set to false. * @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery * @member {boolean} */ this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery; // Undocumented parameters, still needed otherwise we fail this.offset = params.offset; this.length = params.length; var self = this; forOwn_1(params, function checkForUnknownParameter(paramValue, paramName) { if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) { self[paramName] = paramValue; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = keys_1(new SearchParameters()); /** * @private * @param {object} partialState full or part of a state * @return {object} a new object with the number keys as number */ SearchParameters._parseNumbers = function(partialState) { // Do not reparse numbers in SearchParameters, they ought to be parsed already if (partialState instanceof SearchParameters) return partialState; var numbers = {}; var numberKeys = [ 'aroundPrecision', 'aroundRadius', 'getRankingInfo', 'minWordSizefor2Typos', 'minWordSizefor1Typo', 'page', 'maxValuesPerFacet', 'distinct', 'minimumAroundRadius', 'hitsPerPage', 'minProximity' ]; forEach_1(numberKeys, function(k) { var value = partialState[k]; if (isString_1(value)) { var parsedValue = parseFloat(value); numbers[k] = _isNaN(parsedValue) ? value : parsedValue; } }); if (partialState.numericRefinements) { var numericRefinements = {}; forEach_1(partialState.numericRefinements, function(operators, attribute) { numericRefinements[attribute] = {}; forEach_1(operators, function(values, operator) { var parsedValues = map_1(values, function(v) { if (isArray_1(v)) { return map_1(v, function(vPrime) { if (isString_1(vPrime)) { return parseFloat(vPrime); } return vPrime; }); } else if (isString_1(v)) { return parseFloat(v); } return v; }); numericRefinements[attribute][operator] = parsedValues; }); }); numbers.numericRefinements = numericRefinements; } return merge_1({}, partialState, numbers); }; /** * Factory for SearchParameters * @param {object|SearchParameters} newParameters existing parameters or partial * object for the properties of a new SearchParameters * @return {SearchParameters} frozen instance of SearchParameters */ SearchParameters.make = function makeSearchParameters(newParameters) { var instance = new SearchParameters(newParameters); forEach_1(newParameters.hierarchicalFacets, function(facet) { if (facet.rootPath) { var currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) { instance = instance.clearRefinements(facet.name); } // get it again in case it has been cleared currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length === 0) { instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath); } } }); return instance; }; /** * Validates the new parameters based on the previous state * @param {SearchParameters} currentState the current state * @param {object|SearchParameters} parameters the new parameters to set * @return {Error|null} Error if the modification is invalid, null otherwise */ SearchParameters.validate = function(currentState, parameters) { var params = parameters || {}; if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) { return new Error( '[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' + 'an error, if it is really what you want, you should first clear the tags with clearTags method.'); } if (currentState.tagRefinements.length > 0 && params.tagFilters) { return new Error( '[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' + 'an error, if it is not, you should first clear the tags with clearTags method.'); } if (currentState.numericFilters && params.numericRefinements && !isEmpty_1(params.numericRefinements)) { return new Error( "[Numeric filters] Can't switch from the advanced to the managed API. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } if (!isEmpty_1(currentState.numericRefinements) && params.numericFilters) { return new Error( "[Numeric filters] Can't switch from the managed API to the advanced. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } return null; }; SearchParameters.prototype = { constructor: SearchParameters, /** * Remove all refinements (disjunctive + conjunctive + excludes + numeric filters) * @method * @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {SearchParameters} */ clearRefinements: function clearRefinements(attribute) { var clear = RefinementList.clearRefinement; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(attribute), facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'), facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'), disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'), hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet') }); }, /** * Remove all the refined tags from the SearchParameters * @method * @return {SearchParameters} */ clearTags: function clearTags() { if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this; return this.setQueryParameters({ tagFilters: undefined, tagRefinements: [] }); }, /** * Set the index. * @method * @param {string} index the index name * @return {SearchParameters} */ setIndex: function setIndex(index) { if (index === this.index) return this; return this.setQueryParameters({ index: index }); }, /** * Query setter * @method * @param {string} newQuery value for the new query * @return {SearchParameters} */ setQuery: function setQuery(newQuery) { if (newQuery === this.query) return this; return this.setQueryParameters({ query: newQuery }); }, /** * Page setter * @method * @param {number} newPage new page number * @return {SearchParameters} */ setPage: function setPage(newPage) { if (newPage === this.page) return this; return this.setQueryParameters({ page: newPage }); }, /** * Facets setter * The facets are the simple facets, used for conjunctive (and) faceting. * @method * @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting * @return {SearchParameters} */ setFacets: function setFacets(facets) { return this.setQueryParameters({ facets: facets }); }, /** * Disjunctive facets setter * Change the list of disjunctive (or) facets the helper chan handle. * @method * @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting * @return {SearchParameters} */ setDisjunctiveFacets: function setDisjunctiveFacets(facets) { return this.setQueryParameters({ disjunctiveFacets: facets }); }, /** * HitsPerPage setter * Hits per page represents the number of hits retrieved for this query * @method * @param {number} n number of hits retrieved per page of results * @return {SearchParameters} */ setHitsPerPage: function setHitsPerPage(n) { if (this.hitsPerPage === n) return this; return this.setQueryParameters({ hitsPerPage: n }); }, /** * typoTolerance setter * Set the value of typoTolerance * @method * @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict") * @return {SearchParameters} */ setTypoTolerance: function setTypoTolerance(typoTolerance) { if (this.typoTolerance === typoTolerance) return this; return this.setQueryParameters({ typoTolerance: typoTolerance }); }, /** * Add a numeric filter for a given attribute * When value is an array, they are combined with OR * When value is a single value, it will combined with AND * @method * @param {string} attribute attribute to set the filter on * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number | number[]} value value of the filter * @return {SearchParameters} * @example * // for price = 50 or 40 * searchparameter.addNumericRefinement('price', '=', [50, 40]); * @example * // for size = 38 and 40 * searchparameter.addNumericRefinement('size', '=', 38); * searchparameter.addNumericRefinement('size', '=', 40); */ addNumericRefinement: function(attribute, operator, v) { var value = valToNumber_1(v); if (this.isNumericRefined(attribute, operator, value)) return this; var mod = merge_1({}, this.numericRefinements); mod[attribute] = merge_1({}, mod[attribute]); if (mod[attribute][operator]) { // Array copy mod[attribute][operator] = mod[attribute][operator].slice(); // Add the element. Concat can't be used here because value can be an array. mod[attribute][operator].push(value); } else { mod[attribute][operator] = [value]; } return this.setQueryParameters({ numericRefinements: mod }); }, /** * Get the list of conjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getConjunctiveRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsRefinements[facetName] || []; }, /** * Get the list of disjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getDisjunctiveRefinements: function(facetName) { if (!this.isDisjunctiveFacet(facetName)) { throw new Error( facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ); } return this.disjunctiveFacetsRefinements[facetName] || []; }, /** * Get the list of hierarchical refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getHierarchicalRefinement: function(facetName) { // we send an array but we currently do not support multiple // hierarchicalRefinements for a hierarchicalFacet return this.hierarchicalFacetsRefinements[facetName] || []; }, /** * Get the list of exclude refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getExcludeRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsExcludes[facetName] || []; }, /** * Remove all the numeric filter for a given (attribute, operator) * @method * @param {string} attribute attribute to set the filter on * @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number} [number] the value to be removed * @return {SearchParameters} */ removeNumericRefinement: function(attribute, operator, paramValue) { if (paramValue !== undefined) { var paramValueAsNumber = valToNumber_1(paramValue); if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator && isEqual_1(value.val, paramValueAsNumber); }) }); } else if (operator !== undefined) { if (!this.isNumericRefined(attribute, operator)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator; }) }); } if (!this.isNumericRefined(attribute)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute; }) }); }, /** * Get the list of numeric refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {SearchParameters.OperatorList[]} list of refinements */ getNumericRefinements: function(facetName) { return this.numericRefinements[facetName] || {}; }, /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ getNumericRefinement: function(attribute, operator) { return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator]; }, /** * Clear numeric filters. * @method * @private * @param {string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {Object.<string, OperatorList>} */ _clearNumericRefinements: function _clearNumericRefinements(attribute) { if (isUndefined_1(attribute)) { return {}; } else if (isString_1(attribute)) { return omit_1(this.numericRefinements, attribute); } else if (isFunction_1(attribute)) { return reduce_1(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach_1(operators, function(values, operator) { var outValues = []; forEach_1(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty_1(outValues)) operatorList[operator] = outValues; }); if (!isEmpty_1(operatorList)) memo[key] = operatorList; return memo; }, {}); } }, /** * Add a facet to the facets attribute of the helper configuration, if it * isn't already present. * @method * @param {string} facet facet name to add * @return {SearchParameters} */ addFacet: function addFacet(facet) { if (this.isConjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ facets: this.facets.concat([facet]) }); }, /** * Add a disjunctive facet to the disjunctiveFacets attribute of the helper * configuration, if it isn't already present. * @method * @param {string} facet disjunctive facet name to add * @return {SearchParameters} */ addDisjunctiveFacet: function addDisjunctiveFacet(facet) { if (this.isDisjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.concat([facet]) }); }, /** * Add a hierarchical facet to the hierarchicalFacets attribute of the helper * configuration. * @method * @param {object} hierarchicalFacet hierarchical facet to add * @return {SearchParameters} * @throws will throw an error if a hierarchical facet with the same name was already declared */ addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) { if (this.isHierarchicalFacet(hierarchicalFacet.name)) { throw new Error( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`'); } return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) }); }, /** * Add a refinement on a "normal" facet * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addFacetRefinement: function addFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) }); }, /** * Exclude a value from a "normal" facet * @method * @param {string} facet attribute to apply the exclusion on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addExcludeRefinement: function addExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) }); }, /** * Adds a refinement on a disjunctive facet. * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * addTagRefinement adds a tag to the list used to filter the results * @param {string} tag tag to be added * @return {SearchParameters} */ addTagRefinement: function addTagRefinement(tag) { if (this.isTagRefined(tag)) return this; var modification = { tagRefinements: this.tagRefinements.concat(tag) }; return this.setQueryParameters(modification); }, /** * Remove a facet from the facets attribute of the helper configuration, if it * is present. * @method * @param {string} facet facet name to remove * @return {SearchParameters} */ removeFacet: function removeFacet(facet) { if (!this.isConjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ facets: filter_1(this.facets, function(f) { return f !== facet; }) }); }, /** * Remove a disjunctive facet from the disjunctiveFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet disjunctive facet name to remove * @return {SearchParameters} */ removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) { if (!this.isDisjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: filter_1(this.disjunctiveFacets, function(f) { return f !== facet; }) }); }, /** * Remove a hierarchical facet from the hierarchicalFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet hierarchical facet name to remove * @return {SearchParameters} */ removeHierarchicalFacet: function removeHierarchicalFacet(facet) { if (!this.isHierarchicalFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: filter_1(this.hierarchicalFacets, function(f) { return f.name !== facet; }) }); }, /** * Remove a refinement set on facet. If a value is provided, it will clear the * refinement for the given value, otherwise it will clear all the refinement * values for the faceted attribute. * @method * @param {string} facet name of the attribute used for faceting * @param {string} [value] value used to filter * @return {SearchParameters} */ removeFacetRefinement: function removeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) }); }, /** * Remove a negative refinement on a facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeExcludeRefinement: function removeExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) }); }, /** * Remove a refinement on a disjunctive facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Remove a tag from the list of tag refinements * @method * @param {string} tag the tag to remove * @return {SearchParameters} */ removeTagRefinement: function removeTagRefinement(tag) { if (!this.isTagRefined(tag)) return this; var modification = { tagRefinements: filter_1(this.tagRefinements, function(t) { return t !== tag; }) }; return this.setQueryParameters(modification); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper * @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement} */ toggleRefinement: function toggleRefinement(facet, value) { return this.toggleFacetRefinement(facet, value); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper */ toggleFacetRefinement: function toggleFacetRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleConjunctiveFacetRefinement(facet, value); } else if (this.isDisjunctiveFacet(facet)) { return this.toggleDisjunctiveFacetRefinement(facet, value); } throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.toggleRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet)); var mod = {}; var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined && this.hierarchicalFacetsRefinements[facet].length > 0 && ( // remove current refinement: // refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0] === value || // remove a parent refinement of the current refinement: // - refinement was 'beer > IPA > Flying dog' // - call is toggleRefine('beer > IPA') // - refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0 ); if (upOneOrMultipleLevel) { if (value.indexOf(separator) === -1) { // go back to root level mod[facet] = []; } else { mod[facet] = [value.slice(0, value.lastIndexOf(separator))]; } } else { mod[facet] = [value]; } return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Adds a refinement on a hierarchical facet. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is refined */ addHierarchicalFacetRefinement: function(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is not refined */ removeHierarchicalFacetRefinement: function(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Switch the tag refinement * @method * @param {string} tag the tag to remove or add * @return {SearchParameters} */ toggleTagRefinement: function toggleTagRefinement(tag) { if (this.isTagRefined(tag)) { return this.removeTagRefinement(tag); } return this.addTagRefinement(tag); }, /** * Test if the facet name is from one of the disjunctive facets * @method * @param {string} facet facet name to test * @return {boolean} */ isDisjunctiveFacet: function(facet) { return indexOf_1(this.disjunctiveFacets, facet) > -1; }, /** * Test if the facet name is from one of the hierarchical facets * @method * @param {string} facetName facet name to test * @return {boolean} */ isHierarchicalFacet: function(facetName) { return this.getHierarchicalFacetByName(facetName) !== undefined; }, /** * Test if the facet name is from one of the conjunctive/normal facets * @method * @param {string} facet facet name to test * @return {boolean} */ isConjunctiveFacet: function(facet) { return indexOf_1(this.facets, facet) > -1; }, /** * Returns true if the facet is refined, either for a specific value or in * general. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value, optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isFacetRefined: function isFacetRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsRefinements, facet, value); }, /** * Returns true if the facet contains exclusions or if a specific value is * excluded. * * @method * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isExcludeRefined: function isExcludeRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsExcludes, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return indexOf_1(refinements, value) !== -1; }, /** * Test if the triple (attribute, operator, value) is already refined. * If only the attribute and the operator are provided, it tests if the * contains any refinement value. * @method * @param {string} attribute attribute for which the refinement is applied * @param {string} [operator] operator of the refinement * @param {string} [value] value of the refinement * @return {boolean} true if it is refined */ isNumericRefined: function isNumericRefined(attribute, operator, value) { if (isUndefined_1(value) && isUndefined_1(operator)) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && !isUndefined_1(this.numericRefinements[attribute][operator]); if (isUndefined_1(value) || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber_1(value); var isAttributeValueDefined = !isUndefined_1( findArray(this.numericRefinements[attribute][operator], parsedValue) ); return isOperatorDefined && isAttributeValueDefined; }, /** * Returns true if the tag refined, false otherwise * @method * @param {string} tag the tag to check * @return {boolean} */ isTagRefined: function isTagRefined(tag) { return indexOf_1(this.tagRefinements, tag) !== -1; }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection_1( keys_1(this.numericRefinements), this.disjunctiveFacets ); return keys_1(this.disjunctiveFacetsRefinements) .concat(disjunctiveNumericRefinedFacets) .concat(this.getRefinedHierarchicalFacets()); }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() { return intersection_1( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index map_1(this.hierarchicalFacets, 'name'), keys_1(this.hierarchicalFacetsRefinements) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return filter_1(this.disjunctiveFacets, function(f) { return indexOf_1(refinedFacets, f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; forOwn_1(this, function(paramValue, paramName) { if (indexOf_1(managedParameters, paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * Let the user retrieve any parameter value from the SearchParameters * @param {string} paramName name of the parameter * @return {any} the value of the parameter */ getQueryParameter: function getQueryParameter(paramName) { if (!this.hasOwnProperty(paramName)) { throw new Error( "Parameter '" + paramName + "' is not an attribute of SearchParameters " + '(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)'); } return this[paramName]; }, /** * Let the user set a specific value for a given parameter. Will return the * same instance if the parameter is invalid or if the value is the same as the * previous one. * @method * @param {string} parameter the parameter name * @param {any} value the value to be set, must be compliant with the definition * of the attribute on the object * @return {SearchParameters} the updated state */ setQueryParameter: function setParameter(parameter, value) { if (this[parameter] === value) return this; var modification = {}; modification[parameter] = value; return this.setQueryParameters(modification); }, /** * Let the user set any of the parameters with a plain object. * @method * @param {object} params all the keys and the values to be updated * @return {SearchParameters} a new updated instance */ setQueryParameters: function setQueryParameters(params) { if (!params) return this; var error = SearchParameters.validate(this, params); if (error) { throw error; } var parsedParams = SearchParameters._parseNumbers(params); return this.mutateMe(function mergeWith(newInstance) { var ks = keys_1(params); forEach_1(ks, function(k) { newInstance[k] = parsedParams[k]; }); return newInstance; }); }, /** * Returns an object with only the selected attributes. * @param {string[]} filters filters to retrieve only a subset of the state. It * accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage) * or attributes of the index with the notation 'attribute:nameOfMyAttribute' * @return {object} */ filter: function(filters) { return filterState_1(this, filters); }, /** * Helper function to make it easier to build new instances from a mutating * function * @private * @param {function} fn newMutableState -> previousState -> () function that will * change the value of the newMutable to the desired state * @return {SearchParameters} a new instance with the specified modifications applied */ mutateMe: function mutateMe(fn) { var newState = new this.constructor(this); fn(newState, this); return newState; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSortBy: function(hierarchicalFacet) { return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc']; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSeparator: function(hierarchicalFacet) { return hierarchicalFacet.separator || ' > '; }, /** * Helper function to get the hierarchicalFacet prefix path or null * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.rootPath or null as default */ _getHierarchicalRootPath: function(hierarchicalFacet) { return hierarchicalFacet.rootPath || null; }, /** * Helper function to check if we show the parent level of the hierarchicalFacet * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.showParentLevel or true as default */ _getHierarchicalShowParentLevel: function(hierarchicalFacet) { if (typeof hierarchicalFacet.showParentLevel === 'boolean') { return hierarchicalFacet.showParentLevel; } return true; }, /** * Helper function to get the hierarchicalFacet by it's name * @param {string} hierarchicalFacetName * @return {object} a hierarchicalFacet */ getHierarchicalFacetByName: function(hierarchicalFacetName) { return find_1( this.hierarchicalFacets, {name: hierarchicalFacetName} ); }, /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ getHierarchicalFacetBreadcrumb: function(facetName) { if (!this.isHierarchicalFacet(facetName)) { throw new Error( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`'); } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return map_1(path, trim_1); } }; /** * Callback used for clearRefinement method * @callback SearchParameters.clearCallback * @param {OperatorList|FacetList} value the value of the filter * @param {string} key the current attribute name * @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude` * depending on the type of facet * @return {boolean} `true` if the element should be removed. `false` otherwise. */ var SearchParameters_1 = SearchParameters; /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } var compact_1 = compact; /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } var _baseSum = baseSum; /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? _baseSum(array, _baseIteratee(iteratee, 2)) : 0; } var sumBy_1 = sumBy; /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return _arrayMap(props, function(key) { return object[key]; }); } var _baseValues = baseValues; /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : _baseValues(object, keys_1(object)); } var values_1 = values; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$3 = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike_1(collection) ? collection : values_1(collection); fromIndex = (fromIndex && !guard) ? toInteger_1(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax$3(length + fromIndex, 0); } return isString_1(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && _baseIndexOf(collection, value, fromIndex) > -1); } var includes_1 = includes; /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } var _baseSortBy = baseSortBy; /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } var _compareAscending = compareAscending; /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = _compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } var _compareMultiple = compareMultiple; /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = _arrayMap(iteratees.length ? iteratees : [identity_1], _baseUnary(_baseIteratee)); var result = _baseMap(collection, function(value, key, collection) { var criteria = _arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return _baseSortBy(result, function(object, other) { return _compareMultiple(object, other, orders); }); } var _baseOrderBy = baseOrderBy; /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray_1(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray_1(orders)) { orders = orders == null ? [] : [orders]; } return _baseOrderBy(collection, iteratees, orders); } var orderBy_1 = orderBy; /** Used to store function metadata. */ var metaMap = _WeakMap && new _WeakMap; var _metaMap = metaMap; /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !_metaMap ? identity_1 : function(func, data) { _metaMap.set(func, data); return func; }; var _baseSetData = baseSetData; /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = _baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject_1(result) ? result : thisBinding; }; } var _createCtor = createCtor; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = _createCtor(func); function wrapper() { var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } var _createBind = createBind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$4 = Math.max; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax$4(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } var _composeArgs = composeArgs; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$5 = Math.max; /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax$5(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } var _composeArgsRight = composeArgsRight; /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } var _countHolders = countHolders; /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } var _baseLodash = baseLodash; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; var _LazyWrapper = LazyWrapper; /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop$1() { // No operation performed. } var noop_1 = noop$1; /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !_metaMap ? noop_1 : function(func) { return _metaMap.get(func); }; var _getData = getData; /** Used to lookup unminified function names. */ var realNames = {}; var _realNames = realNames; /** Used for built-in method references. */ var objectProto$18 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$16 = objectProto$18.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = _realNames[result], length = hasOwnProperty$16.call(_realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } var _getFuncName = getFuncName; /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = _baseCreate(_baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; var _LodashWrapper = LodashWrapper; /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof _LazyWrapper) { return wrapper.clone(); } var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = _copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } var _wrapperClone = wrapperClone; /** Used for built-in method references. */ var objectProto$19 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$17 = objectProto$19.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) { if (value instanceof _LodashWrapper) { return value; } if (hasOwnProperty$17.call(value, '__wrapped__')) { return _wrapperClone(value); } } return new _LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = _baseLodash.prototype; lodash.prototype.constructor = lodash; var wrapperLodash = lodash; /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = _getFuncName(func), other = wrapperLodash[funcName]; if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = _getData(other); return !!data && func === data[0]; } var _isLaziable = isLaziable; /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = _shortOut(_baseSetData); var _setData = setData; /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/; var reSplitDetails = /,? & /; /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } var _getWrapDetails = getWrapDetails; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } var _insertWrapDetails = insertWrapDetails; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$1 = 1; var WRAP_BIND_KEY_FLAG = 2; var WRAP_CURRY_FLAG = 8; var WRAP_CURRY_RIGHT_FLAG = 16; var WRAP_PARTIAL_FLAG = 32; var WRAP_PARTIAL_RIGHT_FLAG = 64; var WRAP_ARY_FLAG = 128; var WRAP_REARG_FLAG = 256; var WRAP_FLIP_FLAG = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG$1], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { _arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } var _updateWrapDetails = updateWrapDetails; /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask))); } var _setWrapToString = setWrapToString; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$2 = 1; var WRAP_BIND_KEY_FLAG$1 = 2; var WRAP_CURRY_BOUND_FLAG = 4; var WRAP_CURRY_FLAG$1 = 8; var WRAP_PARTIAL_FLAG$1 = 32; var WRAP_PARTIAL_RIGHT_FLAG$1 = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG$1, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG$2 | WRAP_BIND_KEY_FLAG$1); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (_isLaziable(func)) { _setData(result, newData); } result.placeholder = placeholder; return _setWrapToString(result, func, bitmask); } var _createRecurry = createRecurry; /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = func; return object.placeholder; } var _getHolder = getHolder; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$1 = Math.min; /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin$1(indexes.length, arrLength), oldArray = _copyArray(array); while (length--) { var index = indexes[length]; array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } var _reorder = reorder; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } var _replaceHolders = replaceHolders; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$3 = 1; var WRAP_BIND_KEY_FLAG$2 = 2; var WRAP_CURRY_FLAG$2 = 8; var WRAP_CURRY_RIGHT_FLAG$1 = 16; var WRAP_ARY_FLAG$1 = 128; var WRAP_FLIP_FLAG$1 = 512; /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG$1, isBind = bitmask & WRAP_BIND_FLAG$3, isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2, isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1), isFlip = bitmask & WRAP_FLIP_FLAG$1, Ctor = isBindKey ? undefined : _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = _getHolder(wrapper), holdersCount = _countHolders(args, placeholder); } if (partials) { args = _composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = _composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = _replaceHolders(args, placeholder); return _createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = _reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== _root && this instanceof wrapper) { fn = Ctor || _createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } var _createHybrid = createHybrid; /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = _getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : _replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return _createRecurry( func, bitmask, _createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return _apply(fn, this, args); } return wrapper; } var _createCurry = createCurry; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$4 = 1; /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG$4, Ctor = _createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return _apply(fn, isBind ? thisArg : this, args); } return wrapper; } var _createPartial = createPartial; /** Used as the internal argument placeholder. */ var PLACEHOLDER$1 = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$5 = 1; var WRAP_BIND_KEY_FLAG$3 = 2; var WRAP_CURRY_BOUND_FLAG$1 = 4; var WRAP_CURRY_FLAG$3 = 8; var WRAP_ARY_FLAG$2 = 128; var WRAP_REARG_FLAG$1 = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$2 = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG$5 | WRAP_BIND_KEY_FLAG$3 | WRAP_ARY_FLAG$2); var isCombo = ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_CURRY_FLAG$3)) || ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$3)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG$5) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG$5 ? 0 : WRAP_CURRY_BOUND_FLAG$1; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? _composeArgs(partials, value, source[4]) : value; data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER$1) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER$1) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG$2) { data[8] = data[8] == null ? source[8] : nativeMin$2(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } var _mergeData = mergeData; /** Error message constants. */ var FUNC_ERROR_TEXT$1 = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$6 = 1; var WRAP_BIND_KEY_FLAG$4 = 2; var WRAP_CURRY_FLAG$4 = 8; var WRAP_CURRY_RIGHT_FLAG$2 = 16; var WRAP_PARTIAL_FLAG$2 = 32; var WRAP_PARTIAL_RIGHT_FLAG$2 = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$6 = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG$4; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT$1); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG$2 | WRAP_PARTIAL_RIGHT_FLAG$2); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax$6(toInteger_1(ary), 0); arity = arity === undefined ? arity : toInteger_1(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG$2) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : _getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { _mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax$6(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2)) { bitmask &= ~(WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2); } if (!bitmask || bitmask == WRAP_BIND_FLAG$6) { var result = _createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG$4 || bitmask == WRAP_CURRY_RIGHT_FLAG$2) { result = _createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG$2 || bitmask == (WRAP_BIND_FLAG$6 | WRAP_PARTIAL_FLAG$2)) && !holders.length) { result = _createPartial(func, bitmask, thisArg, partials); } else { result = _createHybrid.apply(undefined, newData); } var setter = data ? _baseSetData : _setData; return _setWrapToString(setter(result, newData), func, bitmask); } var _createWrap = createWrap; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_FLAG$3 = 32; /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partial)); return _createWrap(func, WRAP_PARTIAL_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partial.placeholder = {}; var partial_1 = partial; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_RIGHT_FLAG$3 = 64; /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partialRight)); return _createWrap(func, WRAP_PARTIAL_RIGHT_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partialRight.placeholder = {}; var partialRight_1 = partialRight; /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } var _baseClamp = baseClamp; /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString_1(string); position = position == null ? 0 : _baseClamp(toInteger_1(position), 0, string.length); target = _baseToString(target); return string.slice(position, position + target.length) == target; } var startsWith_1 = startsWith; /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ var formatSort = function formatSort(sortBy, defaults) { return reduce_1(sortBy, function preparePredicate(out, sortInstruction) { var sortInstructions = sortInstruction.split(':'); if (defaults && sortInstructions.length === 1) { var similarDefault = find_1(defaults, function(predicate) { return startsWith_1(predicate, sortInstruction[0]); }); if (similarDefault) { sortInstructions = similarDefault.split(':'); } } out[0].push(sortInstructions[0]); out[1].push(sortInstructions[1]); return out; }, [[], []]); }; /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject_1(object)) { return object; } path = _castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = _toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject_1(objValue) ? objValue : (_isIndex(path[index + 1]) ? [] : {}); } } _assignValue(nested, key, newValue); nested = nested[key]; } return object; } var _baseSet = baseSet; /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = _baseGet(object, path); if (predicate(value, path)) { _baseSet(result, _castPath(path, object), value); } } return result; } var _basePickBy = basePickBy; /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = _arrayMap(_getAllKeysIn(object), function(prop) { return [prop]; }); predicate = _baseIteratee(predicate); return _basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } var pickBy_1 = pickBy; var generateHierarchicalTree_1 = generateTrees; function generateTrees(state) { return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) { var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex]; var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || ''; var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet); var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet); var sortBy = formatSort(state._getHierarchicalFacetSortBy(hierarchicalFacet)); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return reduce_1(results, generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path data: null }); }; } function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) { return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) { var parent = hierarchicalTree; if (currentHierarchicalLevel > 0) { var level = 0; parent = hierarchicalTree; while (level < currentHierarchicalLevel) { parent = parent && find_1(parent.data, {isRefined: true}); level++; } } // we found a refined parent, let's add current level data under it if (parent) { // filter values in case an object has multiple categories: // { // categories: { // level0: ['beers', 'bières'], // level1: ['beers > IPA', 'bières > Belges'] // } // } // // If parent refinement is `beers`, then we do not want to have `bières > Belges` // showing up var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); parent.data = orderBy_1( map_1( pickBy_1(hierarchicalFacetResult.data, onlyMatchingValuesFn), formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) ), sortBy[0], sortBy[1] ); } return hierarchicalTree; }; } function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { return function(facetCount, facetValue) { // we want the facetValue is a child of hierarchicalRootPath if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) { return false; } // we always want root levels (only when there is no prefix path) return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || // if there is a rootPath, being root level mean 1 level under rootPath hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || // if current refinement is a root level and current facetValue is a root level, // keep the facetValue facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || // currentRefinement is a child of the facet value currentRefinement.indexOf(facetValue) === 0 || // facetValue is a child of the current parent, add it facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0); }; } function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) { return function format(facetCount, facetValue) { return { name: trim_1(last_1(facetValue.split(hierarchicalSeparator))), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, data: null }; }; } /** * @typedef SearchResults.Facet * @type {object} * @property {string} name name of the attribute in the record * @property {object} data the faceting data: value, number of entries * @property {object} stats undefined unless facet_stats is retrieved from algolia */ /** * @typedef SearchResults.HierarchicalFacet * @type {object} * @property {string} name name of the current value given the hierarchical level, trimmed. * If root node, you get the facet name * @property {number} count number of objects matching this hierarchical value * @property {string} path the current hierarchical value full path * @property {boolean} isRefined `true` if the current value was refined, `false` otherwise * @property {HierarchicalFacet[]} data sub values for the current level */ /** * @typedef SearchResults.FacetValue * @type {object} * @property {string} name the facet value itself * @property {number} count times this facet appears in the results * @property {boolean} isRefined is the facet currently selected * @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets) */ /** * @typedef Refinement * @type {object} * @property {string} type the type of filter used: * `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical` * @property {string} attributeName name of the attribute used for filtering * @property {string} name the value of the filter * @property {number} numericValue the value as a number. Only for numeric filters. * @property {string} operator the operator used. Only for numeric filters. * @property {number} count the number of computed hits for this filter. Only on facets. * @property {boolean} exhaustive if the count is exhaustive */ function getIndices(obj) { var indices = {}; forEach_1(obj, function(val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find_1( hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { return includes_1(hierarchicalFacet.attributes, hierarchicalAttributeName); } ); } /*eslint-disable */ /** * Constructor for SearchResults * @class * @classdesc SearchResults contains the results of a query to Algolia using the * {@link AlgoliaSearchHelper}. * @param {SearchParameters} state state that led to the response * @param {array.<object>} results the results from algolia client * @example <caption>SearchResults of the first query in * <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption> { "hitsPerPage": 10, "processingTimeMS": 2, "facets": [ { "name": "type", "data": { "HardGood": 6627, "BlackTie": 550, "Music": 665, "Software": 131, "Game": 456, "Movie": 1571 }, "exhaustive": false }, { "exhaustive": false, "data": { "Free shipping": 5507 }, "name": "shipping" } ], "hits": [ { "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif", "_highlightResult": { "shortDescription": { "matchLevel": "none", "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "matchedWords": [] }, "category": { "matchLevel": "none", "value": "Computer Security Software", "matchedWords": [] }, "manufacturer": { "matchedWords": [], "value": "Webroot", "matchLevel": "none" }, "name": { "value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "matchedWords": [], "matchLevel": "none" } }, "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg", "shipping": "Free shipping", "bestSellingRank": 4, "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ", "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "category": "Computer Security Software", "salePrice_range": "1 - 50", "objectID": "1688832", "type": "Software", "customerReviewCount": 5980, "salePrice": 49.99, "manufacturer": "Webroot" }, .... ], "nbHits": 10000, "disjunctiveFacets": [ { "exhaustive": false, "data": { "5": 183, "12": 112, "7": 149, ... }, "name": "customerReviewCount", "stats": { "max": 7461, "avg": 157.939, "min": 1 } }, { "data": { "Printer Ink": 142, "Wireless Speakers": 60, "Point & Shoot Cameras": 48, ... }, "name": "category", "exhaustive": false }, { "exhaustive": false, "data": { "> 5000": 2, "1 - 50": 6524, "501 - 2000": 566, "201 - 500": 1501, "101 - 200": 1360, "2001 - 5000": 47 }, "name": "salePrice_range" }, { "data": { "Dynex™": 202, "Insignia™": 230, "PNY": 72, ... }, "name": "manufacturer", "exhaustive": false } ], "query": "", "nbPages": 100, "page": 0, "index": "bestbuy" } **/ /*eslint-enable */ function SearchResults(state, results) { var mainSubResponse = results[0]; this._rawResults = results; /** * query used to generate the results * @member {string} */ this.query = mainSubResponse.query; /** * The query as parsed by the engine given all the rules. * @member {string} */ this.parsedQuery = mainSubResponse.parsedQuery; /** * all the records that match the search parameters. Each record is * augmented with a new attribute `_highlightResult` * which is an object keyed by attribute and with the following properties: * - `value` : the value of the facet highlighted (html) * - `matchLevel`: full, partial or none depending on how the query terms match * @member {object[]} */ this.hits = mainSubResponse.hits; /** * index where the results come from * @member {string} */ this.index = mainSubResponse.index; /** * number of hits per page requested * @member {number} */ this.hitsPerPage = mainSubResponse.hitsPerPage; /** * total number of hits of this query on the index * @member {number} */ this.nbHits = mainSubResponse.nbHits; /** * total number of pages with respect to the number of hits per page and the total number of hits * @member {number} */ this.nbPages = mainSubResponse.nbPages; /** * current page * @member {number} */ this.page = mainSubResponse.page; /** * sum of the processing time of all the queries * @member {number} */ this.processingTimeMS = sumBy_1(results, 'processingTimeMS'); /** * The position if the position was guessed by IP. * @member {string} * @example "48.8637,2.3615", */ this.aroundLatLng = mainSubResponse.aroundLatLng; /** * The radius computed by Algolia. * @member {string} * @example "126792922", */ this.automaticRadius = mainSubResponse.automaticRadius; /** * String identifying the server used to serve this request. * @member {string} * @example "c7-use-2.algolia.net", */ this.serverUsed = mainSubResponse.serverUsed; /** * Boolean that indicates if the computation of the counts did time out. * @deprecated * @member {boolean} */ this.timeoutCounts = mainSubResponse.timeoutCounts; /** * Boolean that indicates if the computation of the hits did time out. * @deprecated * @member {boolean} */ this.timeoutHits = mainSubResponse.timeoutHits; /** * True if the counts of the facets is exhaustive * @member {boolean} */ this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount; /** * True if the number of hits is exhaustive * @member {boolean} */ this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits; /** * Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/). * @member {object[]} */ this.userData = mainSubResponse.userData; /** * disjunctive facets results * @member {SearchResults.Facet[]} */ this.disjunctiveFacets = []; /** * disjunctive facets results * @member {SearchResults.HierarchicalFacet[]} */ this.hierarchicalFacets = map_1(state.hierarchicalFacets, function initFutureTree() { return []; }); /** * other facets results * @member {SearchResults.Facet[]} */ this.facets = []; var disjunctiveFacets = state.getRefinedDisjunctiveFacets(); var facetsIndices = getIndices(state.facets); var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets); var nextDisjunctiveResult = 1; var self = this; // Since we send request only for disjunctive facets that have been refined, // we get the facets informations from the first, general, response. forEach_1(mainSubResponse.facets, function(facetValueObject, facetKey) { var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName( state.hierarchicalFacets, facetKey ); if (hierarchicalFacet) { // Place the hierarchicalFacet data at the correct index depending on // the attributes order that was defined at the helper initialization var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey); var idxAttributeName = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = indexOf_1(state.disjunctiveFacets, facetKey) !== -1; var isFacetConjunctive = indexOf_1(state.facets, facetKey) !== -1; var position; if (isFacetDisjunctive) { position = disjunctiveFacetsIndices[facetKey]; self.disjunctiveFacets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey); } if (isFacetConjunctive) { position = facetsIndices[facetKey]; self.facets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey); } } }); // Make sure we do not keep holes within the hierarchical facets this.hierarchicalFacets = compact_1(this.hierarchicalFacets); // aggregate the refined disjunctive facets forEach_1(disjunctiveFacets, function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. forEach_1(result.facets, function(facetResults, dfacet) { var position; if (hierarchicalFacet) { position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } self.hierarchicalFacets[position][attributeIndex].data = merge_1( {}, self.hierarchicalFacets[position][attributeIndex].data, facetResults ); } else { position = disjunctiveFacetsIndices[dfacet]; var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}; self.disjunctiveFacets[position] = { name: dfacet, data: defaults_1({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { forEach_1(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && indexOf_1(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are already at a root refinement (or no refinement at all), there is no // root level values request if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) { return; } var result = results[nextDisjunctiveResult]; forEach_1(result.facets, function(facetResults, dfacet) { var position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5), // then the disjunctive values will be `beers` (count: 100), // but we do not want to display // | beers (100) // > IPA (5) // We want // | beers (5) // > IPA (5) var defaultData = {}; if (currentRefinement.length > 0) { var root = currentRefinement[0].split(separator)[0]; defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root]; } self.hierarchicalFacets[position][attributeIndex].data = defaults_1( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes forEach_1(state.facetsExcludes, function(excludes, facetName) { var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; forEach_1(excludes, function(facetValue) { self.facets[position] = self.facets[position] || {name: facetName}; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); this.hierarchicalFacets = map_1(this.hierarchicalFacets, generateHierarchicalTree_1(state)); this.facets = compact_1(this.facets); this.disjunctiveFacets = compact_1(this.disjunctiveFacets); this._state = state; } /** * Get a facet object with its name * @deprecated * @param {string} name name of the faceted attribute * @return {SearchResults.Facet} the facet object */ SearchResults.prototype.getFacetByName = function(name) { var predicate = {name: name}; return find_1(this.facets, predicate) || find_1(this.disjunctiveFacets, predicate) || find_1(this.hierarchicalFacets, predicate); }; /** * Get the facet values of a specified attribute from a SearchResults object. * @private * @param {SearchResults} results the search results to search in * @param {string} attribute name of the faceted attribute to search for * @return {array|object} facet values. For the hierarchical facets it is an object. */ function extractNormalizedFacetValues(results, attribute) { var predicate = {name: attribute}; if (results._state.isConjunctiveFacet(attribute)) { var facet = find_1(results.facets, predicate); if (!facet) return []; return map_1(facet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isFacetRefined(attribute, k), isExcluded: results._state.isExcludeRefined(attribute, k) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find_1(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return map_1(disjunctiveFacet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isDisjunctiveFacetRefined(attribute, k) }; }); } else if (results._state.isHierarchicalFacet(attribute)) { return find_1(results.hierarchicalFacets, predicate); } } /** * Sort nodes of a hierarchical facet results * @private * @param {HierarchicalFacet} node node to upon which we want to apply the sort */ function recSort(sortFn, node) { if (!node.data || node.data.length === 0) { return node; } var children = map_1(node.data, partial_1(recSort, sortFn)); var sortedChildren = sortFn(children); var newNode = merge_1({}, node, {data: sortedChildren}); return newNode; } SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc']; function vanillaSortFn(order, data) { return data.sort(order); } /** * Get a the list of values for a given facet attribute. Those values are sorted * refinement first, descending count (bigger value on top), and name ascending * (alphabetical order). The sort formula can overridden using either string based * predicates or a function. * * This method will return all the values returned by the Algolia engine plus all * the values already refined. This means that it can happen that the * `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet) * might not be respected if you have facet values that are already refined. * @param {string} attribute attribute name * @param {object} opts configuration options. * @param {Array.<string> | function} opts.sortBy * When using strings, it consists of * the name of the [FacetValue](#SearchResults.FacetValue) or the * [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the * order (`asc` or `desc`). For example to order the value by count, the * argument would be `['count:asc']`. * * If only the attribute name is specified, the ordering defaults to the one * specified in the default value for this attribute. * * When not specified, the order is * ascending. This parameter can also be a function which takes two facet * values and should return a number, 0 if equal, 1 if the first argument is * bigger or -1 otherwise. * * The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']` * @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('results', function(content){ * //get values ordered only by name ascending using the string predicate * content.getFacetValues('city', {sortBy: ['name:asc']}); * //get values ordered only by count ascending using a function * content.getFacetValues('city', { * // this is equivalent to ['count:asc'] * sortBy: function(a, b) { * if (a.count === b.count) return 0; * if (a.count > b.count) return 1; * if (b.count > a.count) return -1; * } * }); * }); */ SearchResults.prototype.getFacetValues = function(attribute, opts) { var facetValues = extractNormalizedFacetValues(this, attribute); if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.'); var options = defaults_1({}, opts, {sortBy: SearchResults.DEFAULT_SORT}); if (isArray_1(options.sortBy)) { var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT); if (isArray_1(facetValues)) { return orderBy_1(facetValues, order[0], order[1]); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partialRight_1(orderBy_1, order[0], order[1]), facetValues); } else if (isFunction_1(options.sortBy)) { if (isArray_1(facetValues)) { return facetValues.sort(options.sortBy); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partial_1(vanillaSortFn, options.sortBy), facetValues); } throw new Error( 'options.sortBy is optional but if defined it must be ' + 'either an array of string (predicates) or a sorting function' ); }; /** * Returns the facet stats if attribute is defined and the facet contains some. * Otherwise returns undefined. * @param {string} attribute name of the faceted attribute * @return {object} The stats of the facet */ SearchResults.prototype.getFacetStats = function(attribute) { if (this._state.isConjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.facets, attribute); } else if (this._state.isDisjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute); } throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`'); }; function getFacetStatsIfAvailable(facetList, facetName) { var data = find_1(facetList, {name: facetName}); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhausistivity for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function() { var state = this._state; var results = this; var res = []; forEach_1(state.facetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); forEach_1(state.facetsExcludes, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); forEach_1(state.hierarchicalFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); forEach_1(state.numericRefinements, function(operators, attributeName) { forEach_1(operators, function(values, operator) { forEach_1(values, function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); forEach_1(state.tagRefinements, function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var count = get_1(facet, 'data[' + name + ']'); var exhaustive = get_1(facet, 'exhaustive'); return { type: type, attributeName: attributeName, name: name, count: count || 0, exhaustive: exhaustive || false }; } function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var splitted = name.split(facetDeclaration.separator); var configuredName = splitted[splitted.length - 1]; for (var i = 0; facet !== undefined && i < splitted.length; ++i) { facet = find_1(facet.data, {name: splitted[i]}); } var count = get_1(facet, 'count'); var exhaustive = get_1(facet, 'exhaustive'); return { type: 'hierarchical', attributeName: attributeName, name: configuredName, count: count || 0, exhaustive: exhaustive || false }; } var SearchResults_1 = SearchResults; var isBufferBrowser = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }; var inherits_browser = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var util = createCommonjsModule(function (module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(commonjsGlobal.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = isBufferBrowser; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = inherits_browser; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }); var util_1 = util.format; var util_2 = util.deprecate; var util_3 = util.debuglog; var util_4 = util.inspect; var util_5 = util.isArray; var util_6 = util.isBoolean; var util_7 = util.isNull; var util_8 = util.isNullOrUndefined; var util_9 = util.isNumber; var util_10 = util.isString; var util_11 = util.isSymbol; var util_12 = util.isUndefined; var util_13 = util.isRegExp; var util_14 = util.isObject; var util_15 = util.isDate; var util_16 = util.isError; var util_17 = util.isFunction; var util_18 = util.isPrimitive; var util_19 = util.isBuffer; var util_20 = util.log; var util_21 = util.inherits; var util_22 = util._extend; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } var events = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber$2(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject$2(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined$2(handler)) return false; if (isFunction$2(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject$2(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction$2(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction$2(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject$2(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject$2(this._events[type]) && !this._events[type].warned) { if (!isUndefined$2(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction$2(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction$2(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction$2(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject$2(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction$2(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction$2(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction$2(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction$2(arg) { return typeof arg === 'function'; } function isNumber$2(arg) { return typeof arg === 'number'; } function isObject$2(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined$2(arg) { return arg === void 0; } /** * A DerivedHelper is a way to create sub requests to * Algolia from a main helper. * @class * @classdesc The DerivedHelper provides an event based interface for search callbacks: * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. */ function DerivedHelper(mainHelper, fn) { this.main = mainHelper; this.fn = fn; this.lastResults = null; } util.inherits(DerivedHelper, events.EventEmitter); /** * Detach this helper from the main helper * @return {undefined} * @throws Error if the derived helper is already detached */ DerivedHelper.prototype.detach = function() { this.removeAllListeners(); this.main.detachDerivedHelper(this); }; DerivedHelper.prototype.getModifiedState = function(parameters) { return this.fn(parameters); }; var DerivedHelper_1 = DerivedHelper; var requestBuilder = { /** * Get all the queries to send to the client, those queries can used directly * with the Algolia client. * @private * @return {object[]} The queries */ _getQueries: function getQueries(index, state) { var queries = []; // One query for the hits queries.push({ indexName: index, params: requestBuilder._getHitsSearchParams(state) }); // One for each disjunctive facets forEach_1(state.getRefinedDisjunctiveFacets(), function(refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are deeper than level 0 (starting from `beer > IPA`) // we want to get the root values var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true) }); } }); return queries; }, /** * Build search parameters used to fetch hits * @private * @return {object.<string, any>} */ _getHitsSearchParams: function(state) { var facets = state.facets .concat(state.disjunctiveFacets) .concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state)); var facetFilters = requestBuilder._getFacetFilters(state); var numericFilters = requestBuilder._getNumericFilters(state); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { facets: facets, tagFilters: tagFilters }; if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Build search parameters used to fetch a disjunctive facet * @private * @param {string} facet the associated facet name * @param {boolean} hierarchicalRootLevel ?? FIXME * @return {object} */ _getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) { var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel); var numericFilters = requestBuilder._getNumericFilters(state, facet); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], tagFilters: tagFilters, analytics: false }; var hierarchicalFacet = state.getHierarchicalFacetByName(facet); if (hierarchicalFacet) { additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute( state, hierarchicalFacet, hierarchicalRootLevel ); } else { additionalParams.facets = facet; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Return the numeric filters in an algolia request fashion * @private * @param {string} [facetName] the name of the attribute for which the filters should be excluded * @return {string[]} the numeric filters in the algolia format */ _getNumericFilters: function(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; forEach_1(state.numericRefinements, function(operators, attribute) { forEach_1(operators, function(values, operator) { if (facetName !== attribute) { forEach_1(values, function(value) { if (isArray_1(value)) { var vs = map_1(value, function(v) { return attribute + operator + v; }); numericFilters.push(vs); } else { numericFilters.push(attribute + operator + value); } }); } }); }); return numericFilters; }, /** * Return the tags filters depending * @private * @return {string} */ _getTagFilters: function(state) { if (state.tagFilters) { return state.tagFilters; } return state.tagRefinements.join(','); }, /** * Build facetFilters parameter based on current refinements. The array returned * contains strings representing the facet filters in the algolia format. * @private * @param {string} [facet] if set, the current disjunctive facet * @return {array.<string>} */ _getFacetFilters: function(state, facet, hierarchicalRootLevel) { var facetFilters = []; forEach_1(state.facetsRefinements, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); forEach_1(state.facetsExcludes, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(facetValues, facetName) { if (facetName === facet || !facetValues || facetValues.length === 0) return; var orFilters = []; forEach_1(facetValues, function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); forEach_1(state.hierarchicalFacetsRefinements, function(facetValues, facetName) { var facetValue = facetValues[0]; if (facetValue === undefined) { return; } var hierarchicalFacet = state.getHierarchicalFacetByName(facetName); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeToRefine; var attributesIndex; // we ask for parent facet values only when the `facet` is the current hierarchical facet if (facet === facetName) { // if we are at the root level already, no need to ask for facet values, we get them from // the hits query if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) || (rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) { return; } if (!rootPath) { attributesIndex = facetValue.split(separator).length - 2; facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator)); } else { attributesIndex = rootPath.split(separator).length - 1; facetValue = rootPath; } attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } else { attributesIndex = facetValue.split(separator).length - 1; attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } if (attributeToRefine) { facetFilters.push([attributeToRefine + ':' + facetValue]); } }); return facetFilters; }, _getHitsHierarchicalFacetsAttributes: function(state) { var out = []; return reduce_1( state.hierarchicalFacets, // ask for as much levels as there's hierarchical refinements function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) { var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0]; // if no refinement, ask for root level if (!hierarchicalRefinement) { allAttributes.push(hierarchicalFacet.attributes[0]); return allAttributes; } var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var level = hierarchicalRefinement.split(separator).length; var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1); return allAttributes.concat(newAttributes); }, out); }, _getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) { var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (rootLevel === true) { var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeIndex = 0; if (rootPath) { attributeIndex = rootPath.split(separator).length; } return [hierarchicalFacet.attributes[attributeIndex]]; } var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || ''; // if refinement is 'beers > IPA > Flying dog', // then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values) var parentLevel = hierarchicalRefinement.split(separator).length - 1; return hierarchicalFacet.attributes.slice(0, parentLevel + 1); }, getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) { var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state; var searchForFacetSearchParameters = { facetQuery: query, facetName: facetName }; if (typeof maxFacetHits === 'number') { searchForFacetSearchParameters.maxFacetHits = maxFacetHits; } var queries = merge_1(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters); return queries; } }; var requestBuilder_1 = requestBuilder; /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { _baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } var _baseInverter = baseInverter; /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return _baseInverter(object, setter, toIteratee(iteratee), {}); }; } var _createInverter = createInverter; /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = _createInverter(function(result, value, key) { result[value] = key; }, constant_1(identity_1)); var invert_1 = invert; var keys2Short = { advancedSyntax: 'aS', allowTyposOnNumericTokens: 'aTONT', analyticsTags: 'aT', analytics: 'a', aroundLatLngViaIP: 'aLLVIP', aroundLatLng: 'aLL', aroundPrecision: 'aP', aroundRadius: 'aR', attributesToHighlight: 'aTH', attributesToRetrieve: 'aTR', attributesToSnippet: 'aTS', disjunctiveFacetsRefinements: 'dFR', disjunctiveFacets: 'dF', distinct: 'd', facetsExcludes: 'fE', facetsRefinements: 'fR', facets: 'f', getRankingInfo: 'gRI', hierarchicalFacetsRefinements: 'hFR', hierarchicalFacets: 'hF', highlightPostTag: 'hPoT', highlightPreTag: 'hPrT', hitsPerPage: 'hPP', ignorePlurals: 'iP', index: 'idx', insideBoundingBox: 'iBB', insidePolygon: 'iPg', length: 'l', maxValuesPerFacet: 'mVPF', minimumAroundRadius: 'mAR', minProximity: 'mP', minWordSizefor1Typo: 'mWS1T', minWordSizefor2Typos: 'mWS2T', numericFilters: 'nF', numericRefinements: 'nR', offset: 'o', optionalWords: 'oW', page: 'p', queryType: 'qT', query: 'q', removeWordsIfNoResults: 'rWINR', replaceSynonymsInHighlight: 'rSIH', restrictSearchableAttributes: 'rSA', synonyms: 's', tagFilters: 'tF', tagRefinements: 'tR', typoTolerance: 'tT', optionalTagFilters: 'oTF', optionalFacetFilters: 'oFF', snippetEllipsisText: 'sET', disableExactOnAttributes: 'dEOA', enableExactOnSingleWordQuery: 'eEOSWQ' }; var short2Keys = invert_1(keys2Short); var shortener = { /** * All the keys of the state, encoded. * @const */ ENCODED_PARAMETERS: keys_1(short2Keys), /** * Decode a shorten attribute * @param {string} shortKey the shorten attribute * @return {string} the decoded attribute, undefined otherwise */ decode: function(shortKey) { return short2Keys[shortKey]; }, /** * Encode an attribute into a short version * @param {string} key the attribute * @return {string} the shorten attribute */ encode: function(key) { return keys2Short[key]; } }; var utils = createCommonjsModule(function (module, exports) { var has = Object.prototype.hasOwnProperty; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { var obj; while (queue.length) { var item = queue.pop(); obj = item.obj[item.prop]; if (Array.isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } return obj; }; exports.arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.merge = function merge(target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = exports.arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = exports.merge(target[i], item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = exports.merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; exports.assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.encode = function encode(str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; exports.compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } return compactQueue(queue); }; exports.isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function isBuffer(obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; }); var utils_1 = utils.arrayToObject; var utils_2 = utils.merge; var utils_3 = utils.assign; var utils_4 = utils.decode; var utils_5 = utils.encode; var utils_6 = utils.compact; var utils_7 = utils.isRegExp; var utils_8 = utils.isBuffer; var replace = String.prototype.replace; var percentTwenties = /%20/g; var formats = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching return prefix + '[]'; }, indices: function indices(prefix, key) { // eslint-disable-line func-name-matching return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { // eslint-disable-line func-name-matching return prefix; } }; var toISO = Date.prototype.toISOString; var defaults$2 = { delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify( // eslint-disable-line func-name-matching object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults$2.encoder) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$2.encoder); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$2.encoder))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } } return values; }; var stringify_1 = function (object, opts) { var obj = object; var options = opts ? utils.assign({}, opts) : {}; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var delimiter = typeof options.delimiter === 'undefined' ? defaults$2.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$2.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults$2.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults$2.encode; var encoder = typeof options.encoder === 'function' ? options.encoder : defaults$2.encoder; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults$2.serializeDate; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults$2.encodeValuesOnly; if (typeof options.format === 'undefined') { options.format = formats['default']; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; return joined.length > 0 ? prefix + joined : ''; }; var has = Object.prototype.hasOwnProperty; var defaults$3 = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults$3.decoder); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults$3.decoder); val = options.decoder(part.slice(pos + 1), defaults$3.decoder); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]') { obj = []; obj = obj.concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; var parse = function (str, opts) { var options = opts ? utils.assign({}, opts) : {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults$3.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults$3.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults$3.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults$3.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults$3.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults$3.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults$3.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults$3.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$3.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; var lib$1 = { formats: formats, parse: parse, stringify: stringify_1 }; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$7 = 1; var WRAP_PARTIAL_FLAG$4 = 32; /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = _baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG$7; if (partials.length) { var holders = _replaceHolders(partials, _getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG$4; } return _createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; var bind_1 = bind; /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return _basePickBy(object, paths, function(value, path) { return hasIn_1(object, path); }); } var _basePick = basePick; /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = _flatRest(function(object, paths) { return object == null ? {} : _basePick(object, paths); }); var pick_1 = pick; /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, iteratee(value, key, object), value); }); return result; } var mapKeys_1 = mapKeys; /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } var mapValues_1 = mapValues; /** * Module containing the functions to serialize and deserialize * {SearchParameters} in the query string format * @module algoliasearchHelper.url */ var encode = utils.encode; function recursiveEncode(input) { if (isPlainObject_1(input)) { return mapValues_1(input, recursiveEncode); } if (isArray_1(input)) { return map_1(input, recursiveEncode); } if (isString_1(input)) { return encode(input); } return input; } var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR']; var stateKeys = shortener.ENCODED_PARAMETERS; function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) { if (prefixRegexp !== null) { a = a.replace(prefixRegexp, ''); b = b.replace(prefixRegexp, ''); } a = invertedMapping[a] || a; b = invertedMapping[b] || b; if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) { if (a === 'q') return -1; if (b === 'q') return 1; var isARefinements = refinementsParameters.indexOf(a) !== -1; var isBRefinements = refinementsParameters.indexOf(b) !== -1; if (isARefinements && !isBRefinements) { return 1; } else if (isBRefinements && !isARefinements) { return -1; } } return a.localeCompare(b); } /** * Read a query string and return an object containing the state * @param {string} queryString the query string that will be decoded * @param {object} [options] accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) */ var getStateFromQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var partialStateWithPrefix = lib$1.parse(queryString); var prefixRegexp = new RegExp('^' + prefixForParameters); var partialState = mapKeys_1( partialStateWithPrefix, function(v, k) { var hasPrefix = prefixForParameters && prefixRegexp.test(k); var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k; var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey); return decodedKey || unprefixedKey; } ); var partialStateWithParsedNumbers = SearchParameters_1._parseNumbers(partialState); return pick_1(partialStateWithParsedNumbers, SearchParameters_1.PARAMETERS); }; /** * Retrieve an object of all the properties that are not understandable as helper * parameters. * @param {string} queryString the query string to read * @param {object} [options] the options * - prefixForParameters : prefix used for the helper configuration keys * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} the object containing the parsed configuration that doesn't * to the helper */ var getUnrecognizedParametersInQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var foreignConfig = {}; var config = lib$1.parse(queryString); if (prefixForParameters) { var prefixRegexp = new RegExp('^' + prefixForParameters); forEach_1(config, function(v, key) { if (!prefixRegexp.test(key)) foreignConfig[key] = v; }); } else { forEach_1(config, function(v, key) { if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v; }); } return foreignConfig; }; /** * Generate a query string for the state passed according to the options * @param {SearchParameters} state state to serialize * @param {object} [options] May contain the following parameters : * - prefix : prefix in front of the keys * - mapping : map short attributes to another value e.g. {q: 'query'} * - moreAttributes : more values to be added in the query string. Those values * won't be prefixed. * - safe : get safe urls for use in emails, chat apps or any application auto linking urls. * All parameters and values will be encoded in a way that it's safe to share them. * Default to false for legacy reasons () * @return {string} the query string */ var getQueryStringFromState = function(state, options) { var moreAttributes = options && options.moreAttributes; var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var safe = options && options.safe || false; var invertedMapping = invert_1(mapping); var stateForUrl = safe ? state : recursiveEncode(state); var encodedState = mapKeys_1( stateForUrl, function(v, k) { var shortK = shortener.encode(k); return prefixForParameters + (mapping[shortK] || shortK); } ); var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters); var sort = bind_1(sortQueryStringValues, null, prefixRegexp, invertedMapping); if (!isEmpty_1(moreAttributes)) { var stateQs = lib$1.stringify(encodedState, {encode: safe, sort: sort}); var moreQs = lib$1.stringify(moreAttributes, {encode: safe}); if (!stateQs) return moreQs; return stateQs + '&' + moreQs; } return lib$1.stringify(encodedState, {encode: safe, sort: sort}); }; var url = { getStateFromQueryString: getStateFromQueryString, getUnrecognizedParametersInQueryString: getUnrecognizedParametersInQueryString, getQueryStringFromState: getQueryStringFromState }; var version$1 = '2.22.0'; /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {SearchParameters} state the current parameters with the latest changes applied * @property {SearchResults} lastResults the previous results received from Algolia. `null` before * the first request * @example * helper.on('change', function(state, lastResults) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when a main search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {SearchParameters} state the parameters used for this search * @property {SearchResults} lastResults the results from the previous search. `null` if * it is the first search. * @example * helper.on('search', function(state, lastResults) { * console.log('Search sent'); * }); */ /** * Event triggered when a search using `searchForFacetValues` is sent to Algolia * @event AlgoliaSearchHelper#event:searchForFacetValues * @property {SearchParameters} state the parameters used for this search * it is the first search. * @property {string} facet the facet searched into * @property {string} query the query used to search in the facets * @example * helper.on('searchForFacetValues', function(state, facet, query) { * console.log('searchForFacetValues sent'); * }); */ /** * Event triggered when a search using `searchOnce` is sent to Algolia * @event AlgoliaSearchHelper#event:searchOnce * @property {SearchParameters} state the parameters used for this search * it is the first search. * @example * helper.on('searchOnce', function(state) { * console.log('searchOnce sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {SearchResults} results the results received from Algolia * @property {SearchParameters} state the parameters used to query Algolia. Those might * be different from the one in the helper instance (for example if the network is unreliable). * @example * helper.on('result', function(results, state) { * console.log('Search results received'); * }); */ /** * Event triggered when Algolia sends back an error. For example, if an unknown parameter is * used, the error can be caught using this event. * @event AlgoliaSearchHelper#event:error * @property {Error} error the error returned by the Algolia. * @example * helper.on('error', function(error) { * console.log('Houston we got a problem.'); * }); */ /** * Event triggered when the queue of queries have been depleted (with any result or outdated queries) * @event AlgoliaSearchHelper#event:searchQueueEmpty * @example * helper.on('searchQueueEmpty', function() { * console.log('No more search pending'); * // This is received before the result event if we're not expecting new results * }); * * helper.search(); */ /** * Initialize a new AlgoliaSearchHelper * @class * @classdesc The AlgoliaSearchHelper is a class that ease the management of the * search. It provides an event based interface for search callbacks: * - change: when the internal search state is changed. * This event contains a {@link SearchParameters} object and the * {@link SearchResults} of the last result if any. * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. * - error: when the response is an error. This event contains the error returned by the server. * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {SearchParameters | object} options an object defining the initial * config of the search. It doesn't have to be a {SearchParameters}, * just an object containing the properties you need from it. */ function AlgoliaSearchHelper(client, index, options) { if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line else if (!doesClientAgentContainsHelper(client)) client.addAlgoliaAgent('JS Helper ' + version$1); this.setClient(client); var opts = options || {}; opts.index = index; this.state = SearchParameters_1.make(opts); this.lastResults = null; this._queryId = 0; this._lastQueryIdReceived = -1; this.derivedHelpers = []; this._currentNbQueries = 0; } util.inherits(AlgoliaSearchHelper, events.EventEmitter); /** * Start the search with the parameters set in the state. When the * method is called, it triggers a `search` event. The results will * be available through the `result` event. If an error occurs, an * `error` will be fired instead. * @return {AlgoliaSearchHelper} * @fires search * @fires result * @fires error * @chainable */ AlgoliaSearchHelper.prototype.search = function() { this._search(); return this; }; /** * Gets the search query parameters that would be sent to the Algolia Client * for the hits * @return {object} Query Parameters */ AlgoliaSearchHelper.prototype.getQuery = function() { var state = this.state; return requestBuilder_1._getHitsSearchParams(state); }; /** * Start a search using a modified version of the current state. This method does * not trigger the helper lifecycle and does not modify the state kept internally * by the helper. This second aspect means that the next search call will be the * same as a search call before calling searchOnce. * @param {object} options can contain all the parameters that can be set to SearchParameters * plus the index * @param {function} [callback] optional callback executed when the response from the * server is back. * @return {promise|undefined} if a callback is passed the method returns undefined * otherwise it returns a promise containing an object with two keys : * - content with a SearchResults * - state with the state used for the query as a SearchParameters * @example * // Changing the number of records returned per page to 1 * // This example uses the callback API * var state = helper.searchOnce({hitsPerPage: 1}, * function(error, content, state) { * // if an error occurred it will be passed in error, otherwise its value is null * // content contains the results formatted as a SearchResults * // state is the instance of SearchParameters used for this search * }); * @example * // Changing the number of records returned per page to 1 * // This example uses the promise API * var state1 = helper.searchOnce({hitsPerPage: 1}) * .then(promiseHandler); * * function promiseHandler(res) { * // res contains * // { * // content : SearchResults * // state : SearchParameters (the one used for this specific search) * // } * } */ AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) { var tempState = !options ? this.state : this.state.setQueryParameters(options); var queries = requestBuilder_1._getQueries(tempState.index, tempState); var self = this; this._currentNbQueries++; this.emit('searchOnce', tempState); if (cb) { return this.client.search( queries, function(err, content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); if (err) cb(err, null, tempState); else cb(err, new SearchResults_1(tempState, content.results), tempState); } ); } return this.client.search(queries).then(function(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); return { content: new SearchResults_1(tempState, content.results), state: tempState, _originalResponse: content }; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Structure of each result when using * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * @typedef FacetSearchHit * @type {object} * @property {string} value the facet value * @property {string} highlighted the facet value highlighted with the query string * @property {number} count number of occurrence of this facet value * @property {boolean} isRefined true if the value is already refined */ /** * Structure of the data resolved by the * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * promise. * @typedef FacetSearchResult * @type {object} * @property {FacetSearchHit} facetHits the results for this search for facet values * @property {number} processingTimeMS time taken by the query inside the engine */ /** * Search for facet values based on an query and the name of a faceted attribute. This * triggers a search and will return a promise. On top of using the query, it also sends * the parameters from the state so that the search is narrowed down to only the possible values. * * See the description of [FacetSearchResult](reference.html#FacetSearchResult) * @param {string} facet the name of the faceted attribute * @param {string} query the string query for the search * @param {number} maxFacetHits the maximum number values returned. Should be > 0 and <= 100 * @return {promise<FacetSearchResult>} the results of the search */ AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits) { var state = this.state; var index = this.client.initIndex(this.state.index); var isDisjunctive = state.isDisjunctiveFacet(facet); var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, this.state); this._currentNbQueries++; var self = this; this.emit('searchForFacetValues', state, facet, query); return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); content.facetHits = forEach_1(content.facetHits, function(f) { f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value); }); return content; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Sets the text query used for the search. * * This method resets the current page to 0. * @param {string} q the user query * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setQuery = function(q) { this.state = this.state.setPage(0).setQuery(q); this._change(); return this; }; /** * Remove all the types of refinements except tags. A string can be provided to remove * only the refinements of a specific attribute. For more advanced use case, you can * provide a function instead. This function should follow the * [clearCallback definition](#SearchParameters.clearCallback). * * This method resets the current page to 0. * @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * // Removing all the refinements * helper.clearRefinements().search(); * @example * // Removing all the filters on a the category attribute. * helper.clearRefinements('category').search(); * @example * // Removing only the exclude filters on the category facet. * helper.clearRefinements(function(value, attribute, type) { * return type === 'exclude' && attribute === 'category'; * }).search(); */ AlgoliaSearchHelper.prototype.clearRefinements = function(name) { this.state = this.state.setPage(0).clearRefinements(name); this._change(); return this; }; /** * Remove all the tag filters. * * This method resets the current page to 0. * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.clearTags = function() { this.state = this.state.setPage(0).clearTags(); this._change(); return this; }; /** * Adds a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() { return this.addDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Adds a refinement on a hierarchical facet. It will throw * an exception if the facet is not defined or if the facet * is already refined. * * This method resets the current page to 0. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is refined * @chainable * @fires change */ AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value); this._change(); return this; }; /** * Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} operator the operator of the filter * @param {number} value the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Adds a filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement} */ AlgoliaSearchHelper.prototype.addRefine = function() { return this.addFacetRefinement.apply(this, arguments); }; /** * Adds a an exclusion filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).addExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion} */ AlgoliaSearchHelper.prototype.addExclude = function() { return this.addFacetExclusion.apply(this, arguments); }; /** * Adds a tag filter with the `tag` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag the tag to add to the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addTag = function(tag) { this.state = this.state.setPage(0).addTagRefinement(tag); this._change(); return this; }; /** * Removes an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is not set, it doesn't change the filters. * * Some parameters are optional, triggering different behavior: * - if the value is not provided, then all the numeric value will be removed for the * specified attribute/operator couple. * - if the operator is not provided either, then all the numeric filter on this attribute * will be removed. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} [operator] the operator of the filter * @param {number} [value] the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Removes a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() { return this.removeDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is not refined * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) { this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet); this._change(); return this; }; /** * Removes a filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement} */ AlgoliaSearchHelper.prototype.removeRefine = function() { return this.removeFacetRefinement.apply(this, arguments); }; /** * Removes an exclusion filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).removeExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion} */ AlgoliaSearchHelper.prototype.removeExclude = function() { return this.removeFacetExclusion.apply(this, arguments); }; /** * Removes a tag filter with the `tag` provided. If the * filter is not set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag tag to remove from the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeTag = function(tag) { this.state = this.state.setPage(0).removeTagRefinement(tag); this._change(); return this; }; /** * Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion} */ AlgoliaSearchHelper.prototype.toggleExclude = function() { return this.toggleFacetExclusion.apply(this, arguments); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable * @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) { return this.toggleFacetRefinement(facet, value); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).toggleFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefine = function() { return this.toggleFacetRefinement.apply(this, arguments); }; /** * Adds or removes a tag filter with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} tag tag to remove or add * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleTag = function(tag) { this.state = this.state.setPage(0).toggleTagRefinement(tag); this._change(); return this; }; /** * Increments the page number by one. * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setPage(0).nextPage().getPage(); * // returns 1 */ AlgoliaSearchHelper.prototype.nextPage = function() { return this.setPage(this.state.page + 1); }; /** * Decrements the page number by one. * @fires change * @return {AlgoliaSearchHelper} * @chainable * @example * helper.setPage(1).previousPage().getPage(); * // returns 0 */ AlgoliaSearchHelper.prototype.previousPage = function() { return this.setPage(this.state.page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this.state = this.state.setPage(page); this._change(); return this; } /** * Change the current page * @deprecated * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage; /** * Updates the current page. * @function * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setPage = setCurrentPage; /** * Updates the name of the index that will be targeted by the query. * * This method resets the current page to 0. * @param {string} name the index name * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setIndex = function(name) { this.state = this.state.setPage(0).setIndex(name); this._change(); return this; }; /** * Update a parameter of the search. This method reset the page * * The complete list of parameters is available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters and facets have their own API) * * This method resets the current page to 0. * @param {string} parameter name of the parameter to update * @param {any} value new value of the parameter * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setQueryParameter('hitsPerPage', 20).search(); */ AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) { var newState = this.state.setPage(0).setQueryParameter(parameter, value); if (this.state === newState) return this; this.state = newState; this._change(); return this; }; /** * Set the whole state (warning: will erase previous state) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setState = function(newState) { this.state = SearchParameters_1.make(newState); this._change(); return this; }; /** * Get the current search state stored in the helper. This object is immutable. * @param {string[]} [filters] optional filters to retrieve only a subset of the state * @return {SearchParameters|object} if filters is specified a plain object is * returned containing only the requested fields, otherwise return the unfiltered * state * @example * // Get the complete state as stored in the helper * helper.getState(); * @example * // Get a part of the state with all the refinements on attributes and the query * helper.getState(['query', 'attribute:category']); */ AlgoliaSearchHelper.prototype.getState = function(filters) { if (filters === undefined) return this.state; return this.state.filter(filters); }; /** * DEPRECATED Get part of the state as a query string. By default, the output keys will not * be prefixed and will only take the applied refinements and the query. * @deprecated * @param {object} [options] May contain the following parameters : * * **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for * the index, all the refinements with `attribute:*` or for some specific attributes with * `attribute:theAttribute` * * **prefix** : prefix in front of the keys * * **moreAttributes** : more values to be added in the query string. Those values * won't be prefixed. * @return {string} the query string */ AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) { var filters = options && options.filters || ['query', 'attribute:*']; var partialState = this.getState(filters); return url.getQueryStringFromState(partialState, options); }; /** * DEPRECATED Read a query string and return an object containing the state. Use * url module. * @deprecated * @static * @param {string} queryString the query string that will be decoded * @param {object} options accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) * @see {@link url#getStateFromQueryString} */ AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString; /** * DEPRECATED Retrieve an object of all the properties that are not understandable as helper * parameters. Use url module. * @deprecated * @static * @param {string} queryString the query string to read * @param {object} options the options * - prefixForParameters : prefix used for the helper configuration keys * @return {object} the object containing the parsed configuration that doesn't * to the helper */ AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString; /** * DEPRECATED Overrides part of the state with the properties stored in the provided query * string. * @deprecated * @param {string} queryString the query string containing the informations to url the state * @param {object} options optional parameters : * - prefix : prefix used for the algolia parameters * - triggerChange : if set to true the state update will trigger a change event */ AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) { var triggerChange = options && options.triggerChange || false; var configuration = url.getStateFromQueryString(queryString, options); var updatedState = this.state.setQueryParameters(configuration); if (triggerChange) this.setState(updatedState); else this.overrideStateWithoutTriggeringChangeEvent(updatedState); }; /** * Override the current state without triggering a change event. * Do not use this method unless you know what you are doing. (see the example * for a legit use case) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @example * helper.on('change', function(state){ * // In this function you might want to find a way to store the state in the url/history * updateYourURL(state) * }) * window.onpopstate = function(event){ * // This is naive though as you should check if the state is really defined etc. * helper.overrideStateWithoutTriggeringChangeEvent(event.state).search() * } * @chainable */ AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) { this.state = new SearchParameters_1(newState); return this; }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isRefined = function(facet, value) { if (this.state.isConjunctiveFacet(facet)) { return this.state.isFacetRefined(facet, value); } else if (this.state.isDisjunctiveFacet(facet)) { return this.state.isDisjunctiveFacetRefined(facet, value); } throw new Error(facet + ' is not properly defined in this helper configuration' + '(use the facets or disjunctiveFacets keys to configure it)'); }; /** * Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters. * @param {string} attribute the name of the attribute * @return {boolean} true if the attribute is filtered by at least one value * @example * // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters * helper.hasRefinements('price'); // false * helper.addNumericRefinement('price', '>', 100); * helper.hasRefinements('price'); // true * * helper.hasRefinements('color'); // false * helper.addFacetRefinement('color', 'blue'); * helper.hasRefinements('color'); // true * * helper.hasRefinements('material'); // false * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * helper.hasRefinements('material'); // true * * helper.hasRefinements('categories'); // false * helper.toggleFacetRefinement('categories', 'kitchen > knife'); * helper.hasRefinements('categories'); // true * */ AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) { if (!isEmpty_1(this.state.getNumericRefinements(attribute))) { return true; } else if (this.state.isConjunctiveFacet(attribute)) { return this.state.isFacetRefined(attribute); } else if (this.state.isDisjunctiveFacet(attribute)) { return this.state.isDisjunctiveFacetRefined(attribute); } else if (this.state.isHierarchicalFacet(attribute)) { return this.state.isHierarchicalFacetRefined(attribute); } // there's currently no way to know that the user did call `addNumericRefinement` at some point // thus we cannot distinguish if there once was a numeric refinement that was cleared // so we will return false in every other situations to be consistent // while what we should do here is throw because we did not find the attribute in any type // of refinement return false; }; /** * Check if a value is excluded for a specific faceted attribute. If the value * is omitted then the function checks if there is any excluding refinements. * * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} true if refined * @example * helper.isExcludeRefined('color'); // false * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // false * * helper.addFacetExclusion('color', 'red'); * * helper.isExcludeRefined('color'); // true * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // true */ AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) { return this.state.isExcludeRefined(facet, value); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) { return this.state.isDisjunctiveFacetRefined(facet, value); }; /** * Check if the string is a currently filtering tag. * @param {string} tag tag to check * @return {boolean} */ AlgoliaSearchHelper.prototype.hasTag = function(tag) { return this.state.isTagRefined(tag); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag} */ AlgoliaSearchHelper.prototype.isTagRefined = function() { return this.hasTagRefinements.apply(this, arguments); }; /** * Get the name of the currently used index. * @return {string} * @example * helper.setIndex('highestPrice_products').getIndex(); * // returns 'highestPrice_products' */ AlgoliaSearchHelper.prototype.getIndex = function() { return this.state.index; }; function getCurrentPage() { return this.state.page; } /** * Get the currently selected page * @deprecated * @return {number} the current page */ AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage; /** * Get the currently selected page * @function * @return {number} the current page */ AlgoliaSearchHelper.prototype.getPage = getCurrentPage; /** * Get all the tags currently set to filters the results. * * @return {string[]} The list of tags currently set. */ AlgoliaSearchHelper.prototype.getTags = function() { return this.state.tagRefinements; }; /** * Get a parameter of the search by its name. It is possible that a parameter is directly * defined in the index dashboard, but it will be undefined using this method. * * The complete list of parameters is * available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters have their own API) * @param {string} parameterName the parameter name * @return {any} the parameter value * @example * var hitsPerPage = helper.getQueryParameter('hitsPerPage'); */ AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) { return this.state.getQueryParameter(parameterName); }; /** * Get the list of refinements for a given attribute. This method works with * conjunctive, disjunctive, excluding and numerical filters. * * See also SearchResults#getRefinements * * @param {string} facetName attribute name used for faceting * @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and * a type. Numeric also contains an operator. * @example * helper.addNumericRefinement('price', '>', 100); * helper.getRefinements('price'); * // [ * // { * // "value": [ * // 100 * // ], * // "operator": ">", * // "type": "numeric" * // } * // ] * @example * helper.addFacetRefinement('color', 'blue'); * helper.addFacetExclusion('color', 'red'); * helper.getRefinements('color'); * // [ * // { * // "value": "blue", * // "type": "conjunctive" * // }, * // { * // "value": "red", * // "type": "exclude" * // } * // ] * @example * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * // [ * // { * // "value": "plastic", * // "type": "disjunctive" * // } * // ] */ AlgoliaSearchHelper.prototype.getRefinements = function(facetName) { var refinements = []; if (this.state.isConjunctiveFacet(facetName)) { var conjRefinements = this.state.getConjunctiveRefinements(facetName); forEach_1(conjRefinements, function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); forEach_1(excludeRefinements, function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); forEach_1(disjRefinements, function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); forEach_1(numericRefinements, function(value, operator) { refinements.push({ value: value, operator: operator, type: 'numeric' }); }); return refinements; }; /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) { return this.state.getNumericRefinement(attribute, operator); }; /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) { return this.state.getHierarchicalFacetBreadcrumb(facetName); }; // /////////// PRIVATE /** * Perform the underlying queries * @private * @return {undefined} * @fires search * @fires result * @fires error */ AlgoliaSearchHelper.prototype._search = function() { var state = this.state; var mainQueries = requestBuilder_1._getQueries(state.index, state); var states = [{ state: state, queriesCount: mainQueries.length, helper: this }]; this.emit('search', state, this.lastResults); var derivedQueries = map_1(this.derivedHelpers, function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var queries = requestBuilder_1._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: queries.length, helper: derivedHelper }); derivedHelper.emit('search', derivedState, derivedHelper.lastResults); return queries; }); var queries = mainQueries.concat(flatten_1(derivedQueries)); var queryId = this._queryId++; this._currentNbQueries++; this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId)); }; /** * Transform the responses as sent by the server and transform them into a user * usable object that merge the results of all the batch requests. It will dispatch * over the different helper + derived helpers (when there are some). * @private * @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>} * state state used for to generate the request * @param {number} queryId id of the current request * @param {Error} err error if any, null otherwise * @param {object} content content of the response * @return {undefined} */ AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) { // FIXME remove the number of outdated queries discarded instead of just one if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= (queryId - this._lastQueryIdReceived); this._lastQueryIdReceived = queryId; if (err) { this.emit('error', err); if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); } else { if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); var results = content.results; forEach_1(states, function(s) { var state = s.state; var queriesCount = s.queriesCount; var helper = s.helper; var specificResults = results.splice(0, queriesCount); var formattedResponse = helper.lastResults = new SearchResults_1(state, specificResults); helper.emit('result', formattedResponse, state); }); } }; AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) { return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0; }; /** * Test if there are some disjunctive refinements on the facet * @private * @param {string} facet the attribute to test * @return {boolean} */ AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) { return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0; }; AlgoliaSearchHelper.prototype._change = function() { this.emit('change', this.state, this.lastResults); }; /** * Clears the cache of the underlying Algolia client. * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.clearCache = function() { this.client.clearCache(); return this; }; /** * Updates the internal client instance. If the reference of the clients * are equal then no update is actually done. * @param {AlgoliaSearch} newClient an AlgoliaSearch client * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.setClient = function(newClient) { if (this.client === newClient) return this; if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version$1); this.client = newClient; return this; }; /** * Gets the instance of the currently used client. * @return {AlgoliaSearch} */ AlgoliaSearchHelper.prototype.getClient = function() { return this.client; }; /** * Creates an derived instance of the Helper. A derived helper * is a way to request other indices synchronised with the lifecycle * of the main Helper. This mechanism uses the multiqueries feature * of Algolia to aggregate all the requests in a single network call. * * This method takes a function that is used to create a new SearchParameter * that will be used to create requests to Algolia. Those new requests * are created just before the `search` event. The signature of the function * is `SearchParameters -> SearchParameters`. * * This method returns a new DerivedHelper which is an EventEmitter * that fires the same `search`, `result` and `error` events. Those * events, however, will receive data specific to this DerivedHelper * and the SearchParameters that is returned by the call of the * parameter function. * @param {function} fn SearchParameters -> SearchParameters * @return {DerivedHelper} */ AlgoliaSearchHelper.prototype.derive = function(fn) { var derivedHelper = new DerivedHelper_1(this, fn); this.derivedHelpers.push(derivedHelper); return derivedHelper; }; /** * This method detaches a derived Helper from the main one. Prefer using the one from the * derived helper itself, to remove the event listeners too. * @private * @return {undefined} * @throws Error */ AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) { var pos = this.derivedHelpers.indexOf(derivedHelper); if (pos === -1) throw new Error('Derived helper already detached'); this.derivedHelpers.splice(pos, 1); }; /** * This method returns true if there is currently at least one on-going search. * @return {boolean} true if there is a search pending */ AlgoliaSearchHelper.prototype.hasPendingRequests = function() { return this._currentNbQueries > 0; }; /** * @typedef AlgoliaSearchHelper.NumericRefinement * @type {object} * @property {number[]} value the numbers that are used for filtering this attribute with * the operator specified. * @property {string} operator the faceting data: value, number of entries * @property {string} type will be 'numeric' */ /** * @typedef AlgoliaSearchHelper.FacetRefinement * @type {object} * @property {string} value the string use to filter the attribute * @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude' */ /* * This function tests if the _ua parameter of the client * already contains the JS Helper UA */ function doesClientAgentContainsHelper(client) { // this relies on JS Client internal variable, this might break if implementation changes var currentAgent = client._ua; return !currentAgent ? false : currentAgent.indexOf('JS Helper') !== -1; } var algoliasearch_helper = AlgoliaSearchHelper; /** * The algoliasearchHelper module is the function that will let its * contains everything needed to use the Algoliasearch * Helper. It is a also a function that instanciate the helper. * To use the helper, you also need the Algolia JS client v3. * @example * //using the UMD build * var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76'); * var helper = algoliasearchHelper(client, 'bestbuy', { * facets: ['shipping'], * disjunctiveFacets: ['category'] * }); * helper.on('result', function(result) { * console.log(result); * }); * helper.toggleRefine('Movies & TV Shows') * .toggleRefine('Free shipping') * .search(); * @example * // The helper is an event emitter using the node API * helper.on('result', updateTheResults); * helper.once('result', updateTheResults); * helper.removeListener('result', updateTheResults); * helper.removeAllListeners('result'); * @module algoliasearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the name of the index to query * @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it. * @return {AlgoliaSearchHelper} */ function algoliasearchHelper(client, index, opts) { return new algoliasearch_helper(client, index, opts); } /** * The version currently used * @member module:algoliasearchHelper.version * @type {number} */ algoliasearchHelper.version = version$1; /** * Constructor for the Helper. * @member module:algoliasearchHelper.AlgoliaSearchHelper * @type {AlgoliaSearchHelper} */ algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper; /** * Constructor for the object containing all the parameters of the search. * @member module:algoliasearchHelper.SearchParameters * @type {SearchParameters} */ algoliasearchHelper.SearchParameters = SearchParameters_1; /** * Constructor for the object containing the results of the search. * @member module:algoliasearchHelper.SearchResults * @type {SearchResults} */ algoliasearchHelper.SearchResults = SearchResults_1; /** * URL tools to generate query string and parse them from/into * SearchParameters * @member module:algoliasearchHelper.url * @type {object} {@link url} * */ algoliasearchHelper.url = url; var algoliasearchHelper_1 = algoliasearchHelper; var algoliasearchHelper_4 = algoliasearchHelper_1.SearchParameters; // From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js function shallowEqual(objA, objB) { if (objA === objB) { return true; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } function isSpecialClick(event) { var isMiddleClick = event.button === 1; return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey); } function capitalize(key) { return key.length === 0 ? '' : '' + key[0].toUpperCase() + key.slice(1); } function getDisplayName(Component) { return Component.displayName || Component.name || 'UnknownComponent'; } var resolved = Promise.resolve(); var defer = function defer(f) { resolved.then(f); }; function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (isEmpty_1(value) && isPlainObject_1(value)) { delete obj[key]; } else if (isPlainObject_1(value)) { removeEmptyKey(value); } }); return obj; } function createWidgetsManager(onWidgetsUpdate) { var widgets = []; // Is an update scheduled? var scheduled = false; // The state manager's updates need to be batched since more than one // component can register or unregister widgets during the same tick. function scheduleUpdate() { if (scheduled) { return; } scheduled = true; defer(function () { scheduled = false; onWidgetsUpdate(); }); } return { registerWidget: function registerWidget(widget) { widgets.push(widget); scheduleUpdate(); return function unregisterWidget() { widgets.splice(widgets.indexOf(widget), 1); scheduleUpdate(); }; }, update: scheduleUpdate, getWidgets: function getWidgets() { return widgets; } }; } function createStore(initialState) { var state = initialState; var listeners = []; function dispatch() { listeners.forEach(function (listener) { return listener(); }); } return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; dispatch(); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubcribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } var highlightTags = { highlightPreTag: "<ais-highlight-0000000000>", highlightPostTag: "</ais-highlight-0000000000>" }; 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 defineProperty$2 = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; var slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }; /** * Creates a new instance of the InstantSearchManager which controls the widgets and * trigger the search when the widgets are updated. * @param {string} indexName - the main index name * @param {object} initialState - initial widget state * @param {object} SearchParameters - optional additional parameters to send to the algolia API * @param {number} stalledSearchDelay - time (in ms) after the search is stalled * @return {InstantSearchManager} a new instance of InstantSearchManager */ function createInstantSearchManager(_ref) { var indexName = _ref.indexName, _ref$initialState = _ref.initialState, initialState = _ref$initialState === undefined ? {} : _ref$initialState, algoliaClient = _ref.algoliaClient, _ref$searchParameters = _ref.searchParameters, searchParameters = _ref$searchParameters === undefined ? {} : _ref$searchParameters, resultsState = _ref.resultsState, stalledSearchDelay = _ref.stalledSearchDelay; var baseSP = new algoliasearchHelper_4(_extends({}, searchParameters, { index: indexName }, highlightTags)); var stalledSearchTimer = null; var helper = algoliasearchHelper_1(algoliaClient, indexName, baseSP); helper.on('result', handleSearchSuccess); helper.on('error', handleSearchError); helper.on('search', handleNewSearch); var derivedHelpers = {}; var indexMapping = {}; // keep track of the original index where the parameters applied when sortBy is used. var initialSearchParameters = helper.state; var widgetsManager = createWidgetsManager(onWidgetsUpdate); var store = createStore({ widgets: initialState, metadata: [], results: resultsState || null, error: null, searching: false, isSearchStalled: true, searchingForFacetValues: false }); var skip = false; function skipSearch() { skip = true; } function updateClient(client) { helper.setClient(client); search(); } function clearCache() { helper.clearCache(); search(); } function getMetadata(state) { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getMetadata); }).map(function (widget) { return widget.getMetadata(state); }); } function getSearchParameters() { indexMapping = {}; var sharedParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return !widget.context.multiIndexContext && (widget.props.indexName === indexName || !widget.props.indexName); }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, initialSearchParameters); indexMapping[sharedParameters.index] = indexName; var derivatedWidgets = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex !== indexName || widget.props.indexName && widget.props.indexName !== indexName; }).reduce(function (indices, widget) { var targetedIndex = widget.context.multiIndexContext ? widget.context.multiIndexContext.targetedIndex : widget.props.indexName; var index = indices.find(function (i) { return i.targetedIndex === targetedIndex; }); if (index) { index.widgets.push(widget); } else { indices.push({ targetedIndex: targetedIndex, widgets: [widget] }); } return indices; }, []); var mainIndexParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex === indexName || widget.props.indexName && widget.props.indexName === indexName; }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); indexMapping[mainIndexParameters.index] = indexName; return { sharedParameters: sharedParameters, mainIndexParameters: mainIndexParameters, derivatedWidgets: derivatedWidgets }; } function search() { if (!skip) { var _getSearchParameters = getSearchParameters(helper.state), sharedParameters = _getSearchParameters.sharedParameters, mainIndexParameters = _getSearchParameters.mainIndexParameters, derivatedWidgets = _getSearchParameters.derivatedWidgets; Object.keys(derivedHelpers).forEach(function (key) { return derivedHelpers[key].detach(); }); derivedHelpers = {}; helper.setState(sharedParameters); derivatedWidgets.forEach(function (derivatedSearchParameters) { var index = derivatedSearchParameters.targetedIndex; var derivedHelper = helper.derive(function () { var parameters = derivatedSearchParameters.widgets.reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); indexMapping[parameters.index] = index; return parameters; }); derivedHelper.on('result', handleSearchSuccess); derivedHelper.on('error', handleSearchError); derivedHelpers[index] = derivedHelper; }); helper.setState(mainIndexParameters); helper.search(); } } function handleSearchSuccess(content) { var state = store.getState(); var results = state.results ? state.results : {}; /* if switching from mono index to multi index and vice versa, results needs to reset to {}*/ results = !isEmpty_1(derivedHelpers) && results.getFacetByName ? {} : results; if (!isEmpty_1(derivedHelpers)) { results[indexMapping[content.index]] = content; } else { results = content; } var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); stalledSearchTimer = null; nextIsSearchStalled = false; } var nextState = omit_1(_extends({}, currentState, { results: results, isSearchStalled: nextIsSearchStalled, searching: false, error: null }), 'resultsFacetValues'); store.setState(nextState); } function handleSearchError(error) { var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); nextIsSearchStalled = false; } var nextState = omit_1(_extends({}, currentState, { isSearchStalled: nextIsSearchStalled, error: error, searching: false }), 'resultsFacetValues'); store.setState(nextState); } function handleNewSearch() { if (!stalledSearchTimer) { stalledSearchTimer = setTimeout(function () { var nextState = omit_1(_extends({}, store.getState(), { isSearchStalled: true }), 'resultsFacetValues'); store.setState(nextState); }, stalledSearchDelay); } } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_extends({}, store.getState(), { metadata: metadata, searching: true })); // Since the `getSearchParameters` method of widgets also depends on props, // the result search parameters might have changed. search(); } function transitionState(nextSearchState) { var searchState = store.getState().widgets; return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.transitionState); }).reduce(function (res, widget) { return widget.transitionState(searchState, res); }, nextSearchState); } function onExternalStateUpdate(nextSearchState) { var metadata = getMetadata(nextSearchState); store.setState(_extends({}, store.getState(), { widgets: nextSearchState, metadata: metadata, searching: true })); search(); } function onSearchForFacetValues(_ref2) { var facetName = _ref2.facetName, query = _ref2.query, maxFacetHits = _ref2.maxFacetHits; store.setState(_extends({}, store.getState(), { searchingForFacetValues: true })); helper.searchForFacetValues(facetName, query, maxFacetHits).then(function (content) { var _babelHelpers$extends; store.setState(_extends({}, store.getState(), { resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_babelHelpers$extends = {}, defineProperty$2(_babelHelpers$extends, facetName, content.facetHits), defineProperty$2(_babelHelpers$extends, 'query', query), _babelHelpers$extends)), searchingForFacetValues: false })); }, function (error) { store.setState(_extends({}, store.getState(), { error: error, searchingForFacetValues: false })); }).catch(function (error) { // Since setState is synchronous, any error that occurs in the render of a // component will be swallowed by this promise. // This is a trick to make the error show up correctly in the console. // See http://stackoverflow.com/a/30741722/969302 setTimeout(function () { throw error; }); }); } function updateIndex(newIndex) { initialSearchParameters = initialSearchParameters.setIndex(newIndex); search(); } function getWidgetsIds() { return store.getState().metadata.reduce(function (res, meta) { return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res; }, []); } return { store: store, widgetsManager: widgetsManager, getWidgetsIds: getWidgetsIds, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, onSearchForFacetValues: onSearchForFacetValues, updateClient: updateClient, updateIndex: updateIndex, clearCache: clearCache, skipSearch: skipSearch }; } function validateNextProps(props, nextProps) { if (!props.searchState && nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled"); } else if (props.searchState && !nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled"); } } /* eslint valid-jsdoc: 0 */ /** * @description * `<InstantSearch>` is the root component of all React InstantSearch implementations. * It provides all the connected components (aka widgets) a means to interact * with the searchState. * @kind widget * @name <InstantSearch> * @requirements You will need to have an Algolia account to be able to use this widget. * [Create one now](https://www.algolia.com/users/sign_up). * @propType {string} appId - Your Algolia application id. * @propType {string} apiKey - Your Algolia search-only API key. * @propType {string} indexName - Main index in which to search. * @propType {boolean} [refresh=false] - Flag to activate when the cache needs to be cleared so that the front-end is updated when a change occurs in the index. * @propType {object} [algoliaClient] - Provide a custom Algolia client instead of the internal one. * @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html). * @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html). * @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html). * @propType {SearchResults|SearchResults[]} [resultsState] - Use this to inject the results that will be used at first rendering. Those results are found by using the `findResultsState` function. Useful for [Server Side Rendering](guide/Server-side_rendering.html). * @propType {number} [stalledSearchDelay=200] - The amount of time before considering that the search takes too much time. The time is expressed in milliseconds. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import {InstantSearch, SearchBox, Hits} from 'react-instantsearch/dom'; * * export default function Search() { * return ( * <InstantSearch * appId="appId" * apiKey="apiKey" * indexName="indexName" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); * } */ var InstantSearch = function (_Component) { inherits(InstantSearch, _Component); function InstantSearch(props) { classCallCheck(this, InstantSearch); var _this = possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props)); _this.isControlled = Boolean(props.searchState); var initialState = _this.isControlled ? props.searchState : {}; _this.isUnmounting = false; _this.aisManager = createInstantSearchManager({ indexName: props.indexName, searchParameters: props.searchParameters, algoliaClient: props.algoliaClient, initialState: initialState, resultsState: props.resultsState, stalledSearchDelay: props.stalledSearchDelay }); return _this; } createClass(InstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { validateNextProps(this.props, nextProps); if (this.props.indexName !== nextProps.indexName) { this.aisManager.updateIndex(nextProps.indexName); } if (this.props.refresh !== nextProps.refresh) { if (nextProps.refresh) { this.aisManager.clearCache(); } } if (this.props.algoliaClient !== nextProps.algoliaClient) { this.aisManager.updateClient(nextProps.algoliaClient); } if (this.isControlled) { this.aisManager.onExternalStateUpdate(nextProps.searchState); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.isUnmounting = true; this.aisManager.skipSearch(); } }, { key: 'getChildContext', value: function getChildContext() { // If not already cached, cache the bound methods so that we can forward them as part // of the context. if (!this._aisContextCache) { this._aisContextCache = { ais: { onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this), createHrefForState: this.createHrefForState.bind(this), onSearchForFacetValues: this.onSearchForFacetValues.bind(this), onSearchStateChange: this.onSearchStateChange.bind(this), onSearchParameters: this.onSearchParameters.bind(this) } }; } return { ais: _extends({}, this._aisContextCache.ais, { store: this.aisManager.store, widgetsManager: this.aisManager.widgetsManager, mainTargetedIndex: this.props.indexName }) }; } }, { key: 'createHrefForState', value: function createHrefForState(searchState) { searchState = this.aisManager.transitionState(searchState); return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: 'onWidgetsInternalStateUpdate', value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.aisManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.isControlled) { this.aisManager.onExternalStateUpdate(searchState); } } }, { key: 'onSearchStateChange', value: function onSearchStateChange(searchState) { if (this.props.onSearchStateChange && !this.isUnmounting) { this.props.onSearchStateChange(searchState); } } }, { key: 'onSearchParameters', value: function onSearchParameters(getSearchParameters, context, props) { if (this.props.onSearchParameters) { var searchState = this.props.searchState ? this.props.searchState : {}; this.props.onSearchParameters(getSearchParameters, context, props, searchState); } } }, { key: 'onSearchForFacetValues', value: function onSearchForFacetValues(searchState) { this.aisManager.onSearchForFacetValues(searchState); } }, { key: 'getKnownKeys', value: function getKnownKeys() { return this.aisManager.getWidgetsIds(); } }, { key: 'render', value: function render() { var childrenCount = React.Children.count(this.props.children); var _props$root = this.props.root, Root = _props$root.Root, props = _props$root.props; if (childrenCount === 0) return null;else return React__default.createElement( Root, props, this.props.children ); } }]); return InstantSearch; }(React.Component); InstantSearch.defaultProps = { stalledSearchDelay: 200 }; InstantSearch.propTypes = { // @TODO: These props are currently constant. indexName: propTypes.string.isRequired, algoliaClient: propTypes.object.isRequired, searchParameters: propTypes.object, createURL: propTypes.func, refresh: propTypes.bool.isRequired, searchState: propTypes.object, onSearchStateChange: propTypes.func, onSearchParameters: propTypes.func, resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]), children: propTypes.node, root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]), props: propTypes.object }).isRequired, stalledSearchDelay: propTypes.number }; InstantSearch.childContextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; var _name$version$descrip = { name: 'react-instantsearch', version: '4.5.0', description: '\u26A1 Lightning-fast search for React and React Native apps, by Algolia', keywords: ['algolia', 'components', 'fast', 'instantsearch', 'react', 'react-native', 'search'], homepage: 'https://community.algolia.com/react-instantsearch', license: 'MIT', author: { name: 'Algolia, Inc.', url: 'https://www.algolia.com' }, main: 'index.js', module: 'es/index.js', repository: { type: 'git', url: 'https://github.com/algolia/react-instantsearch' }, scripts: { build: './scripts/build.sh', 'build-and-publish': './scripts/build-and-publish.sh' }, dependencies: { algoliasearch: '^3.24.0', 'algoliasearch-helper': '^2.21.0', classnames: '^2.2.5', lodash: '^4.17.4', 'prop-types': '^15.5.10' }, devDependencies: { enzyme: '3.3.0', 'enzyme-adapter-react-16': '1.1.1', react: '16.2.0', 'react-dom': '16.2.0', 'react-native': '0.51.0', 'react-test-renderer': '16.2.0' } }; var version$4 = _name$version$descrip.version; /** * Creates a specialized root InstantSearch component. It accepts * an algolia client and a specification of the root Element. * @param {function} defaultAlgoliaClient - a function that builds an Algolia client * @param {object} root - the defininition of the root of an InstantSearch sub tree. * @returns {object} an InstantSearch root */ function createInstantSearch(defaultAlgoliaClient, root) { var _class, _temp; return _temp = _class = function (_Component) { inherits(CreateInstantSearch, _Component); function CreateInstantSearch() { var _ref; classCallCheck(this, CreateInstantSearch); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var _this = possibleConstructorReturn(this, (_ref = CreateInstantSearch.__proto__ || Object.getPrototypeOf(CreateInstantSearch)).call.apply(_ref, [this].concat(args))); _this.client = _this.props.algoliaClient || defaultAlgoliaClient(_this.props.appId, _this.props.apiKey); _this.client.addAlgoliaAgent('react-instantsearch ' + version$4); return _this; } createClass(CreateInstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var props = this.props; if (nextProps.algoliaClient) { this.client = nextProps.algoliaClient; } else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) { this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey); } this.client.addAlgoliaAgent('react-instantsearch ' + version$4); } }, { key: 'render', value: function render() { return React__default.createElement( InstantSearch, { createURL: this.props.createURL, indexName: this.props.indexName, searchParameters: this.props.searchParameters, searchState: this.props.searchState, onSearchStateChange: this.props.onSearchStateChange, onSearchParameters: this.props.onSearchParameters, root: this.props.root, algoliaClient: this.client, refresh: this.props.refresh, resultsState: this.props.resultsState }, this.props.children ); } }]); return CreateInstantSearch; }(React.Component), _class.propTypes = { algoliaClient: propTypes.object, appId: propTypes.string, apiKey: propTypes.string, children: propTypes.oneOfType([propTypes.arrayOf(propTypes.node), propTypes.node]), indexName: propTypes.string.isRequired, searchParameters: propTypes.object, createURL: propTypes.func, searchState: propTypes.object, refresh: propTypes.bool.isRequired, onSearchStateChange: propTypes.func, onSearchParameters: propTypes.func, resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]), root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]).isRequired, props: propTypes.object }) }, _class.defaultProps = { refresh: false, root: root }, _temp; } /* eslint valid-jsdoc: 0 */ /** * @description * `<Index>` is the component that allows you to apply widgets to a dedicated index. It's * useful if you want to build an interface that targets multiple indices. * @kind widget * @name <Index> * @propType {string} indexName - index in which to search. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import {InstantSearch, Index, SearchBox, Hits, Configure} from 'react-instantsearch/dom'; * * export default function Search() { * return ( * <InstantSearch appId="" apiKey="" indexName="index1"> <SearchBox/> <Configure hitsPerPage={1} /> <Index indexName="index1"> <Hits /> </Index> <Index indexName="index2"> <Hits /> </Index> </InstantSearch> * ); * } */ var Index = function (_Component) { inherits(Index, _Component); function Index(props, context) { classCallCheck(this, Index); var _this = possibleConstructorReturn(this, (Index.__proto__ || Object.getPrototypeOf(Index)).call(this, props)); var widgetsManager = context.ais.widgetsManager; /* we want <Index> to be seen as a regular widget. It means that with only <Index> present a new query will be sent to Algolia. That way you don't need a virtual hits widget to use the connectAutoComplete. */ _this.unregisterWidget = widgetsManager.registerWidget(_this); return _this; } createClass(Index, [{ key: 'componentWillMount', value: function componentWillMount() { this.context.ais.onSearchParameters(this.getSearchParameters, this.getChildContext(), this.props); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.props.indexName !== nextProps.indexName) { this.context.ais.widgetsManager.update(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unregisterWidget(); } }, { key: 'getChildContext', value: function getChildContext() { return { multiIndexContext: { targetedIndex: this.props.indexName } }; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters, props) { return searchParameters.setIndex(this.props ? this.props.indexName : props.indexName); } }, { key: 'render', value: function render() { var childrenCount = React.Children.count(this.props.children); var _props$root = this.props.root, Root = _props$root.Root, props = _props$root.props; if (childrenCount === 0) return null;else return React__default.createElement( Root, props, this.props.children ); } }]); return Index; }(React.Component); Index.propTypes = { // @TODO: These props are currently constant. indexName: propTypes.string.isRequired, children: propTypes.node, root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]), props: propTypes.object }).isRequired }; Index.childContextTypes = { multiIndexContext: propTypes.object.isRequired }; Index.contextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; /** * Creates a specialized root Index component. It accepts * a specification of the root Element. * @param {object} defaultRoot - the defininition of the root of an Index sub tree. * @return {object} a Index root */ var createIndex = function createIndex(defaultRoot) { var CreateIndex = function CreateIndex(_ref) { var indexName = _ref.indexName, root = _ref.root, children = _ref.children; return React__default.createElement( Index, { indexName: indexName, root: root }, children ); }; CreateIndex.propTypes = { indexName: propTypes.string.isRequired, root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]).isRequired, props: propTypes.object }), children: propTypes.node }; CreateIndex.defaultProps = { root: defaultRoot }; return CreateIndex; }; var inherits_browser$2 = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var hasOwn = Object.prototype.hasOwnProperty; var toString$2 = Object.prototype.toString; var foreach = function forEach (obj, fn, ctx) { if (toString$2.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; // This file hosts our error definitions // We use custom error "types" so that we can act on them when we need it // e.g.: if error instanceof errors.UnparsableJSON then.. function AlgoliaSearchError(message, extraProperties) { var forEach = foreach; var error = this; // try to get a stacktrace if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old'; } this.name = 'AlgoliaSearchError'; this.message = message || 'Unknown error'; if (extraProperties) { forEach(extraProperties, function addToErrorObject(value, key) { error[key] = value; }); } } inherits_browser$2(AlgoliaSearchError, Error); function createCustomError(name, message) { function AlgoliaSearchCustomError() { var args = Array.prototype.slice.call(arguments, 0); // custom message not set, use default if (typeof args[0] !== 'string') { args.unshift(message); } AlgoliaSearchError.apply(this, args); this.name = 'AlgoliaSearch' + name + 'Error'; } inherits_browser$2(AlgoliaSearchCustomError, AlgoliaSearchError); return AlgoliaSearchCustomError; } // late exports to let various fn defs and inherits take place var errors = { AlgoliaSearchError: AlgoliaSearchError, UnparsableJSON: createCustomError( 'UnparsableJSON', 'Could not parse the incoming response as JSON, see err.more for details' ), RequestTimeout: createCustomError( 'RequestTimeout', 'Request timedout before getting a response' ), Network: createCustomError( 'Network', 'Network issue, see err.more for details' ), JSONPScriptFail: createCustomError( 'JSONPScriptFail', '<script> was loaded but did not call our provided callback' ), JSONPScriptError: createCustomError( 'JSONPScriptError', '<script> unable to load due to an `error` event on it' ), Unknown: createCustomError( 'Unknown', 'Unknown error occured' ) }; // Parse cloud does not supports setTimeout // We do not store a setTimeout reference in the client everytime // We only fallback to a fake setTimeout when not available // setTimeout cannot be override globally sadly var exitPromise = function exitPromise(fn, _setTimeout) { _setTimeout(fn, 0); }; var buildSearchMethod_1 = buildSearchMethod; /** * Creates a search method to be used in clients * @param {string} queryParam the name of the attribute used for the query * @param {string} url the url * @return {function} the search method */ function buildSearchMethod(queryParam, url) { /** * The search method. Prepares the data and send the query to Algolia. * @param {string} query the string used for query search * @param {object} args additional parameters to send with the search * @param {function} [callback] the callback to be called with the client gets the answer * @return {undefined|Promise} If the callback is not provided then this methods returns a Promise */ return function search(query, args, callback) { // warn V2 users on how to search if (typeof query === 'function' && typeof args === 'object' || typeof callback === 'object') { // .search(query, params, cb) // .search(cb, params) throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)'); } // Normalizing the function signature if (arguments.length === 0 || typeof query === 'function') { // Usage : .search(), .search(cb) callback = query; query = ''; } else if (arguments.length === 1 || typeof args === 'function') { // Usage : .search(query/args), .search(query, cb) callback = args; args = undefined; } // At this point we have 3 arguments with values // Usage : .search(args) // careful: typeof null === 'object' if (typeof query === 'object' && query !== null) { args = query; query = undefined; } else if (query === undefined || query === null) { // .search(undefined/null) query = ''; } var params = ''; if (query !== undefined) { params += queryParam + '=' + encodeURIComponent(query); } var additionalUA; if (args !== undefined) { if (args.additionalUA) { additionalUA = args.additionalUA; delete args.additionalUA; } // `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if params = this.as._getSearchParams(args, params); } return this._search(params, url, callback, additionalUA); }; } var deprecate = function deprecate(fn, message) { var warned = false; function deprecated() { if (!warned) { /* eslint no-console:0 */ console.warn(message); warned = true; } return fn.apply(this, arguments); } return deprecated; }; var deprecatedMessage = function deprecatedMessage(previousUsage, newUsage) { var githubAnchorLink = previousUsage.toLowerCase() .replace(/[\.\(\)]/g, ''); return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage + '`. Please see https://github.com/algolia/algoliasearch-client-javascript/wiki/Deprecated#' + githubAnchorLink; }; var merge$2 = function merge(destination/* , sources */) { var sources = Array.prototype.slice.call(arguments); foreach(sources, function(source) { for (var keyName in source) { if (source.hasOwnProperty(keyName)) { if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') { destination[keyName] = merge({}, destination[keyName], source[keyName]); } else if (source[keyName] !== undefined) { destination[keyName] = source[keyName]; } } } }); return destination; }; var clone = function clone(obj) { return JSON.parse(JSON.stringify(obj)); }; var toStr = Object.prototype.toString; var isArguments$2 = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; // modified from https://github.com/es-shims/es5-shim var has$1 = Object.prototype.hasOwnProperty; var toStr$1 = Object.prototype.toString; var slice = Array.prototype.slice; var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has$1.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr$1.call(object) === '[object Function]'; var isArguments = isArguments$2(object); var isString = isObject && toStr$1.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has$1.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has$1.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has$1.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArguments$2(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; var objectKeys = keysShim; var omit$2 = function omit(obj, test) { var keys = objectKeys; var foreach$$1 = foreach; var filtered = {}; foreach$$1(keys(obj), function doFilter(keyName) { if (test(keyName) !== true) { filtered[keyName] = obj[keyName]; } }); return filtered; }; var toString$3 = {}.toString; var isarray = Array.isArray || function (arr) { return toString$3.call(arr) == '[object Array]'; }; var map$2 = function map(arr, fn) { var newArr = []; foreach(arr, function(item, itemIndex) { newArr.push(fn(item, itemIndex, arr)); }); return newArr; }; var IndexCore_1 = IndexCore; /* * Index class constructor. * You should not use this method directly but use initIndex() function */ function IndexCore(algoliasearch, indexName) { this.indexName = indexName; this.as = algoliasearch; this.typeAheadArgs = null; this.typeAheadValueOption = null; // make sure every index instance has it's own cache this.cache = {}; } /* * Clear all queries in cache */ IndexCore.prototype.clearCache = function() { this.cache = {}; }; /* * Search inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the full text query * @param {object} [args] (optional) if set, contains an object with query parameters: * - page: (integer) Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, * to retrieve the 10th page you need to set page=9 * - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. * - attributesToRetrieve: a string that contains the list of object attributes * you want to retrieve (let you minimize the answer size). * Attributes are separated with a comma (for example "name,address"). * You can also use an array (for example ["name","address"]). * By default, all attributes are retrieved. You can also use '*' to retrieve all * values when an attributesToRetrieve setting is specified for your index. * - attributesToHighlight: a string that contains the list of attributes you * want to highlight according to the query. * Attributes are separated by a comma. You can also use an array (for example ["name","address"]). * If an attribute has no match for the query, the raw value is returned. * By default all indexed text attributes are highlighted. * You can use `*` if you want to highlight all textual attributes. * Numerical attributes are not highlighted. * A matchLevel is returned for each highlighted attribute and can contain: * - full: if all the query terms were found in the attribute, * - partial: if only some of the query terms were found, * - none: if none of the query terms were found. * - attributesToSnippet: a string that contains the list of attributes to snippet alongside * the number of words to return (syntax is `attributeName:nbWords`). * Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). * You can also use an array (Example: attributesToSnippet: ['name:10','content:10']). * By default no snippet is computed. * - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. * Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters in a query word * to accept two typos in this word. Defaults to 7. * - getRankingInfo: if set to 1, the result hits will contain ranking * information in _rankingInfo attribute. * - aroundLatLng: search for entries around a given * latitude/longitude (specified as two floats separated by a comma). * For example aroundLatLng=47.316669,5.016670). * You can specify the maximum distance in meters with the aroundRadius parameter (in meters) * and the precision for ranking with aroundPrecision * (for example if you set aroundPrecision=100, two objects that are distant of * less than 100m will be considered as identical for "geo" ranking parameter). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - insideBoundingBox: search entries inside a given area defined by the two extreme points * of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). * For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - numericFilters: a string that contains the list of numeric filters you want to * apply separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value`. * Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. * You can also use an array (for example numericFilters: ["price>100","price<1000"]). * - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. * To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). * You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]] * means tag1 AND (tag2 OR tag3). * At indexing, tags should be added in the _tags** attribute * of objects (for example {"_tags":["tag1","tag2"]}). * - facetFilters: filter the query by a list of facets. * Facets are separated by commas and each facet is encoded as `attributeName:value`. * For example: `facetFilters=category:Book,author:John%20Doe`. * You can also use an array (for example `["category:Book","author:John%20Doe"]`). * - facets: List of object attributes that you want to use for faceting. * Comma separated list: `"category,author"` or array `['category','author']` * Only attributes that have been added in **attributesForFaceting** index setting * can be used in this parameter. * You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. * - queryType: select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - optionalWords: a string that contains the list of words that should * be considered as optional when found in the query. * Comma separated and array are accepted. * - distinct: If set to 1, enable the distinct feature (disabled by default) * if the attributeForDistinct index setting is set. * This feature is similar to the SQL "distinct" keyword: when enabled * in a query with the distinct=1 parameter, * all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have * the same value for show_name, then only the best * one is kept and others are removed. * - restrictSearchableAttributes: List of attributes you want to use for * textual search (must be a subset of the attributesToIndex index setting) * either comma separated or as an array * @param {function} [callback] the result callback called with two arguments: * error: null or Error('message'). If false, the content contains the error. * content: the server answer that contains the list of results. */ IndexCore.prototype.search = buildSearchMethod_1('query'); /* * -- BETA -- * Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the similar query * @param {object} [args] (optional) if set, contains an object with query parameters. * All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters * are the two most useful to restrict the similar results and get more relevant content */ IndexCore.prototype.similarSearch = buildSearchMethod_1('similarQuery'); /* * Browse index content. The response content will have a `cursor` property that you can use * to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browse('cool songs', { * tagFilters: 'public,comments', * hitsPerPage: 500 * }, callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browse = function(query, queryParameters, callback) { var merge = merge$2; var indexObj = this; var page; var hitsPerPage; // we check variadic calls that are not the one defined // .browse()/.browse(fn) // => page = 0 if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') { page = 0; callback = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'number') { // .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn) page = arguments[0]; if (typeof arguments[1] === 'number') { hitsPerPage = arguments[1]; } else if (typeof arguments[1] === 'function') { callback = arguments[1]; hitsPerPage = undefined; } query = undefined; queryParameters = undefined; } else if (typeof arguments[0] === 'object') { // .browse(queryParameters)/.browse(queryParameters, cb) if (typeof arguments[1] === 'function') { callback = arguments[1]; } queryParameters = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') { // .browse(query, cb) callback = arguments[1]; queryParameters = undefined; } // otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb) // get search query parameters combining various possible calls // to .browse(); queryParameters = merge({}, queryParameters || {}, { page: page, hitsPerPage: hitsPerPage, query: query }); var params = this.as._getSearchParams(queryParameters, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse', body: {params: params}, hostType: 'read', callback: callback }); }; /* * Continue browsing from a previous position (cursor), obtained via a call to `.browse()`. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browseFrom('14lkfsakl32', callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browseFrom = function(cursor, callback) { return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse', body: {cursor: cursor}, hostType: 'read', callback: callback }); }; /* * Search for facet values * https://www.algolia.com/doc/rest-api/search#search-for-facet-values * * @param {string} params.facetName Facet name, name of the attribute to search for values in. * Must be declared as a facet * @param {string} params.facetQuery Query for the facet search * @param {string} [params.*] Any search parameter of Algolia, * see https://www.algolia.com/doc/api-client/javascript/search#search-parameters * Pagination is not supported. The page and hitsPerPage parameters will be ignored. * @param callback (optional) */ IndexCore.prototype.searchForFacetValues = function(params, callback) { var clone$$1 = clone; var omit = omit$2; var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])'; if (params.facetName === undefined || params.facetQuery === undefined) { throw new Error(usage); } var facetName = params.facetName; var filteredParams = omit(clone$$1(params), function(keyName) { return keyName === 'facetName'; }); var searchParameters = this.as._getSearchParams(filteredParams, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query', hostType: 'read', body: {params: searchParameters}, callback: callback }); }; IndexCore.prototype.searchFacet = deprecate(function(params, callback) { return this.searchForFacetValues(params, callback); }, deprecatedMessage( 'index.searchFacet(params[, callback])', 'index.searchForFacetValues(params[, callback])' )); IndexCore.prototype._search = function(params, url, callback, additionalUA) { return this.as._jsonRequest({ cache: this.cache, method: 'POST', url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: {params: params}, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName), body: {params: params} }, callback: callback, additionalUA: additionalUA }); }; /* * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param attrs (optional) if set, contains the array of attribute names to retrieve * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the object to retrieve or the error message if a failure occured */ IndexCore.prototype.getObject = function(objectID, attrs, callback) { var indexObj = this; if (arguments.length === 1 || typeof attrs === 'function') { callback = attrs; attrs = undefined; } var params = ''; if (attrs !== undefined) { params = '?attributes='; for (var i = 0; i < attrs.length; ++i) { if (i !== 0) { params += ','; } params += attrs[i]; } } return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params, hostType: 'read', callback: callback }); }; /* * Get several objects from this index * * @param objectIDs the array of unique identifier of objects to retrieve */ IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) { var isArray = isarray; var map = map$2; var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])'; if (!isArray(objectIDs)) { throw new Error(usage); } var indexObj = this; if (arguments.length === 1 || typeof attributesToRetrieve === 'function') { callback = attributesToRetrieve; attributesToRetrieve = undefined; } var body = { requests: map(objectIDs, function prepareRequest(objectID) { var request = { indexName: indexObj.indexName, objectID: objectID }; if (attributesToRetrieve) { request.attributesToRetrieve = attributesToRetrieve.join(','); } return request; }) }; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/*/objects', hostType: 'read', body: body, callback: callback }); }; IndexCore.prototype.as = null; IndexCore.prototype.indexName = null; IndexCore.prototype.typeAheadArgs = null; IndexCore.prototype.typeAheadValueOption = null; /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ var ms = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse$3(val); } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse$3(str) { str = String(str); if (str.length > 100) { return; } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd'; } if (ms >= h) { return Math.round(ms / h) + 'h'; } if (ms >= m) { return Math.round(ms / m) + 'm'; } if (ms >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return; } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name; } return Math.ceil(ms / n) + ' ' + name + 's'; } var debug = createCommonjsModule(function (module, exports) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = ms; /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms$$1 = curr - (prevTime || curr); self.diff = ms$$1; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } return debug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); exports.names = []; exports.skips = []; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } }); var debug_1 = debug.coerce; var debug_2 = debug.disable; var debug_3 = debug.enable; var debug_4 = debug.enabled; var debug_5 = debug.humanize; var debug_6 = debug.names; var debug_7 = debug.skips; var debug_8 = debug.formatters; var browser$1 = createCommonjsModule(function (module, exports) { /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { return true; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } }); var browser_1 = browser$1.log; var browser_2 = browser$1.formatArgs; var browser_3 = browser$1.save; var browser_4 = browser$1.load; var browser_5 = browser$1.useColors; var browser_6 = browser$1.storage; var browser_7 = browser$1.colors; var debug$2 = browser$1('algoliasearch:src/hostIndexState.js'); var localStorageNamespace = 'algoliasearch-client-js'; var store; var moduleStore = { state: {}, set: function(key, data) { this.state[key] = data; return this.state[key]; }, get: function(key) { return this.state[key] || null; } }; var localStorageStore = { set: function(key, data) { moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure try { var namespace = JSON.parse(commonjsGlobal.localStorage[localStorageNamespace]); namespace[key] = data; commonjsGlobal.localStorage[localStorageNamespace] = JSON.stringify(namespace); return namespace[key]; } catch (e) { return localStorageFailure(key, e); } }, get: function(key) { try { return JSON.parse(commonjsGlobal.localStorage[localStorageNamespace])[key] || null; } catch (e) { return localStorageFailure(key, e); } } }; function localStorageFailure(key, e) { debug$2('localStorage failed with', e); cleanup(); store = moduleStore; return store.get(key); } store = supportsLocalStorage() ? localStorageStore : moduleStore; var store_1 = { get: getOrSet, set: getOrSet, supportsLocalStorage: supportsLocalStorage }; function getOrSet(key, data) { if (arguments.length === 1) { return store.get(key); } return store.set(key, data); } function supportsLocalStorage() { try { if ('localStorage' in commonjsGlobal && commonjsGlobal.localStorage !== null) { if (!commonjsGlobal.localStorage[localStorageNamespace]) { // actual creation of the namespace commonjsGlobal.localStorage.setItem(localStorageNamespace, JSON.stringify({})); } return true; } return false; } catch (_) { return false; } } // In case of any error on localStorage, we clean our own namespace, this should handle // quota errors when a lot of keys + data are used function cleanup() { try { commonjsGlobal.localStorage.removeItem(localStorageNamespace); } catch (_) { // nothing to do } } var AlgoliaSearchCore_1 = AlgoliaSearchCore; // We will always put the API KEY in the JSON body in case of too long API KEY, // to avoid query string being too long and failing in various conditions (our server limit, browser limit, // proxies limit) var MAX_API_KEY_LENGTH = 500; var RESET_APP_DATA_TIMER = process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) || 60 * 2 * 1000; // after 2 minutes reset to first host /* * Algolia Search library initialization * https://www.algolia.com/ * * @param {string} applicationID - Your applicationID, found in your dashboard * @param {string} apiKey - Your API key, found in your dashboard * @param {Object} [opts] * @param {number} [opts.timeout=2000] - The request timeout set in milliseconds, * another request will be issued after this timeout * @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API. * Set to 'https:' to force using https. * Default to document.location.protocol in browsers * @param {Object|Array} [opts.hosts={ * read: [this.applicationID + '-dsn.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]), * write: [this.applicationID + '.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]) - The hosts to use for Algolia Search API. * If you provide them, you will less benefit from our HA implementation */ function AlgoliaSearchCore(applicationID, apiKey, opts) { var debug = browser$1('algoliasearch'); var clone$$1 = clone; var isArray = isarray; var map = map$2; var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)'; if (opts._allowEmptyCredentials !== true && !applicationID) { throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage); } if (opts._allowEmptyCredentials !== true && !apiKey) { throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage); } this.applicationID = applicationID; this.apiKey = apiKey; this.hosts = { read: [], write: [] }; opts = opts || {}; var protocol = opts.protocol || 'https:'; this._timeouts = opts.timeouts || { connect: 1 * 1000, // 500ms connect is GPRS latency read: 2 * 1000, write: 30 * 1000 }; // backward compat, if opts.timeout is passed, we use it to configure all timeouts like before if (opts.timeout) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout; } // while we advocate for colon-at-the-end values: 'http:' for `opts.protocol` // we also accept `http` and `https`. It's a common error. if (!/:$/.test(protocol)) { protocol = protocol + ':'; } if (opts.protocol !== 'http:' && opts.protocol !== 'https:') { throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)'); } this._checkAppIdData(); if (!opts.hosts) { var defaultHosts = map(this._shuffleResult, function(hostNumber) { return applicationID + '-' + hostNumber + '.algolianet.com'; }); // no hosts given, compute defaults this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts); this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts); } else if (isArray(opts.hosts)) { // when passing custom hosts, we need to have a different host index if the number // of write/read hosts are different. this.hosts.read = clone$$1(opts.hosts); this.hosts.write = clone$$1(opts.hosts); } else { this.hosts.read = clone$$1(opts.hosts.read); this.hosts.write = clone$$1(opts.hosts.write); } // add protocol and lowercase hosts this.hosts.read = map(this.hosts.read, prepareHost(protocol)); this.hosts.write = map(this.hosts.write, prepareHost(protocol)); this.extraHeaders = {}; // In some situations you might want to warm the cache this.cache = opts._cache || {}; this._ua = opts._ua; this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache; this._useFallback = opts.useFallback === undefined ? true : opts.useFallback; this._setTimeout = opts._setTimeout; debug('init done, %j', this); } /* * Get the index object initialized * * @param indexName the name of index * @param callback the result callback with one argument (the Index instance) */ AlgoliaSearchCore.prototype.initIndex = function(indexName) { return new IndexCore_1(this, indexName); }; /** * Add an extra field to the HTTP request * * @param name the header field name * @param value the header field value */ AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) { this.extraHeaders[name.toLowerCase()] = value; }; /** * Get the value of an extra HTTP header * * @param name the header field name */ AlgoliaSearchCore.prototype.getExtraHeader = function(name) { return this.extraHeaders[name.toLowerCase()]; }; /** * Remove an extra field from the HTTP request * * @param name the header field name */ AlgoliaSearchCore.prototype.unsetExtraHeader = function(name) { delete this.extraHeaders[name.toLowerCase()]; }; /** * Augment sent x-algolia-agent with more data, each agent part * is automatically separated from the others by a semicolon; * * @param algoliaAgent the agent to add */ AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) { if (this._ua.indexOf(';' + algoliaAgent) === -1) { this._ua += ';' + algoliaAgent; } }; /* * Wrapper that try all hosts to maximize the quality of service */ AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) { this._checkAppIdData(); var requestDebug = browser$1('algoliasearch:' + initialOpts.url); var body; var additionalUA = initialOpts.additionalUA || ''; var cache = initialOpts.cache; var client = this; var tries = 0; var usingFallback = false; var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback; var headers; if ( this.apiKey.length > MAX_API_KEY_LENGTH && initialOpts.body !== undefined && (initialOpts.body.params !== undefined || // index.search() initialOpts.body.requests !== undefined) // client.search() ) { initialOpts.body.apiKey = this.apiKey; headers = this._computeRequestHeaders(additionalUA, false); } else { headers = this._computeRequestHeaders(additionalUA); } if (initialOpts.body !== undefined) { body = safeJSONStringify(initialOpts.body); } requestDebug('request start'); var debugData = []; function doRequest(requester, reqOpts) { client._checkAppIdData(); var startTime = new Date(); var cacheID; if (client._useCache) { cacheID = initialOpts.url; } // as we sometime use POST requests to pass parameters (like query='aa'), // the cacheID must also include the body to be different between calls if (client._useCache && body) { cacheID += '_body_' + reqOpts.body; } // handle cache existence if (client._useCache && cache && cache[cacheID] !== undefined) { requestDebug('serving response from cache'); return client._promise.resolve(JSON.parse(cache[cacheID])); } // if we reached max tries if (tries >= client.hosts[initialOpts.hostType].length) { if (!hasFallback || usingFallback) { requestDebug('could not get any response'); // then stop return client._promise.reject(new errors.AlgoliaSearchError( 'Cannot connect to the AlgoliaSearch API.' + ' Send an email to [email protected] to report and resolve the issue.' + ' Application id was: ' + client.applicationID, {debugData: debugData} )); } requestDebug('switching to fallback'); // let's try the fallback starting from here tries = 0; // method, url and body are fallback dependent reqOpts.method = initialOpts.fallback.method; reqOpts.url = initialOpts.fallback.url; reqOpts.jsonBody = initialOpts.fallback.body; if (reqOpts.jsonBody) { reqOpts.body = safeJSONStringify(reqOpts.jsonBody); } // re-compute headers, they could be omitting the API KEY headers = client._computeRequestHeaders(additionalUA); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); client._setHostIndexByType(0, initialOpts.hostType); usingFallback = true; // the current request is now using fallback return doRequest(client._request.fallback, reqOpts); } var currentHost = client._getHostByType(initialOpts.hostType); var url = currentHost + reqOpts.url; var options = { body: reqOpts.body, jsonBody: reqOpts.jsonBody, method: reqOpts.method, headers: headers, timeouts: reqOpts.timeouts, debug: requestDebug }; requestDebug('method: %s, url: %s, headers: %j, timeouts: %d', options.method, url, options.headers, options.timeouts); if (requester === client._request.fallback) { requestDebug('using fallback'); } // `requester` is any of this._request or this._request.fallback // thus it needs to be called using the client as context return requester.call(client, url, options).then(success, tryFallback); function success(httpResponse) { // compute the status of the response, // // When in browser mode, using XDR or JSONP, we have no statusCode available // So we rely on our API response `status` property. // But `waitTask` can set a `status` property which is not the statusCode (it's the task status) // So we check if there's a `message` along `status` and it means it's an error // // That's the only case where we have a response.status that's not the http statusCode var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status || // this is important to check the request statusCode AFTER the body eventual // statusCode because some implementations (jQuery XDomainRequest transport) may // send statusCode 200 while we had an error httpResponse.statusCode || // When in browser mode, using XDR or JSONP // we default to success when no error (no response.status && response.message) // If there was a JSON.parse() error then body is null and it fails httpResponse && httpResponse.body && 200; requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j', httpResponse.statusCode, status, httpResponse.headers); var httpResponseOk = Math.floor(status / 100) === 2; var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime, statusCode: status }); if (httpResponseOk) { if (client._useCache && cache) { cache[cacheID] = httpResponse.responseText; } return httpResponse.body; } var shouldRetry = Math.floor(status / 100) !== 4; if (shouldRetry) { tries += 1; return retryRequest(); } requestDebug('unrecoverable error'); // no success and no retry => fail var unrecoverableError = new errors.AlgoliaSearchError( httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status} ); return client._promise.reject(unrecoverableError); } function tryFallback(err) { // error cases: // While not in fallback mode: // - CORS not supported // - network error // While in fallback mode: // - timeout // - network error // - badly formatted JSONP (script loaded, did not call our callback) // In both cases: // - uncaught exception occurs (TypeError) requestDebug('error: %s, stack: %s', err.message, err.stack); var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime }); if (!(err instanceof errors.AlgoliaSearchError)) { err = new errors.Unknown(err && err.message, err); } tries += 1; // stop the request implementation when: if ( // we did not generate this error, // it comes from a throw in some other piece of code err instanceof errors.Unknown || // server sent unparsable JSON err instanceof errors.UnparsableJSON || // max tries and already using fallback or no fallback tries >= client.hosts[initialOpts.hostType].length && (usingFallback || !hasFallback)) { // stop request implementation for this command err.debugData = debugData; return client._promise.reject(err); } // When a timeout occured, retry by raising timeout if (err instanceof errors.RequestTimeout) { return retryRequestWithHigherTimeout(); } return retryRequest(); } function retryRequest() { requestDebug('retrying request'); client._incrementHostIndex(initialOpts.hostType); return doRequest(requester, reqOpts); } function retryRequestWithHigherTimeout() { requestDebug('retrying request with higher timeout'); client._incrementHostIndex(initialOpts.hostType); client._incrementTimeoutMultipler(); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); return doRequest(requester, reqOpts); } } var promise = doRequest( client._request, { url: initialOpts.url, method: initialOpts.method, body: body, jsonBody: initialOpts.body, timeouts: client._getTimeoutsForRequest(initialOpts.hostType) } ); // either we have a callback // either we are using promises if (typeof initialOpts.callback === 'function') { promise.then(function okCb(content) { exitPromise(function() { initialOpts.callback(null, content); }, client._setTimeout || setTimeout); }, function nookCb(err) { exitPromise(function() { initialOpts.callback(err); }, client._setTimeout || setTimeout); }); } else { return promise; } }; /* * Transform search param object in query string * @param {object} args arguments to add to the current query string * @param {string} params current query string * @return {string} the final query string */ AlgoliaSearchCore.prototype._getSearchParams = function(args, params) { if (args === undefined || args === null) { return params; } for (var key in args) { if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) { params += params === '' ? '' : '&'; params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]); } } return params; }; AlgoliaSearchCore.prototype._computeRequestHeaders = function(additionalUA, withAPIKey) { var forEach = foreach; var ua = additionalUA ? this._ua + ';' + additionalUA : this._ua; var requestHeaders = { 'x-algolia-agent': ua, 'x-algolia-application-id': this.applicationID }; // browser will inline headers in the url, node.js will use http headers // but in some situations, the API KEY will be too long (big secured API keys) // so if the request is a POST and the KEY is very long, we will be asked to not put // it into headers but in the JSON body if (withAPIKey !== false) { requestHeaders['x-algolia-api-key'] = this.apiKey; } if (this.userToken) { requestHeaders['x-algolia-usertoken'] = this.userToken; } if (this.securityTags) { requestHeaders['x-algolia-tagfilters'] = this.securityTags; } forEach(this.extraHeaders, function addToRequestHeaders(value, key) { requestHeaders[key] = value; }); return requestHeaders; }; /** * Search through multiple indices at the same time * @param {Object[]} queries An array of queries you want to run. * @param {string} queries[].indexName The index name you want to target * @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params` * @param {Object} queries[].params Any search param like hitsPerPage, .. * @param {Function} callback Callback to be called * @return {Promise|undefined} Returns a promise if no callback given */ AlgoliaSearchCore.prototype.search = function(queries, opts, callback) { var isArray = isarray; var map = map$2; var usage = 'Usage: client.search(arrayOfQueries[, callback])'; if (!isArray(queries)) { throw new Error(usage); } if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } var client = this; var postObj = { requests: map(queries, function prepareRequest(query) { var params = ''; // allow query.query // so we are mimicing the index.search(query, params) method // {indexName:, query:, params:} if (query.query !== undefined) { params += 'query=' + encodeURIComponent(query.query); } return { indexName: query.indexName, params: client._getSearchParams(query.params, params) }; }) }; var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) { return requestId + '=' + encodeURIComponent( '/1/indexes/' + encodeURIComponent(request.indexName) + '?' + request.params ); }).join('&'); var url = '/1/indexes/*/queries'; if (opts.strategy !== undefined) { url += '?strategy=' + opts.strategy; } return this._jsonRequest({ cache: this.cache, method: 'POST', url: url, body: postObj, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/*', body: { params: JSONPParams } }, callback: callback }); }; /** * Set the extra security tagFilters header * @param {string|array} tags The list of tags defining the current security filters */ AlgoliaSearchCore.prototype.setSecurityTags = function(tags) { if (Object.prototype.toString.call(tags) === '[object Array]') { var strTags = []; for (var i = 0; i < tags.length; ++i) { if (Object.prototype.toString.call(tags[i]) === '[object Array]') { var oredTags = []; for (var j = 0; j < tags[i].length; ++j) { oredTags.push(tags[i][j]); } strTags.push('(' + oredTags.join(',') + ')'); } else { strTags.push(tags[i]); } } tags = strTags.join(','); } this.securityTags = tags; }; /** * Set the extra user token header * @param {string} userToken The token identifying a uniq user (used to apply rate limits) */ AlgoliaSearchCore.prototype.setUserToken = function(userToken) { this.userToken = userToken; }; /** * Clear all queries in client's cache * @return undefined */ AlgoliaSearchCore.prototype.clearCache = function() { this.cache = {}; }; /** * Set the number of milliseconds a request can take before automatically being terminated. * @deprecated * @param {Number} milliseconds */ AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) { if (milliseconds) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds; } }; /** * Set the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) { this._timeouts = timeouts; }; /** * Get the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.getTimeouts = function() { return this._timeouts; }; AlgoliaSearchCore.prototype._getAppIdData = function() { var data = store_1.get(this.applicationID); if (data !== null) this._cacheAppIdData(data); return data; }; AlgoliaSearchCore.prototype._setAppIdData = function(data) { data.lastChange = (new Date()).getTime(); this._cacheAppIdData(data); return store_1.set(this.applicationID, data); }; AlgoliaSearchCore.prototype._checkAppIdData = function() { var data = this._getAppIdData(); var now = (new Date()).getTime(); if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) { return this._resetInitialAppIdData(data); } return data; }; AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) { var newData = data || {}; newData.hostIndexes = {read: 0, write: 0}; newData.timeoutMultiplier = 1; newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]); return this._setAppIdData(newData); }; AlgoliaSearchCore.prototype._cacheAppIdData = function(data) { this._hostIndexes = data.hostIndexes; this._timeoutMultiplier = data.timeoutMultiplier; this._shuffleResult = data.shuffleResult; }; AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) { var foreach$$1 = foreach; var currentData = this._getAppIdData(); foreach$$1(newData, function(value, key) { currentData[key] = value; }); return this._setAppIdData(currentData); }; AlgoliaSearchCore.prototype._getHostByType = function(hostType) { return this.hosts[hostType][this._getHostIndexByType(hostType)]; }; AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() { return this._timeoutMultiplier; }; AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) { return this._hostIndexes[hostType]; }; AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) { var clone$$1 = clone; var newHostIndexes = clone$$1(this._hostIndexes); newHostIndexes[hostType] = hostIndex; this._partialAppIdDataUpdate({hostIndexes: newHostIndexes}); return hostIndex; }; AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) { return this._setHostIndexByType( (this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType ); }; AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() { var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4); return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier}); }; AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) { return { connect: this._timeouts.connect * this._timeoutMultiplier, complete: this._timeouts[hostType] * this._timeoutMultiplier }; }; function prepareHost(protocol) { return function prepare(host) { return protocol + '//' + host.toLowerCase(); }; } // Prototype.js < 1.7, a widely used library, defines a weird // Array.prototype.toJSON function that will fail to stringify our content // appropriately // refs: // - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q // - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c // - http://stackoverflow.com/a/3148441/147079 function safeJSONStringify(obj) { /* eslint no-extend-native:0 */ if (Array.prototype.toJSON === undefined) { return JSON.stringify(obj); } var toJSON = Array.prototype.toJSON; delete Array.prototype.toJSON; var out = JSON.stringify(obj); Array.prototype.toJSON = toJSON; return out; } function shuffle(array) { var currentIndex = array.length; var temporaryValue; var randomIndex; // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } function removeCredentials(headers) { var newHeaders = {}; for (var headerName in headers) { if (Object.prototype.hasOwnProperty.call(headers, headerName)) { var value; if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') { value = '**hidden for security purposes**'; } else { value = headers[headerName]; } newHeaders[headerName] = value; } } return newHeaders; } var win; if (typeof window !== "undefined") { win = window; } else if (typeof commonjsGlobal !== "undefined") { win = commonjsGlobal; } else if (typeof self !== "undefined"){ win = self; } else { win = {}; } var window_1 = win; var es6Promise = createCommonjsModule(function (module, exports) { /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version 4.1.1 */ (function (global, factory) { module.exports = factory(); }(commonjsGlobal, (function () { function objectOrFunction(x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); } function isFunction(x) { return typeof x === 'function'; } var _isArray = undefined; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } var isArray = _isArray; var len = 0; var vertxNext = undefined; var customSchedulerFn = undefined; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (customSchedulerFn) { customSchedulerFn(flush); } else { scheduleFlush(); } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn; } function setAsap(asapFn) { asap = asapFn; } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return nextTick(flush); }; } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { return function () { vertxNext(flush); }; } return useSetTimeout(); } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { // Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout = setTimeout; return function () { return globalSetTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertx() { try { var r = commonjsRequire; var vertx = r('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = undefined; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && typeof commonjsRequire === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var _arguments = arguments; var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { (function () { var callback = _arguments[_state - 1]; asap(function () { return invokeCallback(_state, child, callback, parent._result); }); })(); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; } /** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve$1(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop); resolve(promise, object); return promise; } var PROMISE_ID = Math.random().toString(36).substring(16); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var GET_THEN_ERROR = new ErrorObject(); function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function getThen(promise) { try { return promise.then; } catch (error) { GET_THEN_ERROR.error = error; return GET_THEN_ERROR; } } function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { try { then$$1.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then$$1) { asap(function (promise) { var sealed = false; var error = tryThen(then$$1, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return resolve(promise, value); }, function (reason) { return reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$1) { if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { handleOwnThenable(promise, maybeThenable); } else { if (then$$1 === GET_THEN_ERROR) { reject(promise, GET_THEN_ERROR.error); GET_THEN_ERROR.error = null; } else if (then$$1 === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$1)) { handleForeignThenable(promise, maybeThenable, then$$1); } else { fulfill(promise, maybeThenable); } } } function resolve(promise, value) { if (promise === value) { reject(promise, selfFulfillment()); } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(value)); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = undefined, callback = undefined, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function ErrorObject() { this.error = null; } var TRY_CATCH_ERROR = new ErrorObject(); function tryCatch(callback, detail) { try { return callback(detail); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = undefined, error = undefined, succeeded = undefined, failed = undefined; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value.error = null; } else { succeeded = true; } if (promise === value) { reject(promise, cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { resolve(promise, value); }, function rejectPromise(reason) { reject(promise, reason); }); } catch (e) { reject(promise, e); } } var id = 0; function nextId() { return id++; } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function Enumerator$1(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(input)) { this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(input); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { reject(this.promise, validationError()); } } function validationError() { return new Error('Array Methods must be provided an Array'); } Enumerator$1.prototype._enumerate = function (input) { for (var i = 0; this._state === PENDING && i < input.length; i++) { this._eachEntry(input[i], i); } }; Enumerator$1.prototype._eachEntry = function (entry, i) { var c = this._instanceConstructor; var resolve$$1 = c.resolve; if (resolve$$1 === resolve$1) { var _then = getThen(entry); if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === Promise$2) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$1) { return resolve$$1(entry); }), i); } } else { this._willSettleAt(resolve$$1(entry), i); } }; Enumerator$1.prototype._settledAt = function (state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; Enumerator$1.prototype._willSettleAt = function (promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all$1(entries) { return new Enumerator$1(this, entries).promise; } /** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race$1(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject$1(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop); reject(promise, reason); return promise; } function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function Promise$2(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew(); } } Promise$2.all = all$1; Promise$2.race = race$1; Promise$2.resolve = resolve$1; Promise$2.reject = reject$1; Promise$2._setScheduler = setScheduler; Promise$2._setAsap = setAsap; Promise$2._asap = asap; Promise$2.prototype = { constructor: Promise$2, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: then, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function _catch(onRejection) { return this.then(null, onRejection); } }; /*global self*/ function polyfill$1() { var local = undefined; if (typeof commonjsGlobal !== 'undefined') { local = commonjsGlobal; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); } catch (e) { // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise$2; } // Strange compat.. Promise$2.polyfill = polyfill$1; Promise$2.Promise = Promise$2; return Promise$2; }))); }); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; var encode$1 = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map$4(objectKeys$2(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray$2(obj[k])) { return map$4(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray$2 = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map$4 (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys$2 = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; var inlineHeaders_1 = inlineHeaders; function inlineHeaders(url, headers) { if (/\?/.test(url)) { url += '&'; } else { url += '?'; } return url + encode$1(headers); } var jsonpRequest_1 = jsonpRequest; var JSONPCounter = 0; function jsonpRequest(url, opts, cb) { if (opts.method !== 'GET') { cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.')); return; } opts.debug('JSONP: start'); var cbCalled = false; var timedOut = false; JSONPCounter += 1; var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); var cbName = 'algoliaJSONP_' + JSONPCounter; var done = false; window[cbName] = function(data) { removeGlobals(); if (timedOut) { opts.debug('JSONP: Late answer, ignoring'); return; } cbCalled = true; clean(); cb(null, { body: data/* , // We do not send the statusCode, there's no statusCode in JSONP, it will be // computed using data.status && data.message like with XDR statusCode*/ }); }; // add callback by hand url += '&callback=' + cbName; // add body params manually if (opts.jsonBody && opts.jsonBody.params) { url += '&' + opts.jsonBody.params; } var ontimeout = setTimeout(timeout, opts.timeouts.complete); // script onreadystatechange needed only for // <= IE8 // https://github.com/angular/angular.js/issues/4523 script.onreadystatechange = readystatechange; script.onload = success; script.onerror = error; script.async = true; script.defer = true; script.src = url; head.appendChild(script); function success() { opts.debug('JSONP: success'); if (done || timedOut) { return; } done = true; // script loaded but did not call the fn => script loading error if (!cbCalled) { opts.debug('JSONP: Fail. Script loaded but did not call the callback'); clean(); cb(new errors.JSONPScriptFail()); } } function readystatechange() { if (this.readyState === 'loaded' || this.readyState === 'complete') { success(); } } function clean() { clearTimeout(ontimeout); script.onload = null; script.onreadystatechange = null; script.onerror = null; head.removeChild(script); } function removeGlobals() { try { delete window[cbName]; delete window[cbName + '_loaded']; } catch (e) { window[cbName] = window[cbName + '_loaded'] = undefined; } } function timeout() { opts.debug('JSONP: Script timeout'); timedOut = true; clean(); cb(new errors.RequestTimeout()); } function error() { opts.debug('JSONP: Script error'); if (done || timedOut) { return; } clean(); cb(new errors.JSONPScriptError()); } } var places = createPlacesClient; function createPlacesClient(algoliasearch) { return function places(appID, apiKey, opts) { var cloneDeep = clone; opts = opts && cloneDeep(opts) || {}; opts.hosts = opts.hosts || [ 'places-dsn.algolia.net', 'places-1.algolianet.com', 'places-2.algolianet.com', 'places-3.algolianet.com' ]; // allow initPlaces() no arguments => community rate limited if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) { appID = ''; apiKey = ''; opts._allowEmptyCredentials = true; } var client = algoliasearch(appID, apiKey, opts); var index = client.initIndex('places'); index.search = buildSearchMethod_1('query', '/1/places/query'); index.getObject = function(objectID, callback) { return this.as._jsonRequest({ method: 'GET', url: '/1/places/' + encodeURIComponent(objectID), hostType: 'read', callback: callback }); }; return index; }; } var getDocumentProtocol_1 = getDocumentProtocol; function getDocumentProtocol() { var protocol = window.document.location.protocol; // when in `file:` mode (local html file), default to `http:` if (protocol !== 'http:' && protocol !== 'https:') { protocol = 'http:'; } return protocol; } var version$5 = '3.24.5'; var Promise$3 = window_1.Promise || es6Promise.Promise; // This is the standalone browser build entry point // Browser implementation of the Algolia Search JavaScript client, // using XMLHttpRequest, XDomainRequest and JSONP as fallback var createAlgoliasearch = function createAlgoliasearch(AlgoliaSearch, uaSuffix) { var inherits = inherits_browser$2; var errors$$1 = errors; var inlineHeaders = inlineHeaders_1; var jsonpRequest = jsonpRequest_1; var places$$1 = places; uaSuffix = uaSuffix || ''; function algoliasearch(applicationID, apiKey, opts) { var cloneDeep = clone; var getDocumentProtocol = getDocumentProtocol_1; opts = cloneDeep(opts || {}); if (opts.protocol === undefined) { opts.protocol = getDocumentProtocol(); } opts._ua = opts._ua || algoliasearch.ua; return new AlgoliaSearchBrowser(applicationID, apiKey, opts); } algoliasearch.version = version$5; algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version; algoliasearch.initPlaces = places$$1(algoliasearch); // we expose into window no matter how we are used, this will allow // us to easily debug any website running algolia window_1.__algolia = { debug: browser$1, algoliasearch: algoliasearch }; var support = { hasXMLHttpRequest: 'XMLHttpRequest' in window_1, hasXDomainRequest: 'XDomainRequest' in window_1 }; if (support.hasXMLHttpRequest) { support.cors = 'withCredentials' in new XMLHttpRequest(); } function AlgoliaSearchBrowser() { // call AlgoliaSearch constructor AlgoliaSearch.apply(this, arguments); } inherits(AlgoliaSearchBrowser, AlgoliaSearch); AlgoliaSearchBrowser.prototype._request = function request(url, opts) { return new Promise$3(function wrapRequest(resolve, reject) { // no cors or XDomainRequest, no request if (!support.cors && !support.hasXDomainRequest) { // very old browser, not supported reject(new errors$$1.Network('CORS not supported')); return; } url = inlineHeaders(url, opts.headers); var body = opts.body; var req = support.cors ? new XMLHttpRequest() : new XDomainRequest(); var reqTimeout; var timedOut; var connected = false; reqTimeout = setTimeout(onTimeout, opts.timeouts.connect); // we set an empty onprogress listener // so that XDomainRequest on IE9 is not aborted // refs: // - https://github.com/algolia/algoliasearch-client-js/issues/76 // - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment req.onprogress = onProgress; if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange; req.onload = onLoad; req.onerror = onError; // do not rely on default XHR async flag, as some analytics code like hotjar // breaks it and set it to false by default if (req instanceof XMLHttpRequest) { req.open(opts.method, url, true); } else { req.open(opts.method, url); } // headers are meant to be sent after open if (support.cors) { if (body) { if (opts.method === 'POST') { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests req.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); } else { req.setRequestHeader('content-type', 'application/json'); } } req.setRequestHeader('accept', 'application/json'); } req.send(body); // event object not received in IE8, at least // but we do not use it, still important to note function onLoad(/* event */) { // When browser does not supports req.timeout, we can // have both a load and timeout event, since handled by a dumb setTimeout if (timedOut) { return; } clearTimeout(reqTimeout); var out; try { out = { body: JSON.parse(req.responseText), responseText: req.responseText, statusCode: req.status, // XDomainRequest does not have any response headers headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {} }; } catch (e) { out = new errors$$1.UnparsableJSON({ more: req.responseText }); } if (out instanceof errors$$1.UnparsableJSON) { reject(out); } else { resolve(out); } } function onError(event) { if (timedOut) { return; } clearTimeout(reqTimeout); // error event is trigerred both with XDR/XHR on: // - DNS error // - unallowed cross domain request reject( new errors$$1.Network({ more: event }) ); } function onTimeout() { timedOut = true; req.abort(); reject(new errors$$1.RequestTimeout()); } function onConnect() { connected = true; clearTimeout(reqTimeout); reqTimeout = setTimeout(onTimeout, opts.timeouts.complete); } function onProgress() { if (!connected) onConnect(); } function onReadyStateChange() { if (!connected && req.readyState > 1) onConnect(); } }); }; AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) { url = inlineHeaders(url, opts.headers); return new Promise$3(function wrapJsonpRequest(resolve, reject) { jsonpRequest(url, opts, function jsonpRequestDone(err, content) { if (err) { reject(err); return; } resolve(content); }); }); }; AlgoliaSearchBrowser.prototype._promise = { reject: function rejectPromise(val) { return Promise$3.reject(val); }, resolve: function resolvePromise(val) { return Promise$3.resolve(val); }, delay: function delayPromise(ms) { return new Promise$3(function resolveOnTimeout(resolve/* , reject*/) { setTimeout(resolve, ms); }); } }; return algoliasearch; }; var algoliasearchLite = createAlgoliasearch(AlgoliaSearchCore_1, '(lite) '); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE$1 = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = _arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = _arrayMap(values, _baseUnary(iteratee)); } if (comparator) { includes = _arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE$1) { includes = _cacheHas; isCommon = false; values = new _SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } var _baseDifference = baseDifference; /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = _baseRest(function(array, values) { return isArrayLikeObject_1(array) ? _baseDifference(array, _baseFlatten(values, 1, isArrayLikeObject_1, true)) : []; }); var difference_1 = difference; /** Used for built-in method references. */ var objectProto$20 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$18 = objectProto$20.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty$18.call(object, key); } var _baseHas = baseHas; /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has$2(object, path) { return object != null && _hasPath(object, path, _baseHas); } var has_1 = has$2; /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = has_1(connectorDesc, 'refine'); var hasSearchForFacetValues = has_1(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = has_1(connectorDesc, 'getSearchParameters'); var hasMetadata = has_1(connectorDesc, 'getMetadata'); var hasTransitionState = has_1(connectorDesc, 'transitionState'); var hasCleanUp = has_1(connectorDesc, 'cleanUp'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp, _initialiseProps; return _temp = _class = function (_Component) { inherits(Connector, _Component); function Connector(props, context) { classCallCheck(this, Connector); var _this = possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context)); _initialiseProps.call(_this); var _context$ais = context.ais, store = _context$ais.store, widgetsManager = _context$ais.widgetsManager; var canRender = false; _this.state = { props: _this.getProvidedProps(_extends({}, props, { canRender: canRender })), canRender: canRender // use to know if a component is rendered (browser), or not (server). }; _this.unsubscribe = store.subscribe(function () { if (_this.state.canRender) { _this.setState({ props: _this.getProvidedProps(_extends({}, _this.props, { canRender: _this.state.canRender })) }); } }); if (isWidget) { _this.unregisterWidget = widgetsManager.registerWidget(_this); } return _this; } createClass(Connector, [{ key: 'getMetadata', value: function getMetadata(nextWidgetsState) { if (hasMetadata) { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters) { if (hasSearchParameters) { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.context.ais.store.getState().widgets); } return null; } }, { key: 'transitionState', value: function transitionState(prevWidgetsState, nextWidgetsState) { if (hasTransitionState) { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { key: 'componentDidMount', value: function componentDidMount() { this.setState({ canRender: true }); } }, { key: 'componentWillMount', value: function componentWillMount() { if (connectorDesc.getSearchParameters) { this.context.ais.onSearchParameters(connectorDesc.getSearchParameters, this.context, this.props); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (!isEqual_1(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(nextProps) }); if (isWidget) { // Since props might have changed, we need to re-run getSearchParameters // and getMetadata with the new props. this.context.ais.widgetsManager.update(); if (connectorDesc.transitionState) { this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets)); } } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unsubscribe(); if (isWidget) { this.unregisterWidget(); // will schedule an update if (hasCleanUp) { var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), { widgets: newState })); this.context.ais.onSearchStateChange(removeEmptyKey(newState)); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var propsEqual = shallowEqual(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !shallowEqual(this.state.props, nextState.props); } }, { key: 'render', value: function render() { var _this2 = this; if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues, searchForFacetValues: function searchForFacetValues() { _this2.searchForFacetValues.apply(_this2, arguments); } } : {}; return React__default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component), _class.displayName = connectorDesc.displayName + '(' + getDisplayName(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = { // @TODO: more precise state manager propType ais: propTypes.object.isRequired, multiIndexContext: propTypes.object }, _initialiseProps = function _initialiseProps() { var _this3 = this; this.getProvidedProps = function (props) { var store = _this3.context.ais.store; var _store$getState = store.getState(), results = _store$getState.results, searching = _store$getState.searching, error = _store$getState.error, widgets = _store$getState.widgets, metadata = _store$getState.metadata, resultsFacetValues = _store$getState.resultsFacetValues, searchingForFacetValues = _store$getState.searchingForFacetValues, isSearchStalled = _store$getState.isSearchStalled; var searchResults = { results: results, searching: searching, error: error, searchingForFacetValues: searchingForFacetValues, isSearchStalled: isSearchStalled }; return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchResults, metadata, resultsFacetValues); }; this.refine = function () { var _connectorDesc$refine; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this3.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.searchForFacetValues = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this3.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.createURL = function () { var _connectorDesc$refine2; for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this3.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.cleanUp = function () { var _connectorDesc$cleanU; for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this3].concat(args)); }; }, _temp; }; } function getIndex(context) { return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (searchResults.results && !searchResults.results.hits) { return searchResults.results[getIndex(context)] ? searchResults.results[getIndex(context)] : null; } else { return searchResults.results ? searchResults.results : null; } } function hasMultipleIndex(context) { return context && context.multiIndexContext; } // eslint-disable-next-line max-params function refineValue(searchState, nextRefinement, context, resetPage, namespace) { if (hasMultipleIndex(context)) { return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage); } else { // When we have a multi index page with shared widgets we should also // reset their page to 1 if the resetPage is provided. Otherwise the // indices will always be reset // see: https://github.com/algolia/react-instantsearch/issues/310 // see: https://github.com/algolia/react-instantsearch/issues/637 if (searchState.indices && resetPage) { Object.keys(searchState.indices).forEach(function (targetedIndex) { searchState = refineValue(searchState, { page: 1 }, { multiIndexContext: { targetedIndex: targetedIndex } }, true, namespace); }); } return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage); } } function refineMultiIndex(searchState, nextRefinement, context, resetPage) { var page = resetPage ? { page: 1 } : undefined; var index = getIndex(context); var state = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], nextRefinement, page))) : _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, nextRefinement, page))); return _extends({}, searchState, { indices: state }); } function refineSingleIndex(searchState, nextRefinement, resetPage) { var page = resetPage ? { page: 1 } : undefined; return _extends({}, searchState, nextRefinement, page); } // eslint-disable-next-line max-params function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) { var _babelHelpers$extends3; var index = getIndex(context); var page = resetPage ? { page: 1 } : undefined; var state = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], (_babelHelpers$extends3 = {}, defineProperty$2(_babelHelpers$extends3, namespace, _extends({}, searchState.indices[index][namespace], nextRefinement)), defineProperty$2(_babelHelpers$extends3, 'page', 1), _babelHelpers$extends3)))) : _extends({}, searchState.indices, defineProperty$2({}, index, _extends(defineProperty$2({}, namespace, nextRefinement), page))); return _extends({}, searchState, { indices: state }); } function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) { var page = resetPage ? { page: 1 } : undefined; return _extends({}, searchState, defineProperty$2({}, namespace, _extends({}, searchState[namespace], nextRefinement)), page); } function getNamespaceAndAttributeName(id) { var parts = id.match(/^([^.]*)\.(.*)/); var namespace = parts && parts[1]; var attributeName = parts && parts[2]; return { namespace: namespace, attributeName: attributeName }; } // eslint-disable-next-line max-params function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) { var index = getIndex(context); var _getNamespaceAndAttri = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri.namespace, attributeName = _getNamespaceAndAttri.attributeName; var refinements = hasMultipleIndex(context) && searchState.indices && namespace && searchState.indices['' + index] && has_1(searchState.indices['' + index][namespace], '' + attributeName) || hasMultipleIndex(context) && searchState.indices && has_1(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && namespace && has_1(searchState[namespace], attributeName) || !hasMultipleIndex(context) && has_1(searchState, id); if (refinements) { var currentRefinement = void 0; if (hasMultipleIndex(context)) { currentRefinement = namespace ? get_1(searchState.indices['' + index][namespace], attributeName) : get_1(searchState.indices[index], id); } else { currentRefinement = namespace ? get_1(searchState[namespace], attributeName) : get_1(searchState, id); } return refinementsCallback(currentRefinement); } if (props.defaultRefinement) { return props.defaultRefinement; } return defaultValue; } function cleanUpValue(searchState, context, id) { var index = getIndex(context); var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri2.namespace, attributeName = _getNamespaceAndAttri2.attributeName; if (hasMultipleIndex(context)) { return namespace ? _extends({}, searchState, { indices: _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], defineProperty$2({}, namespace, omit_1(searchState.indices[index][namespace], '' + attributeName))))) }) : omit_1(searchState, 'indices.' + index + '.' + id); } else { return namespace ? _extends({}, searchState, defineProperty$2({}, namespace, omit_1(searchState[namespace], '' + attributeName))) : omit_1(searchState, '' + id); } } function getId() { return 'configure'; } var connectConfigure = createConnector({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var items = omit_1(props, 'children'); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var items = omit_1(props, 'children'); var nonPresentKeys = this._props ? difference_1(keys_1(this._props), keys_1(props)) : []; this._props = props; var nextValue = defineProperty$2({}, id, _extends({}, omit_1(nextSearchState[id], nonPresentKeys), items)); return refineValue(nextSearchState, nextValue, this.context); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var index = getIndex(this.context); var subState = hasMultipleIndex(this.context) && searchState.indices ? searchState.indices[index] : searchState; var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : []; var configureState = configureKeys.reduce(function (acc, item) { if (!props[item]) { acc[item] = subState[id][item]; } return acc; }, {}); var nextValue = defineProperty$2({}, id, configureState); return refineValue(searchState, nextValue, this.context); } }); var Configure = (function () { return null; }); /** * Configure is a widget that lets you provide raw search parameters * to the Algolia API. * * Any of the props added to this widget will be forwarded to Algolia. For more information * on the different parameters that can be set, have a look at the * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). * * This widget can be used either with react-dom and react-native. It will not render anything * on screen, only configure some parameters. * * Read more in the [Search parameters](guide/Search_parameters.html) guide. * @name Configure * @kind widget * @example * import React from 'react'; * * import { Configure, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Configure distinct={1} /> * </InstantSearch> * ); * } */ var Configure$1 = connectConfigure(Configure); /** * connectCurrentRefinements connector provides the logic to build a widget that will * give the user the ability to remove all or some of the filters that were * set. * @name connectCurrentRefinements * @kind connector * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {function} [clearsQuery=false] - Pass true to also clear the search query * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {array.<{label: string, attributeName: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attributeName` and `currentRefinement` are metadata containing row values. * @providedPropType {string} query - the search query */ var connectCurrentRefinements = createConnector({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) { var items = metadata.reduce(function (res, meta) { if (typeof meta.items !== 'undefined') { if (!props.clearsQuery && meta.id === 'query') { return res; } else { if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') { return res; } return res.concat(meta.items.map(function (item) { return _extends({}, item, { id: meta.id, index: meta.index }); })); } } return res; }, []); return { items: props.transformItems ? props.transformItems(items) : items, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, items) { // `value` corresponds to our internal clear function computed in each connector metadata. var refinementsToClear = items instanceof Array ? items.map(function (item) { return item.value; }) : [items]; return refinementsToClear.reduce(function (res, clear) { return clear(res); }, searchState); } }); var configManagerPropType = propTypes.shape({ register: propTypes.func.isRequired, swap: propTypes.func.isRequired, unregister: propTypes.func.isRequired }); var stateManagerPropType = propTypes.shape({ createURL: propTypes.func.isRequired, setState: propTypes.func.isRequired, getState: propTypes.func.isRequired, unlisten: propTypes.func.isRequired }); var withKeysPropType = function withKeysPropType(keys) { return function (props, propName, componentName) { var prop = props[propName]; if (prop) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = Object.keys(prop)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var key = _step.value; if (keys.indexOf(key) === -1) { return new Error('Unknown `' + propName + '` key `' + key + '`. Check the render method ' + ('of `' + componentName + '`.')); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } return undefined; }; }; function translatable(defaultTranslations) { return function (Composed) { function Translatable(props) { var translations = props.translations, otherProps = objectWithoutProperties(props, ['translations']); var translate = function translate(key) { for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } var translation = translations && has_1(translations, key) ? translations[key] : defaultTranslations[key]; if (typeof translation === 'function') { return translation.apply(undefined, params); } return translation; }; return React__default.createElement(Composed, _extends({ translate: translate }, otherProps)); } Translatable.displayName = 'Translatable(' + getDisplayName(Composed) + ')'; Translatable.propTypes = { translations: withKeysPropType(Object.keys(defaultTranslations)) }; return Translatable; }; } var classnames = createCommonjsModule(function (module) { /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if ('object' !== 'undefined' && module.exports) { module.exports = classNames; } else if (typeof undefined === 'function' && typeof undefined.amd === 'object' && undefined.amd) { // register as 'classnames', consistent with npm package name undefined('classnames', [], function () { return classNames; }); } else { window.classNames = classNames; } }()); }); var prefix = 'ais'; function classNames(block) { return function () { for (var _len = arguments.length, elements = Array(_len), _key = 0; _key < _len; _key++) { elements[_key] = arguments[_key]; } return { className: classnames(elements.filter(function (element) { return element !== undefined && element !== false; }).map(function (element) { return prefix + '-' + block + '__' + element; })) }; }; } var cx$1 = classNames('CurrentRefinements'); var CurrentRefinements = function (_Component) { inherits(CurrentRefinements, _Component); function CurrentRefinements() { classCallCheck(this, CurrentRefinements); return possibleConstructorReturn(this, (CurrentRefinements.__proto__ || Object.getPrototypeOf(CurrentRefinements)).apply(this, arguments)); } createClass(CurrentRefinements, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props, translate = _props.translate, items = _props.items, refine = _props.refine, canRefine = _props.canRefine; return React__default.createElement( 'div', cx$1('root', !canRefine && 'noRefinement'), React__default.createElement( 'div', cx$1('items'), items.map(function (item) { return React__default.createElement( 'div', _extends({ key: item.label }, cx$1('item', item.items && 'itemParent')), React__default.createElement( 'span', cx$1('itemLabel'), item.label ), item.items ? item.items.map(function (nestedItem) { return React__default.createElement( 'div', _extends({ key: nestedItem.label }, cx$1('item')), React__default.createElement( 'span', cx$1('itemLabel'), nestedItem.label ), React__default.createElement( 'button', _extends({}, cx$1('itemClear'), { onClick: function onClick() { return refine(nestedItem.value); } }), translate('clearFilter', nestedItem) ) ); }) : React__default.createElement( 'button', _extends({}, cx$1('itemClear'), { onClick: function onClick() { return refine(item.value); } }), translate('clearFilter', item) ) ); }) ) ); } }]); return CurrentRefinements; }(React.Component); CurrentRefinements.propTypes = { translate: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string })).isRequired, refine: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired, transformItems: propTypes.func }; CurrentRefinements.contextTypes = { canRefine: propTypes.func }; var CurrentRefinementsComponent = translatable({ clearFilter: '✕' })(CurrentRefinements); /** * The CurrentRefinements widget displays the list of currently applied filters. * * It allows the user to selectively remove them. * @name CurrentRefinements * @kind widget * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-CurrentRefinements__root - the root div of the widget * @themeKey ais-CurrentRefinements__items - the container of the filters * @themeKey ais-CurrentRefinements__item - a single filter * @themeKey ais-CurrentRefinements__itemLabel - the label of a filter * @themeKey ais-CurrentRefinements__itemClear - the trigger to remove the filter * @themeKey ais-CurrentRefinements__noRefinement - present when there is no refinement * @translationKey clearFilter - the remove filter button label * @example * import React from 'react'; * * import { CurrentRefinements, RefinementList, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CurrentRefinements /> * <RefinementList attributeName="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ var CurrentRefinements$1 = connectCurrentRefinements(CurrentRefinementsComponent); var getId$1 = function getId(props) { return props.attributes[0]; }; var namespace = 'hierarchicalMenu'; function getCurrentRefinement(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace + '.' + getId$1(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$2(path, props, searchState, context) { var id = props.id, attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel; var currentRefinement = getCurrentRefinement(props, searchState, context); var nextRefinement = void 0; if (currentRefinement === null) { nextRefinement = path; } else { var tmpSearchParameters = new algoliasearchHelper_4({ hierarchicalFacets: [{ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }] }); nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0]; } return nextRefinement; } function transformValue(value, props, searchState, context) { return value.map(function (v) { return { label: v.name, value: getValue$2(v.path, props, searchState, context), count: v.count, isRefined: v.isRefined, items: v.data && transformValue(v.data, props, searchState, context) }; }); } var truncate = function truncate() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; return items.slice(0, limit).map(function () { var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return Array.isArray(item.items) ? _extends({}, item, { items: truncate(item.items, limit) }) : item; }); }; function _refine(props, searchState, nextRefinement, context) { var id = getId$1(props); var nextValue = defineProperty$2({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return cleanUpValue(searchState, context, namespace + '.' + getId$1(props)); } var sortBy = ['name:asc']; /** * connectHierarchicalMenu connector provides the logic to build a widget that will * give the user the ability to explore a tree-like structure. * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * @name connectHierarchicalMenu * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax. * @propType {number} [limitMin=10] - The maximum number of items displayed. * @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items. */ var connectHierarchicalMenu = createConnector({ displayName: 'AlgoliaHierarchicalMenu', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, separator: propTypes.string, rootPath: propTypes.string, showParentLevel: propTypes.bool, defaultRefinement: propTypes.string, showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, transformItems: propTypes.func }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20, separator: ' > ', rootPath: null, showParentLevel: true }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var id = getId$1(props); var results = getResults(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: false }; } var limit = showMore ? limitMax : limitMin; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue(value.data, props, searchState, this.context) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: truncate(transformedItems, limit), currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var id = getId$1(props); var limit = showMore ? limitMax : limitMin; searchParameters = searchParameters.addHierarchicalFacet({ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }).setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); var currentRefinement = getCurrentRefinement(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var rootAttribute = props.attributes[0]; var id = getId$1(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: !currentRefinement ? [] : [{ label: rootAttribute + ': ' + currentRefinement, attributeName: rootAttribute, value: function value(nextState) { return _refine(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); var cx$2 = classNames('SearchBox'); var DefaultLoadingIndicator = function DefaultLoadingIndicator() { return React__default.createElement( 'svg', { width: '18', height: '18', viewBox: '0 0 38 38', xmlns: 'http://www.w3.org/2000/svg', stroke: '#BFC7D8' }, React__default.createElement( 'g', { fill: 'none', fillRule: 'evenodd' }, React__default.createElement( 'g', { transform: 'translate(1 1)', strokeWidth: '2' }, React__default.createElement('circle', { strokeOpacity: '.5', cx: '18', cy: '18', r: '18' }), React__default.createElement( 'path', { d: 'M36 18c0-9.94-8.06-18-18-18' }, React__default.createElement('animateTransform', { attributeName: 'transform', type: 'rotate', from: '0 18 18', to: '360 18 18', dur: '1s', repeatCount: 'indefinite' }) ) ) ) ); }; var DefaultReset = function DefaultReset() { return React__default.createElement( 'svg', { role: 'img', width: '1em', height: '1em' }, React__default.createElement('use', { xlinkHref: '#sbx-icon-clear-3' }) ); }; var DefaultSubmit = function DefaultSubmit() { return React__default.createElement( 'svg', { role: 'img', width: '1em', height: '1em' }, React__default.createElement('use', { xlinkHref: '#sbx-icon-search-13' }) ); }; var SearchBox = function (_Component) { inherits(SearchBox, _Component); function SearchBox(props) { classCallCheck(this, SearchBox); var _this = possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this)); _this.getQuery = function () { return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query; }; _this.onInputMount = function (input) { _this.input = input; if (_this.props.__inputRef) { _this.props.__inputRef(input); } }; _this.onKeyDown = function (e) { if (!_this.props.focusShortcuts) { return; } var shortcuts = _this.props.focusShortcuts.map(function (key) { return typeof key === 'string' ? key.toUpperCase().charCodeAt(0) : key; }); var elt = e.target || e.srcElement; var tagName = elt.tagName; if (elt.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA') { // already in an input return; } var which = e.which || e.keyCode; if (shortcuts.indexOf(which) === -1) { // not the right shortcut return; } _this.input.focus(); e.stopPropagation(); e.preventDefault(); }; _this.onSubmit = function (e) { e.preventDefault(); e.stopPropagation(); _this.input.blur(); var _this$props = _this.props, refine = _this$props.refine, searchAsYouType = _this$props.searchAsYouType; if (!searchAsYouType) { refine(_this.getQuery()); } return false; }; _this.onChange = function (event) { var _this$props2 = _this.props, searchAsYouType = _this$props2.searchAsYouType, refine = _this$props2.refine, onChange = _this$props2.onChange; var value = event.target.value; if (searchAsYouType) { refine(value); } else { _this.setState({ query: value }); } if (onChange) { onChange(event); } }; _this.onReset = function (event) { var _this$props3 = _this.props, searchAsYouType = _this$props3.searchAsYouType, refine = _this$props3.refine, onReset = _this$props3.onReset; refine(''); _this.input.focus(); if (!searchAsYouType) { _this.setState({ query: '' }); } if (onReset) { onReset(event); } }; _this.state = { query: props.searchAsYouType ? null : props.currentRefinement }; return _this; } createClass(SearchBox, [{ key: 'componentDidMount', value: function componentDidMount() { document.addEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { document.removeEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { // Reset query when the searchParameters query has changed. // This is kind of an anti-pattern (props in state), but it works here // since we know for sure that searchParameters having changed means a // new search has been triggered. if (!nextProps.searchAsYouType && nextProps.currentRefinement !== this.props.currentRefinement) { this.setState({ query: nextProps.currentRefinement }); } } // From https://github.com/algolia/autocomplete.js/pull/86 }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props, translate = _props.translate, autoFocus = _props.autoFocus, loadingIndicatorComponent = _props.loadingIndicatorComponent, resetComponent = _props.resetComponent, submitComponent = _props.submitComponent; var query = this.getQuery(); var searchInputEvents = Object.keys(this.props).reduce(function (props, prop) { if (['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) === -1 && prop.indexOf('on') === 0) { return _extends({}, props, defineProperty$2({}, prop, _this2.props[prop])); } return props; }, {}); var isSearchStalled = this.props.showLoadingIndicator && this.props.isSearchStalled; /* eslint-disable max-len */ return React__default.createElement( 'form', _extends({ noValidate: true, onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit, onReset: this.onReset }, cx$2('root'), { action: '', role: 'search' }), React__default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', style: { display: 'none' } }, React__default.createElement( 'symbol', { xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-search-13', viewBox: '0 0 40 40' }, React__default.createElement('path', { d: 'M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z', fillRule: 'evenodd' }) ), React__default.createElement( 'symbol', { xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-clear-3', viewBox: '0 0 20 20' }, React__default.createElement('path', { d: 'M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z', fillRule: 'evenodd' }) ) ), React__default.createElement( 'div', _extends({ role: 'search' }, cx$2('wrapper', isSearchStalled && 'stalled-search')), React__default.createElement('input', _extends({ ref: this.onInputMount, type: 'search', placeholder: translate('placeholder'), autoFocus: autoFocus, autoComplete: 'off', autoCorrect: 'off', autoCapitalize: 'off', spellCheck: 'false', required: true, maxLength: '512', value: query, onChange: this.onChange }, searchInputEvents, cx$2('input'))), this.props.showLoadingIndicator && React__default.createElement( 'div', _extends({ hidden: !isSearchStalled }, cx$2('loading-indicator')), loadingIndicatorComponent ), React__default.createElement( 'button', _extends({ type: 'submit', title: translate('submitTitle'), hidden: isSearchStalled }, cx$2('submit')), submitComponent ), React__default.createElement( 'button', _extends({ type: 'reset', title: translate('resetTitle') }, cx$2('reset'), { onClick: this.onReset }), resetComponent ) ) ); /* eslint-enable */ } }]); return SearchBox; }(React.Component); SearchBox.propTypes = { currentRefinement: propTypes.string, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, loadingIndicatorComponent: propTypes.element, resetComponent: propTypes.element, submitComponent: propTypes.element, focusShortcuts: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), autoFocus: propTypes.bool, searchAsYouType: propTypes.bool, onSubmit: propTypes.func, onReset: propTypes.func, onChange: propTypes.func, isSearchStalled: propTypes.bool, showLoadingIndicator: propTypes.bool, // For testing purposes __inputRef: propTypes.func }; SearchBox.defaultProps = { currentRefinement: '', focusShortcuts: ['s', '/'], autoFocus: false, searchAsYouType: true, showLoadingIndicator: false, isSearchStalled: false, loadingIndicatorComponent: React__default.createElement(DefaultLoadingIndicator, null), submitComponent: React__default.createElement(DefaultSubmit, null), resetComponent: React__default.createElement(DefaultReset, null) }; var SearchBoxComponent = translatable({ resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(SearchBox); var itemsPropType = propTypes.arrayOf(propTypes.shape({ value: propTypes.any, label: propTypes.node.isRequired, items: function items() { return itemsPropType.apply(undefined, arguments); } })); var List = function (_Component) { inherits(List, _Component); function List() { classCallCheck(this, List); var _this = possibleConstructorReturn(this, (List.__proto__ || Object.getPrototypeOf(List)).call(this)); _this.onShowMoreClick = function () { _this.setState(function (state) { return { extended: !state.extended }; }); }; _this.getLimit = function () { var _this$props = _this.props, limitMin = _this$props.limitMin, limitMax = _this$props.limitMax; var extended = _this.state.extended; return extended ? limitMax : limitMin; }; _this.resetQuery = function () { _this.setState({ query: '' }); }; _this.renderItem = function (item, resetQuery) { var items = item.items && React__default.createElement( 'div', _this.props.cx('itemItems'), item.items.slice(0, _this.getLimit()).map(function (child) { return _this.renderItem(child, item); }) ); return React__default.createElement( 'div', _extends({ key: item.key || item.label }, _this.props.cx('item', item.isRefined && 'itemSelected', item.noRefinement && 'itemNoRefinement', items && 'itemParent', items && item.isRefined && 'itemSelectedParent')), _this.props.renderItem(item, resetQuery), items ); }; _this.state = { extended: false, query: '' }; return _this; } createClass(List, [{ key: 'renderShowMore', value: function renderShowMore() { var _props = this.props, showMore = _props.showMore, translate = _props.translate, cx = _props.cx; var extended = this.state.extended; var disabled = this.props.limitMin >= this.props.items.length; if (!showMore) { return null; } return React__default.createElement( 'button', _extends({ disabled: disabled }, cx('showMore', disabled && 'showMoreDisabled'), { onClick: this.onShowMoreClick }), translate('showMore', extended) ); } }, { key: 'renderSearchBox', value: function renderSearchBox() { var _this2 = this; var _props2 = this.props, cx = _props2.cx, searchForItems = _props2.searchForItems, isFromSearch = _props2.isFromSearch, translate = _props2.translate, items = _props2.items, selectItem = _props2.selectItem; var noResults = items.length === 0 && this.state.query !== '' ? React__default.createElement( 'div', cx('noResults'), translate('noResults') ) : null; return React__default.createElement( 'div', cx('SearchBox'), React__default.createElement(SearchBoxComponent, { currentRefinement: this.state.query, refine: function refine(value) { _this2.setState({ query: value }); searchForItems(value); }, focusShortcuts: [], translate: translate, onSubmit: function onSubmit(e) { e.preventDefault(); e.stopPropagation(); if (isFromSearch) { selectItem(items[0], _this2.resetQuery); } } }), noResults ); } }, { key: 'render', value: function render() { var _this3 = this; var _props3 = this.props, cx = _props3.cx, items = _props3.items, withSearchBox = _props3.withSearchBox, canRefine = _props3.canRefine; var searchBox = withSearchBox ? this.renderSearchBox() : null; if (items.length === 0) { return React__default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), searchBox ); } // Always limit the number of items we show on screen, since the actual // number of retrieved items might vary with the `maxValuesPerFacet` config // option. var limit = this.getLimit(); return React__default.createElement( 'div', cx('root', !this.props.canRefine && 'noRefinement'), searchBox, React__default.createElement( 'div', cx('items'), items.slice(0, limit).map(function (item) { return _this3.renderItem(item, _this3.resetQuery); }) ), this.renderShowMore() ); } }]); return List; }(React.Component); List.propTypes = { cx: propTypes.func.isRequired, // Only required with showMore. translate: propTypes.func, items: itemsPropType, renderItem: propTypes.func.isRequired, selectItem: propTypes.func, showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, limit: propTypes.number, show: propTypes.func, searchForItems: propTypes.func, withSearchBox: propTypes.bool, isFromSearch: propTypes.bool, canRefine: propTypes.bool }; List.defaultProps = { isFromSearch: false }; var Link = function (_Component) { inherits(Link, _Component); function Link() { var _ref; var _temp, _this, _ret; classCallCheck(this, Link); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Link.__proto__ || Object.getPrototypeOf(Link)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function (e) { if (isSpecialClick(e)) { return; } _this.props.onClick(); e.preventDefault(); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(Link, [{ key: 'render', value: function render() { return React__default.createElement('a', _extends({}, omit_1(this.props, 'onClick'), { onClick: this.onClick })); } }]); return Link; }(React.Component); Link.propTypes = { onClick: propTypes.func.isRequired }; var cx$3 = classNames('HierarchicalMenu'); var itemsPropType$1 = propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string, count: propTypes.number.isRequired, items: function items() { return itemsPropType$1.apply(undefined, arguments); } })); var HierarchicalMenu = function (_Component) { inherits(HierarchicalMenu, _Component); function HierarchicalMenu() { var _ref; var _temp, _this, _ret; classCallCheck(this, HierarchicalMenu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = HierarchicalMenu.__proto__ || Object.getPrototypeOf(HierarchicalMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props, createURL = _this$props.createURL, refine = _this$props.refine; return React__default.createElement( Link, _extends({}, cx$3('itemLink'), { onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }), React__default.createElement( 'span', cx$3('itemLabel'), item.label ), ' ', React__default.createElement( 'span', cx$3('itemCount'), item.count ) ); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(HierarchicalMenu, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return React__default.createElement(List, _extends({ renderItem: this.renderItem, cx: cx$3 }, pick_1(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isEmpty', 'canRefine']))); } }]); return HierarchicalMenu; }(React.Component); HierarchicalMenu.propTypes = { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired, items: itemsPropType$1, showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, transformItems: propTypes.func }; HierarchicalMenu.contextTypes = { canRefine: propTypes.func }; var HierarchicalMenuComponent = translatable({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; } })(HierarchicalMenu); /** * The hierarchical menu lets the user browse attributes using a tree-like structure. * * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * * @name HierarchicalMenu * @kind widget * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * [{ * "objectID": "321432", * "name": "lemon", * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * }, * { * "objectID": "8976987", * "name": "orange", * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * }] * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "objectID": "321432", * "name": "lemon", * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax. * @propType {number} [limitMin=10] - The maximum number of items displayed. * @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HierarchicalMenu__root - Container of the widget * @themeKey ais-HierarchicalMenu__items - Container of the items * @themeKey ais-HierarchicalMenu__item - Id for a single list item * @themeKey ais-HierarchicalMenu__itemSelected - Id for the selected items in the list * @themeKey ais-HierarchicalMenu__itemParent - Id for the elements that have a sub list displayed * @themeKey ais-HierarchicalMenu__itemSelectedParent - Id for parents that have currently a child selected * @themeKey ais-HierarchicalMenu__itemLink - the link containing the label and the count * @themeKey ais-HierarchicalMenu__itemLabel - the label of the entry * @themeKey ais-HierarchicalMenu__itemCount - the count of the entry * @themeKey ais-HierarchicalMenu__itemItems - id representing a children * @themeKey ais-HierarchicalMenu__showMore - container for the show more button * @themeKey ais-HierarchicalMenu__noRefinement - present when there is no refinement * @translationKey showMore - The label of the show more button. Accepts one parameter, a boolean that is true if the values are expanded * @example * import React from 'react'; * import { HierarchicalMenu, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HierarchicalMenu * id="categories" * key="categories" * attributes={[ * 'category', * 'sub_category', * 'sub_sub_category', * ]} * /> * </InstantSearch> * ); * } */ var HierarchicalMenu$1 = connectHierarchicalMenu(HierarchicalMenuComponent); /** * Find an highlighted attribute given an `attributeName` and an `highlightProperty`, parses it, * and provided an array of objects with the string value and a boolean if this * value is highlighted. * * In order to use this feature, highlight must be activated in the configuration of * the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and * highligtPostTag in Algolia configuration. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightProperty - the property that contains the highlight structure in the results * @param {string} attributeName - the highlighted attribute to look for * @param {object} hit - the actual hit returned by Algolia. * @return {object[]} - An array of {value: string, isHighlighted: boolean}. */ function parseAlgoliaHit(_ref) { var _ref$preTag = _ref.preTag, preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag, _ref$postTag = _ref.postTag, postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag, highlightProperty = _ref.highlightProperty, attributeName = _ref.attributeName, hit = _ref.hit; if (!hit) throw new Error('`hit`, the matching record, must be provided'); var highlightObject = get_1(hit[highlightProperty], attributeName, {}); if (Array.isArray(highlightObject)) { return highlightObject.map(function (item) { return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: item.value }); }); } return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightObject.value }); } /** * Parses an highlighted attribute into an array of objects with the string value, and * a boolean that indicated if this part is highlighted. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseHighlightedAttribute(_ref2) { var preTag = _ref2.preTag, postTag = _ref2.postTag, _ref2$highlightedValu = _ref2.highlightedValue, highlightedValue = _ref2$highlightedValu === undefined ? '' : _ref2$highlightedValu; var splitByPreTag = highlightedValue.split(preTag); var firstValue = splitByPreTag.shift(); var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }]; if (postTag === preTag) { var isHighlighted = true; splitByPreTag.forEach(function (split) { elements.push({ value: split, isHighlighted: isHighlighted }); isHighlighted = !isHighlighted; }); } else { splitByPreTag.forEach(function (split) { var splitByPostTag = split.split(postTag); elements.push({ value: splitByPostTag[0], isHighlighted: true }); if (splitByPostTag[1] !== '') { elements.push({ value: splitByPostTag[1], isHighlighted: false }); } }); } return elements; } var highlight = function highlight(_ref) { var attributeName = _ref.attributeName, hit = _ref.hit, highlightProperty = _ref.highlightProperty; return parseAlgoliaHit({ attributeName: attributeName, hit: hit, preTag: highlightTags.highlightPreTag, postTag: highlightTags.highlightPostTag, highlightProperty: highlightProperty }); }; /** * connectHighlight connector provides the logic to create an highlighter * component that will retrieve, parse and render an highlighted attribute * from an Algolia hit. * @name connectHighlight * @kind connector * @category connector * @providedPropType {function} highlight - function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attributes: `highlightProperty` which is the property that contains the highlight structure from the records, `attributeName` which is the name of the attribute (it can be either a string or an array of strings) to look for and `hit` which is the hit from Algolia. It returns an array of objects `{value: string, isHighlighted: boolean}`. If the element that corresponds to the attributeName is an array of strings, it will return a nested array of objects. * @example * import React from 'react'; * import { connectHighlight } from 'react-instantsearch/connectors'; * import { InstantSearch, Hits } from 'react-instantsearch/dom'; * * const CustomHighlight = connectHighlight( * ({ highlight, attributeName, hit, highlightProperty }) => { * const parsedHit = highlight({ attributeName, hit, highlightProperty: '_highlightResult' }); * const highlightedHits = parsedHit.map(part => { * if (part.isHighlighted) return <mark>{part.value}</mark>; * return part.value; * }); * return <div>{highlightedHits}</div>; * } * ); * * const Hit = ({hit}) => * <p> * <CustomHighlight attributeName="description" hit={hit} /> * </p>; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea"> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); * } */ var connectHighlight = createConnector({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); var cx$4 = classNames('Highlight'); function generateKey(i, value) { return 'split-' + i + '-' + value; } var Highlight = function Highlight(_ref) { var value = _ref.value, highlightedTagName = _ref.highlightedTagName, isHighlighted = _ref.isHighlighted, nonHighlightedTagName = _ref.nonHighlightedTagName; var TagName = isHighlighted ? highlightedTagName : nonHighlightedTagName; var className = isHighlighted ? 'highlighted' : 'nonHighlighted'; return React__default.createElement( TagName, cx$4(className), value ); }; Highlight.propTypes = { value: propTypes.string.isRequired, isHighlighted: propTypes.bool.isRequired, highlightedTagName: propTypes.string.isRequired, nonHighlightedTagName: propTypes.string.isRequired }; function Highlighter(_ref2) { var hit = _ref2.hit, attributeName = _ref2.attributeName, highlight = _ref2.highlight, highlightProperty = _ref2.highlightProperty, tagName = _ref2.tagName, nonHighlightedTagName = _ref2.nonHighlightedTagName, separator = _ref2.separator; var parsedHighlightedValue = highlight({ hit: hit, attributeName: attributeName, highlightProperty: highlightProperty }); return React__default.createElement( 'span', { className: 'ais-Highlight' }, parsedHighlightedValue.map(function (item, i) { if (Array.isArray(item)) { var isLast = i === parsedHighlightedValue.length - 1; return React__default.createElement( 'span', { key: generateKey(i, hit[attributeName][i]) }, item.map(function (element, index) { return React__default.createElement(Highlight, { key: generateKey(index, element.value), value: element.value, highlightedTagName: tagName, nonHighlightedTagName: nonHighlightedTagName, isHighlighted: element.isHighlighted }); }), !isLast && React__default.createElement( 'span', cx$4('separator'), separator ) ); } return React__default.createElement(Highlight, { key: generateKey(i, item.value), value: item.value, highlightedTagName: tagName, nonHighlightedTagName: nonHighlightedTagName, isHighlighted: item.isHighlighted }); }) ); } Highlighter.propTypes = { hit: propTypes.object.isRequired, attributeName: propTypes.string.isRequired, highlight: propTypes.func.isRequired, highlightProperty: propTypes.string.isRequired, tagName: propTypes.string, nonHighlightedTagName: propTypes.string, separator: propTypes.node }; Highlighter.defaultProps = { tagName: 'em', nonHighlightedTagName: 'span', separator: ', ' }; function Highlight$1(props) { return React__default.createElement(Highlighter, _extends({ highlightProperty: '_highlightResult' }, props)); } Highlight$1.propTypes = { hit: propTypes.object.isRequired, attributeName: propTypes.string.isRequired, highlight: propTypes.func.isRequired, tagName: propTypes.string, nonHighlightedTagName: propTypes.string, separator: propTypes.node }; /** * Renders any attribute from a hit into its highlighted form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Highlight * @kind widget * @propType {string} attributeName - location of the highlighted attribute in the hit (the corresponding element can be either a string or an array of strings) * @propType {object} hit - hit object containing the highlighted attribute * @propType {string} [tagName='em'] - tag to be used for highlighted parts of the hit * @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted * @propType {React.Element} [separator=',<space>'] - symbol used to separate the elements of the array in case the attributeName points to an array of strings. * @themeKey ais-Highlight - root of the component * @themeKey ais-Highlight__highlighted - part of the text that is highlighted * @themeKey ais-Highlight__nonHighlighted - part of the text that is non highlighted * @example * import React from 'react'; * * import { connectHits, Highlight, InstantSearch } from 'react-instantsearch/dom'; * * const CustomHits = connectHits(({ hits }) => * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attributeName="description" hit={hit} /> * </p> * )} * </div> * ); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ var Highlight$2 = connectHighlight(Highlight$1); function Snippet(props) { return React__default.createElement(Highlighter, _extends({ highlightProperty: '_snippetResult' }, props)); } Snippet.propTypes = { hit: propTypes.object.isRequired, attributeName: propTypes.string.isRequired, highlight: propTypes.func.isRequired, tagName: propTypes.string, nonHighlightedTagName: propTypes.string, separator: propTypes.node }; /** * Renders any attribute from an hit into its highlighted snippet form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Snippet * @kind widget * @requirements To use this widget, the attribute name passed to the `attributeName` prop must be * present in "Attributes to snippet" on the Algolia dashboard or configured as `attributesToSnippet` * via a set settings call to the Algolia API. * @propType {string} attributeName - location of the highlighted snippet attribute in the hit (the corresponding element can be either a string or an array of strings) * @propType {object} hit - hit object containing the highlighted snippet attribute * @propType {string} [tagName='em'] - tag to be used for highlighted parts of the attribute * @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted * @propType {React.Element} [separator=',<space>'] - symbol used to separate the elements of the array in case the attributeName points to an array of strings. * @example * import React from 'react'; * import { Snippet, InstantSearch, Hits } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Hits * hitComponent={({ hit }) => ( * <p key={hit.objectID}> * <Snippet attributeName="description" hit={hit} /> * </p> * )} * /> * </InstantSearch> * ); * } */ var Snippet$1 = connectHighlight(Snippet); /** * connectHits connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * * **Warning:** you will need to use the **objectID** property available on every hit as a key * when iterating over them. This will ensure you have the best possible UI experience * especially on slow networks. * @name connectHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @example * import React from 'react'; * * import { Highlight, InstantSearch } from 'react-instantsearch/dom'; * import { connectHits } from 'react-instantsearch/connectors'; * const CustomHits = connectHits(({ hits }) => * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attributeName="description" hit={hit} /> * </p> * )} * </div> * ); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ var connectHits = createConnector({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); var hits = results ? results.hits : []; return { hits: hits }; }, /* Hits needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters) { return searchParameters; } }); var cx$5 = classNames('Hits'); var Hits = function Hits(_ref) { var hits = _ref.hits, HitComponent = _ref.hitComponent; return ( // Spread the hit on HitComponent instead of passing the full object. BC. // ex: <HitComponent {...hit} key={hit.objectID} /> React__default.createElement( 'div', cx$5('root'), hits.map(function (hit) { return React__default.createElement(HitComponent, { key: hit.objectID, hit: hit }); }) ) ); }; Hits.propTypes = { hits: propTypes.array, hitComponent: propTypes.func.isRequired }; Hits.defaultProps = { hitComponent: function hitComponent(props) { return React__default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px' } }, JSON.stringify(props).slice(0, 100), '...' ); } }; /** * Displays a list of hits. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name Hits * @kind widget * @propType {Component} [hitComponent] - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey ais-Hits__root - the root of the component * @example * import React from 'react'; * import { Hits, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Hits /> * </InstantSearch> * ); * } */ var Hits$1 = connectHits(Hits); function getId$2() { return 'hitsPerPage'; } function getCurrentRefinement$1(props, searchState, context) { var id = getId$2(); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * connectHitsPerPage connector provides the logic to create connected * components that will allow a user to choose to display more or less results from Algolia. * @name connectHitsPerPage * @kind connector * @propType {number} defaultRefinement - The number of items selected by default * @propType {{value: number, label: string}[]} items - List of hits per page options. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectHitsPerPage = createConnector({ displayName: 'AlgoliaHitsPerPage', propTypes: { defaultRefinement: propTypes.number.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.number.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$1(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId$2(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$2()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement$1(props, searchState, this.context)); }, getMetadata: function getMetadata() { return { id: getId$2() }; } }); var Select = function (_Component) { inherits(Select, _Component); function Select() { var _ref; var _temp, _this, _ret; classCallCheck(this, Select); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Select.__proto__ || Object.getPrototypeOf(Select)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.onSelect(e.target.value); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(Select, [{ key: 'render', value: function render() { var _props = this.props, cx = _props.cx, items = _props.items, selectedItem = _props.selectedItem; return React__default.createElement( 'select', _extends({}, cx('root'), { value: selectedItem, onChange: this.onChange }), items.map(function (item) { return React__default.createElement( 'option', { key: has_1(item, 'key') ? item.key : item.value, disabled: item.disabled, value: item.value }, has_1(item, 'label') ? item.label : item.value ); }) ); } }]); return Select; }(React.Component); Select.propTypes = { cx: propTypes.func.isRequired, onSelect: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ value: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired, key: propTypes.oneOfType([propTypes.string, propTypes.number]), label: propTypes.string, disabled: propTypes.bool })).isRequired, selectedItem: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired }; var cx$6 = classNames('HitsPerPage'); var HitsPerPage = function (_Component) { inherits(HitsPerPage, _Component); function HitsPerPage() { classCallCheck(this, HitsPerPage); return possibleConstructorReturn(this, (HitsPerPage.__proto__ || Object.getPrototypeOf(HitsPerPage)).apply(this, arguments)); } createClass(HitsPerPage, [{ key: 'render', value: function render() { var _props = this.props, currentRefinement = _props.currentRefinement, refine = _props.refine, items = _props.items; return React__default.createElement(Select, { onSelect: refine, selectedItem: currentRefinement, items: items, cx: cx$6 }); } }]); return HitsPerPage; }(React.Component); HitsPerPage.propTypes = { refine: propTypes.func.isRequired, currentRefinement: propTypes.number.isRequired, transformItems: propTypes.func, items: propTypes.arrayOf(propTypes.shape({ /** * Number of hits to display. */ value: propTypes.number.isRequired, /** * Label to display on the option. */ label: propTypes.string })) }; /** * The HitsPerPage widget displays a dropdown menu to let the user change the number * of displayed hits. * * If you only want to configure the number of hits per page without * displaying a widget, you should use the `<Configure hitsPerPage={20} />` widget. See [`<Configure /> documentation`](widgets/Configure.html) * * @name HitsPerPage * @kind widget * @propType {{value: number, label: string}[]} items - List of available options. * @propType {number} defaultRefinement - The number of items selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HitsPerPage__root - the root of the component. * @example * import React from 'react'; * import { HitsPerPage, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HitsPerPage * defaultRefinement={20} * items={[{value: 20, label: 'Show 20 hits'}, {value: 50, label: 'Show 50 hits'}]} * /> * </InstantSearch> * ); * } */ var HitsPerPage$1 = connectHitsPerPage(HitsPerPage); function getId$3() { return 'page'; } function getCurrentRefinement$2(props, searchState, context) { var id = getId$3(); var page = 1; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { currentRefinement = parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * InfiniteHits connector provides the logic to create connected * components that will render an continuous list of results retrieved from * Algolia. This connector provides a function to load more results. * @name connectInfiniteHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @providedPropType {boolean} hasMore - indicates if there are more pages to load * @providedPropType {function} refine - call to load more results */ var connectInfiniteHits = createConnector({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { this._allResults = []; return { hits: this._allResults, hasMore: false }; } var hits = results.hits, page = results.page, nbPages = results.nbPages; // If it is the same page we do not touch the page result list if (page === 0) { this._allResults = hits; } else if (page > this.previousPage) { this._allResults = [].concat(toConsumableArray(this._allResults), toConsumableArray(hits)); } else if (page < this.previousPage) { this._allResults = hits; } var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; this.previousPage = page; return { hits: this._allResults, hasMore: hasMore }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQueryParameters({ page: getCurrentRefinement$2(props, searchState, this.context) - 1 }); }, refine: function refine(props, searchState) { var id = getId$3(); var nextPage = getCurrentRefinement$2(props, searchState, this.context) + 1; var nextValue = defineProperty$2({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, this.context, resetPage); } }); var cx$7 = classNames('InfiniteHits'); var InfiniteHits = function (_Component) { inherits(InfiniteHits, _Component); function InfiniteHits() { classCallCheck(this, InfiniteHits); return possibleConstructorReturn(this, (InfiniteHits.__proto__ || Object.getPrototypeOf(InfiniteHits)).apply(this, arguments)); } createClass(InfiniteHits, [{ key: 'render', value: function render() { var _props = this.props, ItemComponent = _props.hitComponent, hits = _props.hits, hasMore = _props.hasMore, refine = _props.refine, translate = _props.translate; var renderedHits = hits.map(function (hit) { return React__default.createElement(ItemComponent, { key: hit.objectID, hit: hit }); }); var loadMoreButton = hasMore ? React__default.createElement( 'button', _extends({}, cx$7('loadMore'), { onClick: function onClick() { return refine(); } }), translate('loadMore') ) : React__default.createElement( 'button', _extends({}, cx$7('loadMore'), { disabled: true }), translate('loadMore') ); return React__default.createElement( 'div', cx$7('root'), renderedHits, loadMoreButton ); } }]); return InfiniteHits; }(React.Component); InfiniteHits.propTypes = { hits: propTypes.array, hitComponent: propTypes.oneOfType([propTypes.string, propTypes.func]).isRequired, hasMore: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired }; /* eslint-disable react/display-name */ InfiniteHits.defaultProps = { hitComponent: function hitComponent(hit) { return React__default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px' } }, JSON.stringify(hit).slice(0, 100), '...' ); } }; /* eslint-enable react/display-name */ var InfiniteHitsComponent = translatable({ loadMore: 'Load more' })(InfiniteHits); /** * Displays an infinite list of hits along with a **load more** button. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name InfiniteHits * @kind widget * @propType {Component} hitComponent - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey ais-InfiniteHits__root - the root of the component * @translationKey loadMore - the label of load more button * @example * import React from 'react'; * import { InfiniteHits, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <InfiniteHits /> * </InstantSearch> * ); * } */ var InfiniteHits$1 = connectInfiniteHits(InfiniteHitsComponent); var namespace$1 = 'menu'; function getId$4(props) { return props.attributeName; } function getCurrentRefinement$3(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$1 + '.' + getId$4(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$3(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$3(props, searchState, context); return name === currentRefinement ? '' : name; } function getLimit(_ref) { var showMore = _ref.showMore, limitMin = _ref.limitMin, limitMax = _ref.limitMax; return showMore ? limitMax : limitMin; } function _refine$1(props, searchState, nextRefinement, context) { var id = getId$4(props); var nextValue = defineProperty$2({}, id, nextRefinement ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$1); } function _cleanUp$1(props, searchState, context) { return cleanUpValue(searchState, context, namespace$1 + '.' + getId$4(props)); } var sortBy$1 = ['count:desc', 'name:asc']; /** * connectMenu connector provides the logic to build a widget that will * give the user the ability to choose a single value for a specific facet. * @name connectMenu * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @kind connector * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of diplayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {boolean} [withSearchBox=false] - allow search inside values * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var connectMenu = createConnector({ displayName: 'AlgoliaMenu', propTypes: { attributeName: propTypes.string.isRequired, showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, defaultRefinement: propTypes.string, transformItems: propTypes.func, withSearchBox: propTypes.bool, searchForFacetValues: propTypes.bool // @deprecated }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var _this = this; var attributeName = props.attributeName; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== ''); var withSearchBox = props.withSearchBox || props.searchForFacetValues; if (props.withSearchBox && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$3(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue$3(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy$1 }).map(function (v) { return { label: v.name, value: getValue$3(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var sortedItems = withSearchBox && !isFromSearch ? orderBy_1(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items; var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems; return { items: transformedItems.slice(0, getLimit(props)), currentRefinement: getCurrentRefinement$3(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$1(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement, maxFacetHits: getLimit(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$1(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit(props)) }); searchParameters = searchParameters.addDisjunctiveFacet(attributeName); var currentRefinement = getCurrentRefinement$3(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attributeName, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this2 = this; var id = getId$4(props); var currentRefinement = getCurrentRefinement$3(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: props.attributeName + ': ' + currentRefinement, attributeName: props.attributeName, value: function value(nextState) { return _refine$1(props, nextState, '', _this2.context); }, currentRefinement: currentRefinement }] }; } }); var cx$8 = classNames('Menu'); var Menu = function (_Component) { inherits(Menu, _Component); function Menu() { var _ref; var _temp, _this, _ret; classCallCheck(this, Menu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Menu.__proto__ || Object.getPrototypeOf(Menu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item, resetQuery) { var createURL = _this.props.createURL; var label = _this.props.isFromSearch ? React__default.createElement(Highlight$2, { attributeName: 'label', hit: item }) : item.label; return React__default.createElement( Link, _extends({}, cx$8('itemLink', item.isRefined && 'itemLinkSelected'), { onClick: function onClick() { return _this.selectItem(item, resetQuery); }, href: createURL(item.value) }), React__default.createElement( 'span', cx$8('itemLabel', item.isRefined && 'itemLabelSelected'), label ), ' ', React__default.createElement( 'span', cx$8('itemCount', item.isRefined && 'itemCountSelected'), item.count ) ); }, _this.selectItem = function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(Menu, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return React__default.createElement(List, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$8 }, pick_1(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine']))); } }]); return Menu; }(React.Component); Menu.propTypes = { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, searchForItems: propTypes.func.isRequired, withSearchBox: propTypes.bool, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired, count: propTypes.number.isRequired, isRefined: propTypes.bool.isRequired })), isFromSearch: propTypes.bool.isRequired, canRefine: propTypes.bool.isRequired, showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, transformItems: propTypes.func }; Menu.contextTypes = { canRefine: propTypes.func }; var MenuComponent = translatable({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(Menu); /** * The Menu component displays a menu that lets the user choose a single value for a specific attribute. * @name Menu * @kind widget * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * If you are using the `withSearchBox` prop, you'll also need to make the attribute searchable using * the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values). * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of diplayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/). * @themeKey ais-Menu__root - the root of the component * @themeKey ais-Menu__items - the container of all items in the menu * @themeKey ais-Menu__item - a single item * @themeKey ais-Menu__itemLinkSelected - the selected menu item * @themeKey ais-Menu__itemLink - the item link * @themeKey ais-Menu__itemLabelSelected - the selected item label * @themeKey ais-Menu__itemLabel - the item label * @themeKey ais-Menu__itemCount - the item count * @themeKey ais-Menu__itemCountSelected - the selected item count * @themeKey ais-Menu__noRefinement - present when there is no refinement * @themeKey ais-Menu__showMore - the button that let the user toggle more results * @themeKey ais-Menu__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @example * import React from 'react'; * * import { Menu, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Menu * attributeName="category" * /> * </InstantSearch> * ); * } */ var Menu$1 = connectMenu(MenuComponent); var cx$9 = classNames('MenuSelect'); var MenuSelect = function (_Component) { inherits(MenuSelect, _Component); function MenuSelect() { var _ref; var _temp, _this, _ret; classCallCheck(this, MenuSelect); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = MenuSelect.__proto__ || Object.getPrototypeOf(MenuSelect)).call.apply(_ref, [this].concat(args))), _this), _this.handleSelectChange = function (_ref2) { var value = _ref2.target.value; _this.props.refine(value === 'ais__see__all__option' ? '' : value); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(MenuSelect, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props, items = _props.items, translate = _props.translate; return React__default.createElement( 'select', _extends({ value: this.selectedValue, onChange: this.handleSelectChange }, cx$9('select')), React__default.createElement( 'option', _extends({ value: 'ais__see__all__option' }, cx$9('option')), translate('seeAllOption') ), items.map(function (item) { return React__default.createElement( 'option', _extends({ key: item.value, value: item.value }, cx$9('option')), item.label, ' (', item.count, ')' ); }) ); } }, { key: 'selectedValue', get: function get() { var _ref3 = find_1(this.props.items, { isRefined: true }) || { value: 'ais__see__all__option' }, value = _ref3.value; return value; } }]); return MenuSelect; }(React.Component); MenuSelect.propTypes = { canRefine: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired, count: propTypes.oneOfType([propTypes.number.isRequired, propTypes.string.isRequired]), isRefined: propTypes.bool.isRequired })) }; MenuSelect.contextTypes = { canRefine: propTypes.func }; var MenuSelectComponent = translatable({ seeAllOption: 'See all' })(MenuSelect); /** * The MenuSelect component displays a select that lets the user choose a single value for a specific attribute. * @name MenuSelect * @kind widget * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attributeName - the name of the attribute in the record * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-MenuSelect__select - the `<select>` DOM element. * @themeKey ais-MenuSelect__option - the `<option>` DOM element for a single item * @translationkey seeAllOption - The label of the option to select to remove the refinement * @example * import React from 'react'; * * import { MenuSelect, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <MenuSelect * attributeName="category" * /> * </InstantSearch> * ); * } */ var MenuSelect$1 = connectMenu(MenuSelectComponent); function stringifyItem(item) { if (typeof item.start === 'undefined' && typeof item.end === 'undefined') { return ''; } return (item.start ? item.start : '') + ':' + (item.end ? item.end : ''); } function parseItem(value) { if (value.length === 0) { return { start: null, end: null }; } var _value$split = value.split(':'), _value$split2 = slicedToArray(_value$split, 2), startStr = _value$split2[0], endStr = _value$split2[1]; return { start: startStr.length > 0 ? parseInt(startStr, 10) : null, end: endStr.length > 0 ? parseInt(endStr, 10) : null }; } var namespace$2 = 'multiRange'; function getId$5(props) { return props.attributeName; } function getCurrentRefinement$4(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$2 + '.' + getId$5(props), '', function (currentRefinement) { if (currentRefinement === '') { return ''; } return currentRefinement; }); } function isRefinementsRangeIncludesInsideItemRange(stats, start, end) { return stats.min > start && stats.min < end || stats.max > start && stats.max < end; } function isItemRangeIncludedInsideRefinementsRange(stats, start, end) { return start > stats.min && start < stats.max || end > stats.min && end < stats.max; } function itemHasRefinement(attributeName, results, value) { var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; var range = value.split(':'); var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]); var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]); return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end))); } function _refine$2(props, searchState, nextRefinement, context) { var nextValue = defineProperty$2({}, getId$5(props, searchState), nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$2); } function _cleanUp$2(props, searchState, context) { return cleanUpValue(searchState, context, namespace$2 + '.' + getId$5(props)); } /** * connectMultiRange connector provides the logic to build a widget that will * give the user the ability to select a range value for a numeric attribute. * Ranges are defined statically. * @name connectMultiRange * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @kind connector * @propType {string} attributeName - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string. * @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the MultiRange can display. */ var connectMultiRange = createConnector({ displayName: 'AlgoliaMultiRange', propTypes: { id: propTypes.string, attributeName: propTypes.string.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node, start: propTypes.number, end: propTypes.number })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName; var currentRefinement = getCurrentRefinement$4(props, searchState, this.context); var results = getResults(searchResults, this.context); var items = props.items.map(function (item) { var value = stringifyItem(item); return { label: item.label, value: value, isRefined: value === currentRefinement, noRefinement: results ? itemHasRefinement(getId$5(props), results, value) : false }; }); var stats = results && results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; var refinedItem = find_1(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: isEmpty_1(refinedItem), noRefinement: !stats, label: 'All' }); } return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement, canRefine: items.length > 0 && items.some(function (item) { return item.noRefinement === false; }) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$2(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$2(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var _parseItem = parseItem(getCurrentRefinement$4(props, searchState, this.context)), start = _parseItem.start, end = _parseItem.end; searchParameters = searchParameters.addDisjunctiveFacet(attributeName); if (start) { searchParameters = searchParameters.addNumericRefinement(attributeName, '>=', start); } if (end) { searchParameters = searchParameters.addNumericRefinement(attributeName, '<=', end); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$5(props); var value = getCurrentRefinement$4(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (value !== '') { var _find2 = find_1(props.items, function (item) { return stringifyItem(item) === value; }), label = _find2.label; items.push({ label: props.attributeName + ': ' + label, attributeName: props.attributeName, currentRefinement: label, value: function value(nextState) { return _refine$2(props, nextState, '', _this.context); } }); } return { id: id, index: index, items: items }; } }); var cx$10 = classNames('MultiRange'); var MultiRange = function (_Component) { inherits(MultiRange, _Component); function MultiRange() { var _ref; var _temp, _this, _ret; classCallCheck(this, MultiRange); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = MultiRange.__proto__ || Object.getPrototypeOf(MultiRange)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props, refine = _this$props.refine, translate = _this$props.translate; var label = item.value === '' ? translate('all') : item.label; return React__default.createElement( 'label', cx$10(item.value === '' && 'itemAll'), React__default.createElement('input', _extends({}, cx$10('itemRadio', item.isRefined && 'itemRadioSelected'), { type: 'radio', checked: item.isRefined, disabled: item.noRefinement, onChange: function onChange() { return refine(item.value); } })), React__default.createElement('span', cx$10('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')), React__default.createElement( 'span', cx$10('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'), label ) ); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(MultiRange, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props, items = _props.items, canRefine = _props.canRefine; return React__default.createElement(List, { renderItem: this.renderItem, showMore: false, canRefine: canRefine, cx: cx$10, items: items.map(function (item) { return _extends({}, item, { key: item.value }); }) }); } }]); return MultiRange; }(React.Component); MultiRange.propTypes = { items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node.isRequired, value: propTypes.string.isRequired, isRefined: propTypes.bool.isRequired, noRefinement: propTypes.bool.isRequired })).isRequired, refine: propTypes.func.isRequired, transformItems: propTypes.func, canRefine: propTypes.bool.isRequired, translate: propTypes.func.isRequired }; MultiRange.contextTypes = { canRefine: propTypes.func }; var MultiRangeComponent = translatable({ all: 'All' })(MultiRange); /** * MultiRange is a widget used for selecting the range value of a numeric attribute. * @name MultiRange * @kind widget * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the format "min:max". * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-MultiRange__root - The root component of the widget * @themeKey ais-MultiRange__items - The container of the items * @themeKey ais-MultiRange__item - A single item * @themeKey ais-MultiRange__itemSelected - The selected item * @themeKey ais-MultiRange__itemLabel - The label of an item * @themeKey ais-MultiRange__itemLabelSelected - The selected label item * @themeKey ais-MultiRange__itemRadio - The radio of an item * @themeKey ais-MultiRange__itemRadioSelected - The selected radio item * @themeKey ais-MultiRange__noRefinement - present when there is no refinement for all ranges * @themeKey ais-MultiRange__itemNoRefinement - present when there is no refinement for one range * @themeKey ais-MultiRange__itemAll - indicate the range that will contain all the results * @translationkey all - The label of the largest range added automatically by react instantsearch * @example * import React from 'react'; * * import { MultiRange, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <MultiRange * attributeName="price" * items={[ * { end: 10, label: '<$10' }, * { start: 10, end: 100, label: '$10-$100' }, * { start: 100, end: 500, label: '$100-$500' }, * { start: 500, label: '>$500' }, * ]} * /> * </InstantSearch> * ); * } */ var MultiRange$1 = connectMultiRange(MultiRangeComponent); function getId$6() { return 'page'; } function getCurrentRefinement$5(props, searchState, context) { var id = getId$6(); var page = 1; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } function _refine$3(props, searchState, nextPage, context) { var id = getId$6(); var nextValue = defineProperty$2({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, context, resetPage); } /** * connectPagination connector provides the logic to build a widget that will * let the user displays hits corresponding to a certain page. * @name connectPagination * @kind connector * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [pagesPadding=3] - How many page links to display around the current page. * @propType {number} [maxPages=Infinity] - Maximum number of pages to display. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {number} nbPages - the total of existing pages * @providedPropType {number} currentRefinement - the page refinement currently applied */ var connectPagination = createConnector({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement$5(props, searchState, this.context), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine$3(props, searchState, nextPage, this.context); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$6()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement$5(props, searchState, this.context) - 1); }, getMetadata: function getMetadata() { return { id: getId$6() }; } }); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil; var nativeMax$7 = Math.max; /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax$7(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } var _baseRange = baseRange; /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && _isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite_1(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite_1(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite_1(step); return _baseRange(start, end, step, fromRight); }; } var _createRange = createRange; /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = _createRange(); var range_1 = range; var LinkList = function (_Component) { inherits(LinkList, _Component); function LinkList() { classCallCheck(this, LinkList); return possibleConstructorReturn(this, (LinkList.__proto__ || Object.getPrototypeOf(LinkList)).apply(this, arguments)); } createClass(LinkList, [{ key: 'render', value: function render() { var _props = this.props, cx = _props.cx, createURL = _props.createURL, items = _props.items, onSelect = _props.onSelect, canRefine = _props.canRefine; return React__default.createElement( 'ul', cx('root', !canRefine && 'noRefinement'), items.map(function (item) { return React__default.createElement( 'li', _extends({ key: has_1(item, 'key') ? item.key : item.value }, cx('item', item.selected && !item.disabled && 'itemSelected', item.disabled && 'itemDisabled', item.modifier), { disabled: item.disabled }), item.disabled ? React__default.createElement( 'span', cx('itemLink', 'itemLinkDisabled'), has_1(item, 'label') ? item.label : item.value ) : React__default.createElement( Link, _extends({}, cx('itemLink', item.selected && 'itemLinkSelected'), { 'aria-label': item.ariaLabel, href: createURL(item.value), onClick: function onClick() { return onSelect(item.value); } }), has_1(item, 'label') ? item.label : item.value ) ); }) ); } }]); return LinkList; }(React.Component); LinkList.propTypes = { cx: propTypes.func.isRequired, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ value: propTypes.oneOfType([propTypes.string, propTypes.number, propTypes.object]).isRequired, key: propTypes.oneOfType([propTypes.string, propTypes.number]), label: propTypes.node, modifier: propTypes.string, ariaLabel: propTypes.string, disabled: propTypes.bool })), onSelect: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired }; var cx$11 = classNames('Pagination'); // Determines the size of the widget (the number of pages displayed - that the user can directly click on) function calculateSize(padding, maxPages) { return Math.min(2 * padding + 1, maxPages); } function calculatePaddingLeft(currentPage, padding, maxPages, size) { if (currentPage <= padding) { return currentPage; } if (currentPage >= maxPages - padding) { return size - (maxPages - currentPage); } return padding + 1; } // Retrieve the correct page range to populate the widget function getPages(currentPage, maxPages, padding) { var size = calculateSize(padding, maxPages); // If the widget size is equal to the max number of pages, return the entire page range if (size === maxPages) return range_1(1, maxPages + 1); var paddingLeft = calculatePaddingLeft(currentPage, padding, maxPages, size); var paddingRight = size - paddingLeft; var first = currentPage - paddingLeft; var last = currentPage + paddingRight; return range_1(first + 1, last + 1); } var Pagination = function (_Component) { inherits(Pagination, _Component); function Pagination() { classCallCheck(this, Pagination); return possibleConstructorReturn(this, (Pagination.__proto__ || Object.getPrototypeOf(Pagination)).apply(this, arguments)); } createClass(Pagination, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'getItem', value: function getItem(modifier, translationKey, value) { var _props = this.props, nbPages = _props.nbPages, maxPages = _props.maxPages, translate = _props.translate; return { key: modifier + '.' + value, modifier: modifier, disabled: value < 1 || value >= Math.min(maxPages, nbPages), label: translate(translationKey, value), value: value, ariaLabel: translate('aria' + capitalize(translationKey), value) }; } }, { key: 'render', value: function render() { var _props2 = this.props, nbPages = _props2.nbPages, maxPages = _props2.maxPages, currentRefinement = _props2.currentRefinement, pagesPadding = _props2.pagesPadding, showFirst = _props2.showFirst, showPrevious = _props2.showPrevious, showNext = _props2.showNext, showLast = _props2.showLast, refine = _props2.refine, createURL = _props2.createURL, translate = _props2.translate, ListComponent = _props2.listComponent, otherProps = objectWithoutProperties(_props2, ['nbPages', 'maxPages', 'currentRefinement', 'pagesPadding', 'showFirst', 'showPrevious', 'showNext', 'showLast', 'refine', 'createURL', 'translate', 'listComponent']); var totalPages = Math.min(nbPages, maxPages); var lastPage = totalPages; var items = []; if (showFirst) { items.push({ key: 'first', modifier: 'itemFirst', disabled: currentRefinement === 1, label: translate('first'), value: 1, ariaLabel: translate('ariaFirst') }); } if (showPrevious) { items.push({ key: 'previous', modifier: 'itemPrevious', disabled: currentRefinement === 1, label: translate('previous'), value: currentRefinement - 1, ariaLabel: translate('ariaPrevious') }); } items = items.concat(getPages(currentRefinement, totalPages, pagesPadding).map(function (value) { return { key: value, modifier: 'itemPage', label: translate('page', value), value: value, selected: value === currentRefinement, ariaLabel: translate('ariaPage', value) }; })); if (showNext) { items.push({ key: 'next', modifier: 'itemNext', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('next'), value: currentRefinement + 1, ariaLabel: translate('ariaNext') }); } if (showLast) { items.push({ key: 'last', modifier: 'itemLast', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('last'), value: lastPage, ariaLabel: translate('ariaLast') }); } return React__default.createElement(ListComponent, _extends({}, otherProps, { cx: cx$11, items: items, onSelect: refine, createURL: createURL })); } }]); return Pagination; }(React.Component); Pagination.propTypes = { nbPages: propTypes.number.isRequired, currentRefinement: propTypes.number.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired, translate: propTypes.func.isRequired, listComponent: propTypes.func, showFirst: propTypes.bool, showPrevious: propTypes.bool, showNext: propTypes.bool, showLast: propTypes.bool, pagesPadding: propTypes.number, maxPages: propTypes.number }; Pagination.defaultProps = { listComponent: LinkList, showFirst: true, showPrevious: true, showNext: true, showLast: false, pagesPadding: 3, maxPages: Infinity }; Pagination.contextTypes = { canRefine: propTypes.func }; var PaginationComponent = translatable({ previous: '‹', next: '›', first: '«', last: '»', page: function page(currentRefinement) { return currentRefinement.toString(); }, ariaPrevious: 'Previous page', ariaNext: 'Next page', ariaFirst: 'First page', ariaLast: 'Last page', ariaPage: function ariaPage(currentRefinement) { return 'Page ' + currentRefinement.toString(); } })(Pagination); /** * The Pagination widget displays a simple pagination system allowing the user to * change the current page. * @name Pagination * @kind widget * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [pagesPadding=3] - How many page links to display around the current page. * @propType {number} [maxPages=Infinity] - Maximum number of pages to display. * @themeKey ais-Pagination__root - The root component of the widget * @themeKey ais-Pagination__itemFirst - The first page link item * @themeKey ais-Pagination__itemPrevious - The previous page link item * @themeKey ais-Pagination__itemPage - The page link item * @themeKey ais-Pagination__itemNext - The next page link item * @themeKey ais-Pagination__itemLast - The last page link item * @themeKey ais-Pagination__itemDisabled - a disabled item * @themeKey ais-Pagination__itemSelected - a selected item * @themeKey ais-Pagination__itemLink - The link of an item * @themeKey ais-Pagination__noRefinement - present when there is no refinement * @translationKey previous - Label value for the previous page link * @translationKey next - Label value for the next page link * @translationKey first - Label value for the first page link * @translationKey last - Label value for the last page link * @translationkey page - Label value for a page item. You get function(currentRefinement) and you need to return a string * @translationKey ariaPrevious - Accessibility label value for the previous page link * @translationKey ariaNext - Accessibility label value for the next page link * @translationKey ariaFirst - Accessibility label value for the first page link * @translationKey ariaLast - Accessibility label value for the last page link * @translationkey ariaPage - Accessibility label value for a page item. You get function(currentRefinement) and you need to return a string * @example * import React from 'react'; * * import { Pagination, InstantSearch } from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Pagination /> * </InstantSearch> * ); * } */ var Pagination$1 = connectPagination(PaginationComponent); /** * connectPoweredBy connector provides the logic to build a widget that * will display a link to algolia. * @name connectPoweredBy * @kind connector * @providedPropType {string} url - the url to redirect to algolia */ var connectPoweredBy = createConnector({ displayName: 'AlgoliaPoweredBy', propTypes: {}, getProvidedProps: function getProvidedProps(props) { var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + ('utm_content=' + (props.canRender ? location.hostname : '') + '&') + 'utm_campaign=poweredby'; return { url: url }; } }); var cx$12 = classNames('PoweredBy'); /* eslint-disable max-len */ var AlgoliaLogo = function AlgoliaLogo() { return React__default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', baseProfile: 'basic', viewBox: '0 0 1366 362' }, React__default.createElement( 'linearGradient', { id: 'g', x1: '428.258', x2: '434.145', y1: '404.15', y2: '409.85', gradientUnits: 'userSpaceOnUse', gradientTransform: 'matrix(94.045 0 0 -94.072 -40381.527 38479.52)' }, React__default.createElement('stop', { offset: '0', stopColor: '#00AEFF' }), React__default.createElement('stop', { offset: '1', stopColor: '#3369E7' }) ), React__default.createElement('path', { d: 'M61.8 15.4h242.8c23.9 0 43.4 19.4 43.4 43.4v242.9c0 23.9-19.4 43.4-43.4 43.4H61.8c-23.9 0-43.4-19.4-43.4-43.4v-243c0-23.9 19.4-43.3 43.4-43.3z', fill: 'url(#g)' }), React__default.createElement('path', { d: 'M187 98.7c-51.4 0-93.1 41.7-93.1 93.2S135.6 285 187 285s93.1-41.7 93.1-93.2-41.6-93.1-93.1-93.1zm0 158.8c-36.2 0-65.6-29.4-65.6-65.6s29.4-65.6 65.6-65.6 65.6 29.4 65.6 65.6-29.3 65.6-65.6 65.6zm0-117.8v48.9c0 1.4 1.5 2.4 2.8 1.7l43.4-22.5c1-.5 1.3-1.7.8-2.7-9-15.8-25.7-26.6-45-27.3-1 0-2 .8-2 1.9zm-60.8-35.9l-5.7-5.7c-5.6-5.6-14.6-5.6-20.2 0l-6.8 6.8c-5.6 5.6-5.6 14.6 0 20.2l5.6 5.6c.9.9 2.2.7 3-.2 3.3-4.5 6.9-8.8 10.9-12.8 4.1-4.1 8.3-7.7 12.9-11 1-.6 1.1-2 .3-2.9zM217.5 89V77.7c0-7.9-6.4-14.3-14.3-14.3h-33.3c-7.9 0-14.3 6.4-14.3 14.3v11.6c0 1.3 1.2 2.2 2.5 1.9 9.3-2.7 19.1-4.1 29-4.1 9.5 0 18.9 1.3 28 3.8 1.2.3 2.4-.6 2.4-1.9z', fill: '#FFFFFF' }), React__default.createElement('path', { d: 'M842.5 267.6c0 26.7-6.8 46.2-20.5 58.6-13.7 12.4-34.6 18.6-62.8 18.6-10.3 0-31.7-2-48.8-5.8l6.3-31c14.3 3 33.2 3.8 43.1 3.8 15.7 0 26.9-3.2 33.6-9.6s10-15.9 10-28.5v-6.4c-3.9 1.9-9 3.8-15.3 5.8-6.3 1.9-13.6 2.9-21.8 2.9-10.8 0-20.6-1.7-29.5-5.1-8.9-3.4-16.6-8.4-22.9-15-6.3-6.6-11.3-14.9-14.8-24.8s-5.3-27.6-5.3-40.6c0-12.2 1.9-27.5 5.6-37.7 3.8-10.2 9.2-19 16.5-26.3 7.2-7.3 16-12.9 26.3-17s22.4-6.7 35.5-6.7c12.7 0 24.4 1.6 35.8 3.5 11.4 1.9 21.1 3.9 29 6.1v155.2zm-108.7-77.2c0 16.4 3.6 34.6 10.8 42.2 7.2 7.6 16.5 11.4 27.9 11.4 6.2 0 12.1-.9 17.6-2.6 5.5-1.7 9.9-3.7 13.4-6.1v-97.1c-2.8-.6-14.5-3-25.8-3.3-14.2-.4-25 5.4-32.6 14.7-7.5 9.3-11.3 25.6-11.3 40.8zm294.3 0c0 13.2-1.9 23.2-5.8 34.1s-9.4 20.2-16.5 27.9c-7.1 7.7-15.6 13.7-25.6 17.9s-25.4 6.6-33.1 6.6c-7.7-.1-23-2.3-32.9-6.6-9.9-4.3-18.4-10.2-25.5-17.9-7.1-7.7-12.6-17-16.6-27.9s-6-20.9-6-34.1c0-13.2 1.8-25.9 5.8-36.7 4-10.8 9.6-20 16.8-27.7s15.8-13.6 25.6-17.8c9.9-4.2 20.8-6.2 32.6-6.2s22.7 2.1 32.7 6.2c10 4.2 18.6 10.1 25.6 17.8 7.1 7.7 12.6 16.9 16.6 27.7 4.2 10.8 6.3 23.5 6.3 36.7zm-40 .1c0-16.9-3.7-31-10.9-40.8-7.2-9.9-17.3-14.8-30.2-14.8-12.9 0-23 4.9-30.2 14.8-7.2 9.9-10.7 23.9-10.7 40.8 0 17.1 3.6 28.6 10.8 38.5 7.2 10 17.3 14.9 30.2 14.9 12.9 0 23-5 30.2-14.9 7.2-10 10.8-21.4 10.8-38.5zm127.1 86.4c-64.1.3-64.1-51.8-64.1-60.1L1051 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9zm68.9 0h-39.3V108.1l39.3-6.2v175zm-19.7-193.5c13.1 0 23.8-10.6 23.8-23.7S1177.6 36 1164.4 36s-23.8 10.6-23.8 23.7 10.7 23.7 23.8 23.7zm117.4 18.6c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4s8.9 13.5 11.1 21.7c2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6s-25.9 2.7-41.1 2.7c-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8s9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2s-10-3-16.7-3c-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1s19.5-2.6 30.3-2.6zm3.3 141.9c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18 5.9 3.6 13.7 5.3 23.6 5.3zM512.9 103c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4 5.3 5.8 8.9 13.5 11.1 21.7 2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6-12.2 1.8-25.9 2.7-41.1 2.7-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8 4.7.5 9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2-4.4-1.7-10-3-16.7-3-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1 9.4-1.8 19.5-2.6 30.3-2.6zm3.4 142c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18s13.7 5.3 23.6 5.3zm158.5 31.9c-64.1.3-64.1-51.8-64.1-60.1L610.6 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9z', fill: '#182359' }) ); }; /* eslint-enable max-len */ var PoweredBy = function (_Component) { inherits(PoweredBy, _Component); function PoweredBy() { classCallCheck(this, PoweredBy); return possibleConstructorReturn(this, (PoweredBy.__proto__ || Object.getPrototypeOf(PoweredBy)).apply(this, arguments)); } createClass(PoweredBy, [{ key: 'render', value: function render() { var _props = this.props, translate = _props.translate, url = _props.url; return React__default.createElement( 'div', cx$12('root'), React__default.createElement( 'span', cx$12('searchBy'), translate('searchBy'), ' ' ), React__default.createElement( 'a', _extends({ href: url, target: '_blank' }, cx$12('algoliaLink'), { 'aria-label': 'Algolia' }), React__default.createElement(AlgoliaLogo, null) ) ); } }]); return PoweredBy; }(React.Component); PoweredBy.propTypes = { url: propTypes.string.isRequired, translate: propTypes.func.isRequired }; var PoweredByComponent = translatable({ searchBy: 'Search by' })(PoweredBy); /** * PoweredBy displays an Algolia logo. * * Algolia requires that you use this widget if you are on a [community or free plan](https://www.algolia.com/pricing). * @name PoweredBy * @kind widget * @themeKey ais-PoweredBy__root - The root component of the widget * @themeKey ais-PoweredBy__searchBy - The powered by label * @themeKey ais-PoweredBy__algoliaLink - The algolia logo link * @translationKey searchBy - Label value for the powered by * @example * import React from 'react'; * * import { PoweredBy, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <PoweredBy /> * </InstantSearch> * ); * } */ var PoweredBy$1 = connectPoweredBy(PoweredByComponent); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsFinite = _root.isFinite; /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite$1(value) { return typeof value == 'number' && nativeIsFinite(value); } var _isFinite = isFinite$1; /** * connectRange connector provides the logic to create connected * components that will give the ability for a user to refine results using * a numeric range. * @name connectRange * @kind connector * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - Name of the attribute for faceting * @propType {{min: number, max: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {number} [precision=2] - Number of digits after decimal point to use. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {number} min - the minimum value available. * @providedPropType {number} max - the maximum value available. * @providedPropType {number} precision - Number of digits after decimal point to use. */ function getId$7(props) { return props.attributeName; } var namespace$3 = 'range'; function getCurrentRange(boundaries, stats, precision) { var pow = Math.pow(10, precision); var min = void 0; if (_isFinite(boundaries.min)) { min = boundaries.min; } else if (_isFinite(stats.min)) { min = stats.min; } else { min = undefined; } var max = void 0; if (_isFinite(boundaries.max)) { max = boundaries.max; } else if (_isFinite(stats.max)) { max = stats.max; } else { max = undefined; } return { min: min !== undefined ? Math.floor(min * pow) / pow : min, max: max !== undefined ? Math.ceil(max * pow) / pow : max }; } function getCurrentRefinement$6(props, searchState, currentRange, context) { var refinement = getCurrentRefinementValue(props, searchState, context, namespace$3 + '.' + getId$7(props), {}, function (currentRefinement) { var min = currentRefinement.min, max = currentRefinement.max; if (typeof min === 'string') { min = parseInt(min, 10); } if (typeof max === 'string') { max = parseInt(max, 10); } return { min: min, max: max }; }); var hasMinBound = props.min !== undefined; var hasMaxBound = props.max !== undefined; var hasMinRefinment = refinement.min !== undefined; var hasMaxRefinment = refinement.max !== undefined; if (hasMinBound && hasMinRefinment && refinement.min < currentRange.min) { throw Error("You can't provide min value lower than range."); } if (hasMaxBound && hasMaxRefinment && refinement.max > currentRange.max) { throw Error("You can't provide max value greater than range."); } if (hasMinBound && !hasMinRefinment) { refinement.min = currentRange.min; } if (hasMaxBound && !hasMaxRefinment) { refinement.max = currentRange.max; } return refinement; } function getCurrentRefinementWithRange(refinement, range) { return { min: refinement.min !== undefined ? refinement.min : range.min, max: refinement.max !== undefined ? refinement.max : range.max }; } function nextValueForRefinement(hasBound, isReset, range, value) { var next = void 0; if (!hasBound && range === value) { next = undefined; } else if (hasBound && isReset) { next = range; } else { next = value; } return next; } function _refine$4(props, searchState, nextRefinement, currentRange, context) { var nextMin = nextRefinement.min, nextMax = nextRefinement.max; var currentMinRange = currentRange.min, currentMaxRange = currentRange.max; var isMinReset = nextMin === undefined || nextMin === ''; var isMaxReset = nextMax === undefined || nextMax === ''; var nextMinAsNumber = !isMinReset ? parseFloat(nextMin) : undefined; var nextMaxAsNumber = !isMaxReset ? parseFloat(nextMax) : undefined; var isNextMinValid = isMinReset || _isFinite(nextMinAsNumber); var isNextMaxValid = isMaxReset || _isFinite(nextMaxAsNumber); if (!isNextMinValid || !isNextMaxValid) { throw Error("You can't provide non finite values to the range connector."); } if (nextMinAsNumber < currentMinRange) { throw Error("You can't provide min value lower than range."); } if (nextMaxAsNumber > currentMaxRange) { throw Error("You can't provide max value greater than range."); } var id = getId$7(props); var resetPage = true; var nextValue = defineProperty$2({}, id, { min: nextValueForRefinement(props.min !== undefined, isMinReset, currentMinRange, nextMinAsNumber), max: nextValueForRefinement(props.max !== undefined, isMaxReset, currentMaxRange, nextMaxAsNumber) }); return refineValue(searchState, nextValue, context, resetPage, namespace$3); } function _cleanUp$3(props, searchState, context) { return cleanUpValue(searchState, context, namespace$3 + '.' + getId$7(props)); } var connectRange = createConnector({ displayName: 'AlgoliaRange', propTypes: { id: propTypes.string, attributeName: propTypes.string.isRequired, defaultRefinement: propTypes.shape({ min: propTypes.number.isRequired, max: propTypes.number.isRequired }), min: propTypes.number, max: propTypes.number, precision: propTypes.number }, defaultProps: { precision: 2 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName, precision = props.precision, minBound = props.min, maxBound = props.max; var results = getResults(searchResults, this.context); var hasFacet = results && results.getFacetByName(attributeName); var stats = hasFacet ? results.getFacetStats(attributeName) || {} : {}; var facetValues = hasFacet ? results.getFacetValues(attributeName) : []; var count = facetValues.map(function (v) { return { value: v.name, count: v.count }; }); var _getCurrentRange = getCurrentRange({ min: minBound, max: maxBound }, stats, precision), rangeMin = _getCurrentRange.min, rangeMax = _getCurrentRange.max; // The searchState is not always in sync with the helper state. For example // when we set boundaries on the first render the searchState don't have // the correct refinement. If this behaviour change in the upcoming version // we could store the range inside the searchState instead of rely on `this`. this._currentRange = { min: rangeMin, max: rangeMax }; var currentRefinement = getCurrentRefinement$6(props, searchState, this._currentRange, this.context); return { min: rangeMin, max: rangeMax, canRefine: count.length > 0, currentRefinement: getCurrentRefinementWithRange(currentRefinement, this._currentRange), count: count, precision: precision }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$4(props, searchState, nextRefinement, this._currentRange, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$3(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attributeName = props.attributeName; var _getCurrentRefinement = getCurrentRefinement$6(props, searchState, this._currentRange, this.context), min = _getCurrentRefinement.min, max = _getCurrentRefinement.max; params = params.addDisjunctiveFacet(attributeName); if (min !== undefined) { params = params.addNumericRefinement(attributeName, '>=', min); } if (max !== undefined) { params = params.addNumericRefinement(attributeName, '<=', max); } return params; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var _currentRange = this._currentRange, minRange = _currentRange.min, maxRange = _currentRange.max; var _getCurrentRefinement2 = getCurrentRefinement$6(props, searchState, this._currentRange, this.context), minValue = _getCurrentRefinement2.min, maxValue = _getCurrentRefinement2.max; var items = []; var hasMin = minValue !== undefined; var hasMax = maxValue !== undefined; var shouldDisplayMinLabel = hasMin && minValue !== minRange; var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange; if (shouldDisplayMinLabel || shouldDisplayMaxLabel) { var fragments = [hasMin ? minValue + ' <= ' : '', props.attributeName, hasMax ? ' <= ' + maxValue : '']; items.push({ label: fragments.join(''), attributeName: props.attributeName, value: function value(nextState) { return _refine$4(props, nextState, {}, _this._currentRange, _this.context); }, currentRefinement: getCurrentRefinementWithRange({ min: minValue, max: maxValue }, { min: minRange, max: maxRange }) }); } return { id: getId$7(props), index: getIndex(this.context), items: items }; } }); var cx$13 = classNames('RangeInput'); var RawRangeInput = function (_Component) { inherits(RawRangeInput, _Component); function RawRangeInput(props) { classCallCheck(this, RawRangeInput); var _this = possibleConstructorReturn(this, (RawRangeInput.__proto__ || Object.getPrototypeOf(RawRangeInput)).call(this, props)); _this.onSubmit = function (e) { e.preventDefault(); _this.props.refine({ min: _this.state.from, max: _this.state.to }); }; _this.state = _this.normalizeStateForRendering(props); return _this; } createClass(RawRangeInput, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) { this.context.canRefine(this.props.canRefine); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { // In [email protected] the call to setState on the inputs trigger this lifecycle hook // because the context has changed (for react). I don't think that the bug is related // to react because I failed to reproduce it with a simple hierarchy of components. // The workaround here is to check the differences between previous & next props in order // to avoid to override current state when values are not yet refined. In the react documentation, // they DON'T categorically say that setState never run componentWillReceiveProps. // see: https://reactjs.org/docs/react-component.html#componentwillreceiveprops if (nextProps.canRefine && (this.props.canRefine !== nextProps.canRefine || this.props.currentRefinement.min !== nextProps.currentRefinement.min || this.props.currentRefinement.max !== nextProps.currentRefinement.max)) { this.setState(this.normalizeStateForRendering(nextProps)); } if (this.context.canRefine && this.props.canRefine !== nextProps.canRefine) { this.context.canRefine(nextProps.canRefine); } } }, { key: 'normalizeStateForRendering', value: function normalizeStateForRendering(props) { var canRefine = props.canRefine, rangeMin = props.min, rangeMax = props.max; var _props$currentRefinem = props.currentRefinement, valueMin = _props$currentRefinem.min, valueMax = _props$currentRefinem.max; return { from: canRefine && valueMin !== undefined && valueMin !== rangeMin ? valueMin : '', to: canRefine && valueMax !== undefined && valueMax !== rangeMax ? valueMax : '' }; } }, { key: 'normalizeRangeForRendering', value: function normalizeRangeForRendering(_ref) { var canRefine = _ref.canRefine, min = _ref.min, max = _ref.max; var hasMin = min !== undefined; var hasMax = max !== undefined; return { min: canRefine && hasMin && hasMax ? min : '', max: canRefine && hasMin && hasMax ? max : '' }; } }, { key: 'render', value: function render() { var _this2 = this; var _state = this.state, from = _state.from, to = _state.to; var _props = this.props, precision = _props.precision, translate = _props.translate, canRefine = _props.canRefine; var _normalizeRangeForRen = this.normalizeRangeForRendering(this.props), min = _normalizeRangeForRen.min, max = _normalizeRangeForRen.max; var step = 1 / Math.pow(10, precision); return React__default.createElement( 'form', _extends({}, cx$13('root', !canRefine && 'noRefinement'), { onSubmit: this.onSubmit }), React__default.createElement( 'fieldset', _extends({ disabled: !canRefine }, cx$13('fieldset')), React__default.createElement( 'label', cx$13('labelMin'), React__default.createElement('input', _extends({}, cx$13('inputMin'), { type: 'number', min: min, max: max, value: from, step: step, placeholder: min, onChange: function onChange(e) { return _this2.setState({ from: e.currentTarget.value }); } })) ), React__default.createElement( 'span', cx$13('separator'), translate('separator') ), React__default.createElement( 'label', cx$13('labelMax'), React__default.createElement('input', _extends({}, cx$13('inputMax'), { type: 'number', min: min, max: max, value: to, step: step, placeholder: max, onChange: function onChange(e) { return _this2.setState({ to: e.currentTarget.value }); } })) ), React__default.createElement( 'button', _extends({}, cx$13('submit'), { type: 'submit' }), translate('submit') ) ) ); } }]); return RawRangeInput; }(React.Component); RawRangeInput.propTypes = { canRefine: propTypes.bool.isRequired, precision: propTypes.number.isRequired, translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, min: propTypes.number, max: propTypes.number, currentRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }) }; RawRangeInput.defaultProps = { currentRefinement: {} }; RawRangeInput.contextTypes = { canRefine: propTypes.func }; var RangeInputComponent = translatable({ submit: 'ok', separator: 'to' })(RawRangeInput); /** * RangeInput allows a user to select a numeric range using a minimum and maximum input. * @name RangeInput * @kind widget * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - the name of the attribute in the record * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {number} [precision=2] - Number of digits after decimal point to use. * @themeKey ais-RangeInput__root - The root component of the widget * @themeKey ais-RangeInput__labelMin - The label for the min input * @themeKey ais-RangeInput__inputMin - The min input * @themeKey ais-RangeInput__separator - The separator between input * @themeKey ais-RangeInput__labelMax - The label for the max input * @themeKey ais-RangeInput__inputMax - The max input * @themeKey ais-RangeInput__submit - The submit button * @themeKey ais-RangeInput__noRefinement - present when there is no refinement * @translationKey submit - Label value for the submit button * @translationKey separator - Label value for the input separator * @example * import React from 'react'; * * import { RangeInput, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RangeInput attributeName="price"/> * </InstantSearch> * ); * } */ var RangeInput = connectRange(RangeInputComponent); /** * Since a lot of sliders already exist, we did not include one by default. * However you can easily connect React InstantSearch to an existing one * using the [connectRange connector](connectors/connectRange.html). * * @name RangeSlider * @requirements To connect any slider to Algolia, the underlying attribute used must be holding numerical values. * @kind widget * @example * * // Here's an example showing how to connect the airbnb rheostat slider to React InstantSearch using the * // range connector import PropTypes from 'prop-types'; import React, {Component} from 'react'; import {connectRange} from 'react-instantsearch/connectors'; import Rheostat from 'rheostat'; class Range extends React.Component { static propTypes = { min: PropTypes.number, max: PropTypes.number, currentRefinement: PropTypes.object, refine: PropTypes.func.isRequired, canRefine: PropTypes.bool.isRequired, }; state = {currentValues: {min: this.props.min, max: this.props.max}}; componentWillReceiveProps(sliderState) { if (sliderState.canRefine) { this.setState({currentValues: {min: sliderState.currentRefinement.min, max: sliderState.currentRefinement.max}}); } } onValuesUpdated = (sliderState) => { this.setState({currentValues: {min: sliderState.values[0], max: sliderState.values[1]}}); }; onChange = (sliderState) => { if (this.props.currentRefinement.min !== sliderState.values[0] || this.props.currentRefinement.max !== sliderState.values[1]) { this.props.refine({min: sliderState.values[0], max: sliderState.values[1]}); } }; render() { const {min, max, currentRefinement} = this.props; const {currentValues} = this.state; return min !== max ? <div> <Rheostat min={min} max={max} values={[currentRefinement.min, currentRefinement.max]} onChange={this.onChange} onValuesUpdated={this.onValuesUpdated} /> <div style={{display: 'flex', justifyContent: 'space-between'}}> <div>{currentValues.min}</div> <div>{currentValues.max}</div> </div> </div> : null; } } const ConnectedRange = connectRange(Range); */ var RangeSlider = connectRange(function () { return React__default.createElement( 'div', null, 'We do not provide any Slider, see the documentation to learn how to connect one easily:', React__default.createElement( 'a', { target: '_blank', rel: 'noopener noreferrer', href: 'https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html' }, 'https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html' ) ); }); var cx$14 = classNames('StarRating'); var StarRating = function (_Component) { inherits(StarRating, _Component); function StarRating() { classCallCheck(this, StarRating); return possibleConstructorReturn(this, (StarRating.__proto__ || Object.getPrototypeOf(StarRating)).apply(this, arguments)); } createClass(StarRating, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'onClick', value: function onClick(min, max, e) { e.preventDefault(); e.stopPropagation(); if (min === this.props.currentRefinement.min && max === this.props.currentRefinement.max) { this.props.refine({ min: this.props.min, max: this.props.max }); } else { this.props.refine({ min: min, max: max }); } } }, { key: 'buildItem', value: function buildItem(_ref) { var max = _ref.max, lowerBound = _ref.lowerBound, count = _ref.count, translate = _ref.translate, createURL = _ref.createURL, isLastSelectableItem = _ref.isLastSelectableItem; var disabled = !count; var isCurrentMinLower = this.props.currentRefinement.min < lowerBound; var selected = isLastSelectableItem && isCurrentMinLower || !disabled && lowerBound === this.props.currentRefinement.min && max === this.props.currentRefinement.max; var icons = []; for (var icon = 0; icon < max; icon++) { var iconTheme = icon >= lowerBound ? 'ratingIconEmpty' : 'ratingIcon'; icons.push(React__default.createElement('span', _extends({ key: icon }, cx$14(iconTheme, selected && iconTheme + 'Selected', disabled && iconTheme + 'Disabled')))); } // The last item of the list (the default item), should not // be clickable if it is selected. var isLastAndSelect = isLastSelectableItem && selected; var StarsWrapper = isLastAndSelect ? 'div' : 'a'; var onClickHandler = isLastAndSelect ? {} : { href: createURL({ min: lowerBound, max: max }), onClick: this.onClick.bind(this, lowerBound, max) }; return React__default.createElement( StarsWrapper, _extends({}, cx$14('ratingLink', selected && 'ratingLinkSelected', disabled && 'ratingLinkDisabled'), { disabled: disabled, key: lowerBound }, onClickHandler), icons, React__default.createElement( 'span', cx$14('ratingLabel', selected && 'ratingLabelSelected', disabled && 'ratingLabelDisabled'), translate('ratingLabel') ), React__default.createElement( 'span', null, ' ' ), React__default.createElement( 'span', cx$14('ratingCount', selected && 'ratingCountSelected', disabled && 'ratingCountDisabled'), count ) ); } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props, min = _props.min, max = _props.max, translate = _props.translate, count = _props.count, createURL = _props.createURL, canRefine = _props.canRefine; // min & max are always set when there is a results, otherwise it means // that we don't want to render anything since we don't have any values. var limitMin = min !== undefined && min >= 0 ? min : 0; var limitMax = max !== undefined && max >= 0 ? max : -1; var inclusiveLength = limitMax - limitMin + 1; var safeInclusiveLength = Math.max(inclusiveLength, 0); var values = count.map(function (item) { return _extends({}, item, { value: parseFloat(item.value) }); }).filter(function (item) { return item.value >= limitMin && item.value <= limitMax; }); var range = new Array(safeInclusiveLength).fill(null).map(function (_, index) { var element = values.find(function (item) { return item.value === limitMax - index; }); var placeholder = { value: limitMax - index, count: 0, total: 0 }; return element || placeholder; }).reduce(function (acc, item, index) { return acc.concat(_extends({}, item, { total: index === 0 ? item.count : acc[index - 1].total + item.count })); }, []); var items = range.map(function (item, index) { return _this2.buildItem({ lowerBound: item.value, count: item.total, isLastSelectableItem: range.length - 1 === index, max: limitMax, translate: translate, createURL: createURL }); }); return React__default.createElement( 'div', cx$14('root', !canRefine && 'noRefinement'), items ); } }]); return StarRating; }(React.Component); StarRating.propTypes = { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, min: propTypes.number, max: propTypes.number, currentRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }), count: propTypes.arrayOf(propTypes.shape({ value: propTypes.string, count: propTypes.number })), canRefine: propTypes.bool.isRequired }; StarRating.contextTypes = { canRefine: propTypes.func }; var StarRatingComponent = translatable({ ratingLabel: ' & Up' })(StarRating); /** * StarRating lets the user refine search results by clicking on stars. * * The stars are based on the selected `attributeName`. * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @name StarRating * @kind widget * @propType {string} attributeName - the name of the attribute in the record * @propType {number} [min] - Minimum value for the rating. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value for the rating. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the lower bound (end) and the max for the rating. * @themeKey ais-StarRating__root - The root component of the widget * @themeKey ais-StarRating__ratingLink - The item link * @themeKey ais-StarRating__ratingLinkSelected - The selected link item * @themeKey ais-StarRating__ratingLinkDisabled - The disabled link item * @themeKey ais-StarRating__ratingIcon - The rating icon * @themeKey ais-StarRating__ratingIconSelected - The selected rating icon * @themeKey ais-StarRating__ratingIconDisabled - The disabled rating icon * @themeKey ais-StarRating__ratingIconEmpty - The rating empty icon * @themeKey ais-StarRating__ratingIconEmptySelected - The selected rating empty icon * @themeKey ais-StarRating__ratingIconEmptyDisabled - The disabled rating empty icon * @themeKey ais-StarRating__ratingLabel - The link label * @themeKey ais-StarRating__ratingLabelSelected - The selected link label * @themeKey ais-StarRating__ratingLabelDisabled - The disabled link label * @themeKey ais-StarRating__ratingCount - The link count * @themeKey ais-StarRating__ratingCountSelected - The selected link count * @themeKey ais-StarRating__ratingCountDisabled - The disabled link count * @themeKey ais-StarRating__noRefinement - present when there is no refinement * @translationKey ratingLabel - Label value for the rating link * @example * import React from 'react'; * * import { StarRating, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <StarRating attributeName="rating" /> * </InstantSearch> * ); * } */ var StarRating$1 = connectRange(StarRatingComponent); var namespace$4 = 'refinementList'; function getId$8(props) { return props.attributeName; } function getCurrentRefinement$7(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$4 + '.' + getId$8(props), [], function (currentRefinement) { if (typeof currentRefinement === 'string') { // All items were unselected if (currentRefinement === '') { return []; } // Only one item was in the searchState but we know it should be an array return [currentRefinement]; } return currentRefinement; }); } function getValue$4(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$7(props, searchState, context); var isAnewValue = currentRefinement.indexOf(name) === -1; var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates : currentRefinement.filter(function (selectedValue) { return selectedValue !== name; }); // cannot use .splice(), it mutates return nextRefinement; } function getLimit$1(_ref) { var showMore = _ref.showMore, limitMin = _ref.limitMin, limitMax = _ref.limitMax; return showMore ? limitMax : limitMin; } function _refine$5(props, searchState, nextRefinement, context) { var id = getId$8(props); // Setting the value to an empty string ensures that it is persisted in // the URL as an empty value. // This is necessary in the case where `defaultRefinement` contains one // item and we try to deselect it. `nextSelected` would be an empty array, // which would not be persisted to the URL. // {foo: ['bar']} => "foo[0]=bar" // {foo: []} => "" var nextValue = defineProperty$2({}, id, nextRefinement.length > 0 ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$4); } function _cleanUp$4(props, searchState, context) { return cleanUpValue(searchState, context, namespace$4 + '.' + getId$8(props)); } /** * connectRefinementList connector provides the logic to build a widget that will * give the user the ability to choose multiple values for a specific facet. * @name connectRefinementList * @kind connector * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [withSearchBox=false] - allow search inside values * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of displayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var sortBy$2 = ['isRefined', 'count:desc', 'name:asc']; var connectRefinementList = createConnector({ displayName: 'AlgoliaRefinementList', propTypes: { id: propTypes.string, attributeName: propTypes.string.isRequired, operator: propTypes.oneOf(['and', 'or']), showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), withSearchBox: propTypes.bool, searchForFacetValues: propTypes.bool, // @deprecated transformItems: propTypes.func }, defaultProps: { operator: 'or', showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) { var _this = this; var attributeName = props.attributeName; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== ''); var withSearchBox = props.withSearchBox || props.searchForFacetValues; if (props.withSearchBox && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$7(props, searchState, this.context), canRefine: canRefine, isFromSearch: isFromSearch, withSearchBox: withSearchBox }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue$4(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy$2 }).map(function (v) { return { label: v.name, value: getValue$4(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit$1(props)), currentRefinement: getCurrentRefinement$7(props, searchState, this.context), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$5(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement, maxFacetHits: getLimit$1(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$4(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName, operator = props.operator; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = addKey + 'Refinement'; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props)) }); searchParameters = searchParameters[addKey](attributeName); return getCurrentRefinement$7(props, searchState, this.context).reduce(function (res, val) { return res[addRefinementKey](attributeName, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId$8(props); var context = this.context; return { id: id, index: getIndex(this.context), items: getCurrentRefinement$7(props, searchState, context).length > 0 ? [{ attributeName: props.attributeName, label: props.attributeName + ': ', currentRefinement: getCurrentRefinement$7(props, searchState, context), value: function value(nextState) { return _refine$5(props, nextState, [], context); }, items: getCurrentRefinement$7(props, searchState, context).map(function (item) { return { label: '' + item, value: function value(nextState) { var nextSelectedItems = getCurrentRefinement$7(props, nextState, context).filter(function (other) { return other !== item; }); return _refine$5(props, searchState, nextSelectedItems, context); } }; }) }] : [] }; } }); var cx$15 = classNames('RefinementList'); var RefinementList$3 = function (_Component) { inherits(RefinementList, _Component); function RefinementList(props) { classCallCheck(this, RefinementList); var _this = possibleConstructorReturn(this, (RefinementList.__proto__ || Object.getPrototypeOf(RefinementList)).call(this, props)); _this.selectItem = function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }; _this.renderItem = function (item, resetQuery) { var label = _this.props.isFromSearch ? React__default.createElement(Highlight$2, { attributeName: 'label', hit: item }) : item.label; return React__default.createElement( 'label', null, React__default.createElement('input', _extends({}, cx$15('itemCheckbox', item.isRefined && 'itemCheckboxSelected'), { type: 'checkbox', checked: item.isRefined, onChange: function onChange() { return _this.selectItem(item, resetQuery); } })), React__default.createElement('span', cx$15('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')), React__default.createElement( 'span', cx$15('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'), label ), ' ', React__default.createElement( 'span', cx$15('itemCount', item.isRefined && 'itemCountSelected'), item.count.toLocaleString() ) ); }; _this.state = { query: '' }; return _this; } createClass(RefinementList, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return React__default.createElement( 'div', null, React__default.createElement(List, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$15 }, pick_1(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine']), { query: this.state.query })) ); } }]); return RefinementList; }(React.Component); RefinementList$3.propTypes = { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, searchForItems: propTypes.func.isRequired, withSearchBox: propTypes.bool, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.arrayOf(propTypes.string).isRequired, count: propTypes.number.isRequired, isRefined: propTypes.bool.isRequired })), isFromSearch: propTypes.bool.isRequired, canRefine: propTypes.bool.isRequired, showMore: propTypes.bool, limitMin: propTypes.number, limitMax: propTypes.number, transformItems: propTypes.func }; RefinementList$3.contextTypes = { canRefine: propTypes.func }; var RefinementListComponent = translatable({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(RefinementList$3); /** * The RefinementList component displays a list that let the end user choose multiple values for a specific facet. * @name RefinementList * @kind widget * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/). * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of displayed items * @propType {number} [limitMax=20] - the maximum number of displayed items. Only used when showMore is set to `true` * @propType {string[]} [defaultRefinement] - the values of the items selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-RefinementList__root - the root of the component * @themeKey ais-RefinementList__items - the container of all items in the list * @themeKey ais-RefinementList__itemSelected - the selected list item * @themeKey ais-RefinementList__itemCheckbox - the item checkbox * @themeKey ais-RefinementList__itemCheckboxSelected - the selected item checkbox * @themeKey ais-RefinementList__itemLabel - the item label * @themeKey ais-RefinementList__itemLabelSelected - the selected item label * @themeKey ais-RefinementList__itemCount - the item count * @themeKey ais-RefinementList__itemCountSelected - the selected item count * @themeKey ais-RefinementList__showMore - the button that let the user toggle more results * @themeKey ais-RefinementList__noRefinement - present when there is no refinement * @themeKey ais-RefinementList__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * If you are using the `withSearchBox` prop, you'll also need to make the attribute searchable using * the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values). * @example * import React from 'react'; * * import { RefinementList, InstantSearch } from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RefinementList attributeName="colors" /> * </InstantSearch> * ); * } */ var RefinementList$4 = connectRefinementList(RefinementListComponent); var cx$16 = classNames('ClearAll'); var ClearAll = function (_Component) { inherits(ClearAll, _Component); function ClearAll() { classCallCheck(this, ClearAll); return possibleConstructorReturn(this, (ClearAll.__proto__ || Object.getPrototypeOf(ClearAll)).apply(this, arguments)); } createClass(ClearAll, [{ key: 'render', value: function render() { var _props = this.props, translate = _props.translate, items = _props.items, refine = _props.refine; var isDisabled = items.length === 0; if (isDisabled) { return React__default.createElement( 'button', _extends({}, cx$16('root'), { disabled: true }), translate('reset') ); } return React__default.createElement( 'button', _extends({}, cx$16('root'), { onClick: function onClick() { return refine(items); } }), translate('reset') ); } }]); return ClearAll; }(React.Component); ClearAll.propTypes = { translate: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.object).isRequired, refine: propTypes.func.isRequired }; var ClearAllComponent = translatable({ reset: 'Clear all filters' })(ClearAll); /** * The ClearAll widget displays a button that lets the user clean every refinement applied * to the search. * @name ClearAll * @kind widget * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {boolean} [clearsQuery=false] - Pass true to also clear the search query * @themeKey ais-ClearAll__root - the widget button * @translationKey reset - the clear all button value * @example * import React from 'react'; * * import { ClearAll, RefinementList, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ClearAll /> * <RefinementList attributeName="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ var ClearAll$1 = connectCurrentRefinements(ClearAllComponent); /** * connectScrollTo connector provides the logic to build a widget that will * let the page scroll to a certain point. * @name connectScrollTo * @kind connector * @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget. * @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo * @providedPropType {boolean} hasNotChanged - indicates whether the refinement came from the scrollOn argument (for instance page by default) */ var connectScrollTo = createConnector({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: propTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = getCurrentRefinementValue(props, searchState, this.context, id, null, function (currentRefinement) { return currentRefinement; }); if (!this._prevSearchState) { this._prevSearchState = {}; } /* Get the subpart of the state that interest us*/ if (hasMultipleIndex(this.context)) { var index = getIndex(this.context); searchState = searchState.indices ? searchState.indices[index] : {}; } /* if there is a change in the app that has been triggered by another element than "props.scrollOn (id) or the Configure widget, we need to keep track of the search state to know if there's a change in the app that was not triggered by the props.scrollOn (id) or the Configure widget. This is useful when using ScrollTo in combination of Pagination. As pagination can be change by every widget, we want to scroll only if it cames from the pagination widget itself. We also remove the configure key from the search state to do this comparaison because for now configure values are not present in the search state before a first refinement has been made and will false the results. See: https://github.com/algolia/react-instantsearch/issues/164 */ var cleanedSearchState = omit_1(omit_1(searchState, 'configure'), id); var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState); this._prevSearchState = cleanedSearchState; return { value: value, hasNotChanged: hasNotChanged }; } }); var cx$17 = classNames('ScrollTo'); var ScrollTo = function (_Component) { inherits(ScrollTo, _Component); function ScrollTo() { classCallCheck(this, ScrollTo); return possibleConstructorReturn(this, (ScrollTo.__proto__ || Object.getPrototypeOf(ScrollTo)).apply(this, arguments)); } createClass(ScrollTo, [{ key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { var _props = this.props, value = _props.value, hasNotChanged = _props.hasNotChanged; if (value !== prevProps.value && hasNotChanged) { this.el.scrollIntoView(); } } }, { key: 'render', value: function render() { var _this2 = this; return React__default.createElement( 'div', _extends({ ref: function ref(_ref) { return _this2.el = _ref; } }, cx$17('root')), this.props.children ); } }]); return ScrollTo; }(React.Component); ScrollTo.propTypes = { value: propTypes.any, children: propTypes.node, hasNotChanged: propTypes.bool }; /** * The ScrollTo component will make the page scroll to the component wrapped by it when one of the * [search state](guide/Search_state.html) prop is updated. By default when the page number changes, * the scroll goes to the wrapped component. * * @name ScrollTo * @kind widget * @propType {string} [scrollOn="page"] - Widget state key on which to listen for changes. * @example * import React from 'react'; * * import { ScrollTo, Hits, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ScrollTo> * <Hits /> * </ScrollTo> * </InstantSearch> * ); * } */ var ScrollTo$1 = connectScrollTo(ScrollTo); function getId$9() { return 'query'; } function getCurrentRefinement$8(props, searchState, context) { var id = getId$9(props); return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function _refine$6(props, searchState, nextRefinement, context) { var id = getId$9(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage); } function _cleanUp$5(props, searchState, context) { return cleanUpValue(searchState, context, getId$9()); } /** * connectSearchBox connector provides the logic to build a widget that will * let the user search for a query. * @name connectSearchBox * @kind connector * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the query to search for. * @providedPropType {boolean} isSearchStalled - a flag that indicates if react-is has detected that searches are stalled. */ var connectSearchBox = createConnector({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: propTypes.string }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { currentRefinement: getCurrentRefinement$8(props, searchState, this.context), isSearchStalled: searchResults.isSearchStalled }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$6(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$5(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$8(props, searchState, this.context)); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$9(props); var currentRefinement = getCurrentRefinement$8(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: id + ': ' + currentRefinement, value: function value(nextState) { return _refine$6(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); /** * The SearchBox component displays a search box that lets the user search for a specific query. * @name SearchBox * @kind widget * @propType {string[]} [focusShortcuts=['s','/']] - List of keyboard shortcuts that focus the search box. Accepts key names and key codes. * @propType {boolean} [autoFocus=false] - Should the search box be focused on render? * @propType {boolean} [searchAsYouType=true] - Should we search on every change to the query? If you disable this option, new searches will only be triggered by clicking the search button or by pressing the enter key while the search box is focused. * @propType {function} [onSubmit] - Intercept submit event sent from the SearchBox form container. * @propType {function} [onReset] - Listen to `reset` event sent from the SearchBox form container. * @propType {function} [on*] - Listen to any events sent form the search input itself. * @propType {React.Element} [submitComponent] - Change the apparence of the default submit button (magnifying glass). * @propType {React.Element} [resetComponent] - Change the apparence of the default reset button (cross). * @propType {React.Element} [loadingIndicatorComponent] - Change the apparence of the default loading indicator (spinning circle). * @propType {string} [defaultRefinement] - Provide default refinement value when component is mounted. * @propType {boolean} [showLoadingIndicator=false] - Display that the search is loading. This only happens after a certain amount of time to avoid a blinking effect. This timer can be configured with `stalledSearchDelay` props on <InstantSearch>. By default, the value is 200ms. * @themeKey ais-SearchBox__root - the root of the component * @themeKey ais-SearchBox__wrapper - the search box wrapper * @themeKey ais-SearchBox__input - the search box input * @themeKey ais-SearchBox__submit - the submit button * @themeKey ais-SearchBox__reset - the reset button * @themeKey ais-SearchBox__loading-indicator - the loading indicator * @translationkey submitTitle - The submit button title * @translationkey resetTitle - The reset button title * @translationkey placeholder - The label of the input placeholder * @example * import React from 'react'; * * import { SearchBox, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox /> * </InstantSearch> * ); * } */ var SearchBox$1 = connectSearchBox(SearchBoxComponent); function getId$10() { return 'sortBy'; } function getCurrentRefinement$9(props, searchState, context) { var id = getId$10(props); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return null; }); } /** * The connectSortBy connector provides the logic to build a widget that will * display a list of indices. This allows a user to change how the hits are being sorted. * @name connectSortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind connector * @propType {string} defaultRefinement - The default selected index. * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectSortBy = createConnector({ displayName: 'AlgoliaSortBy', propTypes: { defaultRefinement: propTypes.string, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$9(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId$10(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$10()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement$9(props, searchState, this.context); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId$10() }; } }); var cx$18 = classNames('SortBy'); var SortBy = function (_Component) { inherits(SortBy, _Component); function SortBy() { classCallCheck(this, SortBy); return possibleConstructorReturn(this, (SortBy.__proto__ || Object.getPrototypeOf(SortBy)).apply(this, arguments)); } createClass(SortBy, [{ key: 'render', value: function render() { var _props = this.props, refine = _props.refine, items = _props.items, currentRefinement = _props.currentRefinement; return React__default.createElement(Select, { cx: cx$18, selectedItem: currentRefinement, onSelect: refine, items: items }); } }]); return SortBy; }(React.Component); SortBy.propTypes = { refine: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, currentRefinement: propTypes.string.isRequired, transformItems: propTypes.func }; /** * The SortBy component displays a list of indexes allowing a user to change the hits are sorting. * @name SortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind widget * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {string} defaultRefinement - The default selected index. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-SortBy__root - the root of the component * @example * import React from 'react'; * * import { SortBy, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SortBy * items={[ * { value: 'ikea', label: 'Featured' }, * { value: 'ikea_price_asc', label: 'Price asc.' }, * { value: 'ikea_price_desc', label: 'Price desc.' }, * ]} * defaultRefinement="ikea" * /> * </InstantSearch> * ); * } */ var SortBy$1 = connectSortBy(SortBy); /** * connectStats connector provides the logic to build a widget that will * displays algolia search statistics (hits number and processing time). * @name connectStats * @kind connector * @providedPropType {number} nbHits - number of hits returned by Algolia. * @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results. */ var connectStats = createConnector({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); var cx$19 = classNames('Stats'); var Stats = function (_Component) { inherits(Stats, _Component); function Stats() { classCallCheck(this, Stats); return possibleConstructorReturn(this, (Stats.__proto__ || Object.getPrototypeOf(Stats)).apply(this, arguments)); } createClass(Stats, [{ key: 'render', value: function render() { var _props = this.props, translate = _props.translate, nbHits = _props.nbHits, processingTimeMS = _props.processingTimeMS; return React__default.createElement( 'span', cx$19('root'), translate('stats', nbHits, processingTimeMS) ); } }]); return Stats; }(React.Component); Stats.propTypes = { translate: propTypes.func.isRequired, nbHits: propTypes.number.isRequired, processingTimeMS: propTypes.number.isRequired }; var StatsComponent = translatable({ stats: function stats(n, ms) { return n.toLocaleString() + ' results found in ' + ms.toLocaleString() + 'ms'; } })(Stats); /** * The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server). * @name Stats * @kind widget * @themeKey ais-Stats__root - the root of the component * @translationkey stats - The string displayed by the stats widget. You get function(n, ms) and you need to return a string. n is a number of hits retrieved, ms is a processed time. * @example * import React from 'react'; * * import { Stats, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Stats /> * </InstantSearch> * ); * } */ var Stats$1 = connectStats(StatsComponent); function getId$11(props) { return props.attributeName; } var namespace$5 = 'toggle'; function getCurrentRefinement$10(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$5 + '.' + getId$11(props), false, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return false; }); } function _refine$7(props, searchState, nextRefinement, context) { var id = getId$11(props); var nextValue = defineProperty$2({}, id, nextRefinement ? nextRefinement : false); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$5); } function _cleanUp$6(props, searchState, context) { return cleanUpValue(searchState, context, namespace$5 + '.' + getId$11(props)); } /** * connectToggle connector provides the logic to build a widget that will * provides an on/off filtering feature based on an attribute value. * @name connectToggle * @kind connector * @requirements To use this widget, you'll need an attribute to toggle on. * * You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an * extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details. * * @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {string} value - Value of the refinement to apply on `attributeName`. * @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default? * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {boolean} currentRefinement - `true` when the refinement is applied, `false` otherwise */ var connectToggle = createConnector({ displayName: 'AlgoliaToggle', propTypes: { label: propTypes.string, filter: propTypes.func, attributeName: propTypes.string, value: propTypes.any, defaultRefinement: propTypes.bool }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$10(props, searchState, this.context); return { currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$7(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$6(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName, value = props.value, filter = props.filter; var checked = getCurrentRefinement$10(props, searchState, this.context); if (checked) { if (attributeName) { searchParameters = searchParameters.addFacet(attributeName).addFacetRefinement(attributeName, value); } if (filter) { searchParameters = filter(searchParameters); } } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$11(props); var checked = getCurrentRefinement$10(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (checked) { items.push({ label: props.label, currentRefinement: checked, attributeName: props.attributeName, value: function value(nextState) { return _refine$7(props, nextState, false, _this.context); } }); } return { id: id, index: index, items: items }; } }); var cx$20 = classNames('Toggle'); var Toggle = function (_Component) { inherits(Toggle, _Component); function Toggle() { var _ref; var _temp, _this, _ret; classCallCheck(this, Toggle); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Toggle.__proto__ || Object.getPrototypeOf(Toggle)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.refine(e.target.checked); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(Toggle, [{ key: 'render', value: function render() { var _props = this.props, currentRefinement = _props.currentRefinement, label = _props.label; return React__default.createElement( 'label', cx$20('root'), React__default.createElement('input', _extends({}, cx$20('checkbox'), { type: 'checkbox', checked: currentRefinement, onChange: this.onChange })), React__default.createElement( 'span', cx$20('label'), label ) ); } }]); return Toggle; }(React.Component); Toggle.propTypes = { currentRefinement: propTypes.bool.isRequired, refine: propTypes.func.isRequired, label: propTypes.string.isRequired }; /** * The Toggle provides an on/off filtering feature based on an attribute value. * @name Toggle * @kind widget * @requirements To use this widget, you'll need an attribute to toggle on. * * You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an * extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details. * * @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {any} value - Value of the refinement to apply on `attributeName` when checked. * @propType {boolean} [defaultRefinement=false] - Default state of the widget. Should the toggle be checked by default? * @themeKey ais-Toggle__root - the root of the component * @themeKey ais-Toggle__checkbox - the toggle checkbox * @themeKey ais-Toggle__label - the toggle label * @example * import React from 'react'; * * import { Toggle, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Toggle * attributeName="materials" * label="Made with solid pine" * value={'Solid pine'} * /> * </InstantSearch> * ); * } */ var Toggle$1 = connectToggle(Toggle); var cx$21 = classNames('Panel'); var Panel = function (_Component) { inherits(Panel, _Component); createClass(Panel, [{ key: 'getChildContext', value: function getChildContext() { return { canRefine: this.canRefine }; } }]); function Panel(props) { classCallCheck(this, Panel); var _this = possibleConstructorReturn(this, (Panel.__proto__ || Object.getPrototypeOf(Panel)).call(this, props)); _this.canRefine = function (canRefine) { _this.setState({ canRefine: canRefine }); }; _this.state = { canRefine: true }; return _this; } createClass(Panel, [{ key: 'render', value: function render() { return React__default.createElement( 'div', cx$21('root', !this.state.canRefine && 'noRefinement'), React__default.createElement( 'h5', cx$21('title'), this.props.title ), this.props.children ); } }]); return Panel; }(React.Component); Panel.propTypes = { title: propTypes.string.isRequired, children: propTypes.node }; Panel.childContextTypes = { canRefine: propTypes.func }; var getId$12 = function getId(props) { return props.attributes[0]; }; var namespace$6 = 'hierarchicalMenu'; function _refine$8(props, searchState, nextRefinement, context) { var id = getId$12(props); var nextValue = defineProperty$2({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$6); } function transformValue$1(values) { return values.reduce(function (acc, item) { if (item.isRefined) { acc.push({ label: item.name, // If dealing with a nested "items", "value" is equal to the previous value concatenated with the current label // If dealing with the first level, "value" is equal to the current label value: item.path }); // Create a variable in order to keep the same acc for the recursion, otherwise "reduce" returns a new one if (item.data) { acc = acc.concat(transformValue$1(item.data, acc)); } } return acc; }, []); } /** * The breadcrumb component is s a type of secondary navigation scheme that * reveals the user’s location in a website or web application. * * @name connectBreadcrumb * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a Breadcrumb of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {string} {React.Element} [separator=' > '] - Specifies the level separator used in the data. * @propType {string} [rootURL=null] - The root element's URL (the originating page). * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display. */ var connectBreadcrumb = createConnector({ displayName: 'AlgoliaBreadcrumb', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, rootURL: propTypes.string, separator: propTypes.oneOfType([propTypes.string, propTypes.element]), transformItems: propTypes.func }, defaultProps: { rootURL: null, separator: ' > ' }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var id = getId$12(props); var results = getResults(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], canRefine: false }; } var values = results.getFacetValues(id); var items = values.data ? transformValue$1(values.data) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { canRefine: transformedItems.length > 0, items: transformedItems }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$8(props, searchState, nextRefinement, this.context); } }); var cx$22 = classNames('Breadcrumb'); var itemsPropType$2 = propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired })); var Breadcrumb = function (_Component) { inherits(Breadcrumb, _Component); function Breadcrumb() { classCallCheck(this, Breadcrumb); return possibleConstructorReturn(this, (Breadcrumb.__proto__ || Object.getPrototypeOf(Breadcrumb)).apply(this, arguments)); } createClass(Breadcrumb, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props, canRefine = _props.canRefine, createURL = _props.createURL, items = _props.items, refine = _props.refine, rootURL = _props.rootURL, separator = _props.separator, translate = _props.translate; var rootPath = canRefine ? React__default.createElement( 'span', cx$22('item'), React__default.createElement( Link, _extends({}, cx$22('itemLink', 'itemLinkRoot'), { onClick: function onClick() { return !rootURL ? refine() : null; }, href: rootURL ? rootURL : createURL() }), React__default.createElement( 'span', cx$22('rootLabel'), translate('rootLabel') ) ), React__default.createElement( 'span', cx$22('separator'), separator ) ) : null; var breadcrumb = items.map(function (item, idx) { var isLast = idx === items.length - 1; return !isLast ? React__default.createElement( 'span', _extends({}, cx$22('item'), { key: idx }), React__default.createElement( Link, _extends({}, cx$22('itemLink'), { onClick: function onClick() { return refine(item.value); }, href: createURL(item.value), key: idx }), React__default.createElement( 'span', cx$22('itemLabel'), item.label ) ), React__default.createElement( 'span', cx$22('separator'), isLast ? '' : separator ) ) : React__default.createElement( 'span', _extends({}, cx$22('itemLink', 'itemDisabled', 'item'), { key: idx }), React__default.createElement( 'span', cx$22('itemLabel'), item.label ) ); }); return React__default.createElement( 'div', cx$22('root', !canRefine && 'noRefinement'), rootPath, breadcrumb ); } }]); return Breadcrumb; }(React.Component); Breadcrumb.propTypes = { canRefine: propTypes.bool.isRequired, createURL: propTypes.func.isRequired, items: itemsPropType$2, refine: propTypes.func.isRequired, rootURL: propTypes.string, separator: propTypes.oneOfType([propTypes.string, propTypes.element]), translate: propTypes.func.isRequired }; Breadcrumb.contextTypes = { canRefine: propTypes.func }; var BreadcrumbComponent = translatable({ rootLabel: 'Home' })(Breadcrumb); /** * A breadcrumb is a secondary navigation scheme that allows the user to see where the current page * is in relation to the website or web application’s hierarchy. * In terms of usability, using a breadcrumb reduces the number of actions a visitor needs to take in * order to get to a higher-level page. * * If you want to select a specific refinement for your Breadcrumb component, you will need to use a Virtual Hierarchical Menu * (https://community.algolia.com/react-instantsearch/guide/Virtual_widgets.html) and set its * defaultRefinement that will be then used by the Breadcrumb. * * @name Breadcrumb * @kind widget * @requirements Breadcrumbs are used for websites with a large amount of content organised in a hierarchical manner. * The typical example is an e-commerce website which has a large variety of products grouped into logical categories * (with categories, subcategories which also have subcategories).To use this widget, your attributes must be formatted in a specific way. * * Keep in mind that breadcrumbs shouldn’t replace effective primary navigation menus: * it is only an alternative way to navigate around the website. * * If, for instance, you would like to have a breadcrumb of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow * @propType {string} [separator='>'] - Symbol used for separating hyperlinks * @propType {string} [rootURL=null] - The originating page (homepage) * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return * @themeKey ais-Breadcrumb__root - The widget container * @themeKey ais-Breadcrumb__itemLinkRoot - The root link (originating page) * @themeKey ais-Breadcrumb__rootLabel - The root label * @themeKey ais-Breadcrumb__item - Contains the link, the label and the separator * @themeKey ais-Breadcrumb__itemLink - The link containing the label * @themeKey ais-Breadcrumb__itemLabel - The link's label * @themeKey ais-Breadcrumb__itemDisabled - For the last item of the breadcrumb which is not clickable * @themeKey ais-Breadcrumb__separator - The separator * @themeKey ais-Breadcrumb__noRefinement - present when there is no refinement * @translationKey rootLabel - The root's label. Accepts a string * @example * import React from 'react'; * import { Breadcrumb, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Breadcrumb * attributes={[ * 'category', * 'sub_category', * 'sub_sub_category', * ]} * rootURL="www.algolia.com" * separator=" / " * /> * </InstantSearch> * ); * } */ var Breadcrumb$1 = connectBreadcrumb(BreadcrumbComponent); var InstantSearch$2 = createInstantSearch(algoliasearchLite, { Root: 'div', props: { className: 'ais-InstantSearch__root' } }); var Index$2 = createIndex({ Root: 'div', props: { className: 'ais-MultiIndex__root' } }); exports.InstantSearch = InstantSearch$2; exports.Index = Index$2; exports.Configure = Configure$1; exports.CurrentRefinements = CurrentRefinements$1; exports.HierarchicalMenu = HierarchicalMenu$1; exports.Highlight = Highlight$2; exports.Snippet = Snippet$1; exports.Hits = Hits$1; exports.HitsPerPage = HitsPerPage$1; exports.InfiniteHits = InfiniteHits$1; exports.Menu = Menu$1; exports.MenuSelect = MenuSelect$1; exports.MultiRange = MultiRange$1; exports.Pagination = Pagination$1; exports.PoweredBy = PoweredBy$1; exports.RangeInput = RangeInput; exports.RangeSlider = RangeSlider; exports.StarRating = StarRating$1; exports.RefinementList = RefinementList$4; exports.ClearAll = ClearAll$1; exports.ScrollTo = ScrollTo$1; exports.SearchBox = SearchBox$1; exports.SortBy = SortBy$1; exports.Stats = Stats$1; exports.Toggle = Toggle$1; exports.Panel = Panel; exports.Breadcrumb = Breadcrumb$1; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=Dom.js.map
client/src/containers/LoginPage.js
elliotjz/book-trading-club
import React from 'react' import { Redirect } from 'react-router-dom' import Auth from '../modules/Auth'; import LoginForm from '../components/LoginForm' class LoginPage extends React.Component { constructor(props, context) { super(props, context); const storedMessage = localStorage.getItem('successMessage'); let successMessage = ''; if (storedMessage) { successMessage = storedMessage; localStorage.removeItem('successMessage'); } this.state = { errors: {}, successMessage, user: { email: '', password: '' }, successfulLogin: false }; this.processForm = this.processForm.bind(this); this.changeUser = this.changeUser.bind(this); } processForm(event) { // prevent default action. in this case, action is the form submission event event.preventDefault(); // create a string for an HTTP body message const email = encodeURIComponent(this.state.user.email); const password = encodeURIComponent(this.state.user.password); const formData = `email=${email}&password=${password}`; // create an AJAX request const xhr = new XMLHttpRequest(); xhr.open('post', '/auth/login'); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.responseType = 'json'; xhr.addEventListener('load', () => { if (xhr.status === 200) { // change the component-container state this.setState({ errors: {} }); // save the token Auth.authenticateUser(xhr.response.token, xhr.response.user); // change the current URL to / this.setState({ successfulLogin: true }) } else { // failure // change the component state const errors = xhr.response.errors ? xhr.response.errors : {}; errors.summary = xhr.response.message; this.setState({ errors }); } }); xhr.send(formData); } changeUser(event) { const field = event.target.name; const user = this.state.user; user[field] = event.target.value; this.setState({ user }); } render() { return this.state.successfulLogin ? ( <Redirect to="/" push /> ) : ( <LoginForm onSubmit={this.processForm} onChange={this.changeUser} errors={this.state.errors} successMessage={this.state.successMessage} user={this.state.user} /> ); } } export default LoginPage;
test/PageHeaderSpec.js
JimiHFord/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import PageHeader from '../src/PageHeader'; describe('PageHeader', function () { it('Should output a div with content', function () { let instance = ReactTestUtils.renderIntoDocument( <PageHeader> <strong>Content</strong> </PageHeader> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong')); }); it('Should have a page-header class', function () { let instance = ReactTestUtils.renderIntoDocument( <PageHeader> Content </PageHeader> ); assert.ok(React.findDOMNode(instance).className.match(/\bpage-header\b/)); }); });
src/Root.js
sMteX/WoWAnalyzer
import React from 'react'; import { applyMiddleware, createStore } from 'redux'; import { Provider as ReduxProvider } from 'react-redux'; import { composeWithDevTools } from 'redux-devtools-extension'; import thunk from 'redux-thunk'; import createHistory from 'history/createBrowserHistory'; import { ConnectedRouter, routerMiddleware } from 'react-router-redux'; import reducers from 'interface/reducers'; import RootErrorBoundary from 'interface/RootErrorBoundary'; import App from 'interface/App'; import RootLocalizationProvider from 'interface/RootLocalizationProvider'; import { Provider } from 'interface/LocationContext'; // Create a history of your choosing (we're using a browser history in this case) const history = createHistory(); // Build the middleware for intercepting and dispatching navigation actions const middleware = routerMiddleware(history); const store = createStore( reducers, composeWithDevTools( applyMiddleware(thunk, middleware) ) ); const Root = () => ( <ReduxProvider store={store}> <RootErrorBoundary> <RootLocalizationProvider> <ConnectedRouter history={history}> <Provider> <App /> </Provider> </ConnectedRouter> </RootLocalizationProvider> </RootErrorBoundary> </ReduxProvider> ); export default Root;
src/svg-icons/image/straighten.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageStraighten = (props) => ( <SvgIcon {...props}> <path d="M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H3V8h2v4h2V8h2v4h2V8h2v4h2V8h2v4h2V8h2v8z"/> </SvgIcon> ); ImageStraighten = pure(ImageStraighten); ImageStraighten.displayName = 'ImageStraighten'; export default ImageStraighten;
docs/src/examples/modules/Tab/Types/TabExampleSecondaryPointing.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Tab } from 'semantic-ui-react' const panes = [ { menuItem: 'Tab 1', render: () => <Tab.Pane attached={false}>Tab 1 Content</Tab.Pane>, }, { menuItem: 'Tab 2', render: () => <Tab.Pane attached={false}>Tab 2 Content</Tab.Pane>, }, { menuItem: 'Tab 3', render: () => <Tab.Pane attached={false}>Tab 3 Content</Tab.Pane>, }, ] const TabExampleSecondaryPointing = () => ( <Tab menu={{ secondary: true, pointing: true }} panes={panes} /> ) export default TabExampleSecondaryPointing
packages/react-scripts/fixtures/kitchensink/src/features/webpack/LinkedModules.js
amido/create-react-app
/** * Copyright (c) 2015-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. */ import React from 'react'; import './assets/style.css'; import { test, version } from 'test-integrity'; export default () => { const v = version(); if (!test() || v !== '2.0.0') { throw new Error('Functionality test did not pass.'); } return <p id="feature-linked-modules">{v}</p>; };
src/js/containers/App.js
rmhowe/search-ui
import React from 'react'; import { connect } from 'react-redux'; import Immutable from 'immutable'; import throttle from 'lodash/throttle'; import NavBar from '../components/NavBar'; import Artists from '../components/Artists'; import ReactSlider from 'react-slider'; import { fetchData, setSmallBrowserMode, setFilter, setGenderFilter, setOrderBy, toggleMap } from '../actions'; import { SMALL_BROWSER } from '../constants'; class App extends React.Component { constructor(props) { super(props); this.checkBrowserSize = throttle(this.checkBrowserSize, 300); } componentDidMount() { this.checkBrowserSize(); this.props.dispatch(fetchData('data/artists.json')).then(() => { this.setInitialFilters(); }); window.addEventListener('resize', this.checkBrowserSize); } componentWillUnmount() { window.removeEventListener('resize', this.checkBrowserSize); } checkBrowserSize = () => { if (window.innerWidth <= SMALL_BROWSER && !this.props.smallBrowserMode) { this.props.dispatch(setSmallBrowserMode(true)); } else if (window.innerWidth > SMALL_BROWSER && this.props.smallBrowserMode) { this.props.dispatch(setSmallBrowserMode(false)); } } setInitialFilters = () => { const artists = this.props.artists; this.props.dispatch(setFilter('age', this.getMinMax('age'))); this.props.dispatch(setFilter('rate', this.getMinMax('rate'))); }; getMinMax(type) { const values = this.props.artists.map(artist => artist.get(type)).toJS(); const min = Math.min.apply(Math, values); const max = Math.max.apply(Math, values); return Immutable.List([min, max]); } handleFilterChange = (filter, value) => { this.props.dispatch(setFilter(filter, value)); }; handleGenderFilterChange = (gender, value) => { this.props.dispatch(setGenderFilter(gender, value)); }; handleOrderByChange = (value, ascending) => { this.props.dispatch(setOrderBy(value, ascending)); }; handleToggleMap = () => { this.props.dispatch(toggleMap()); }; render() { return ( <div className="app"> <header className="header"> <NavBar smallBrowserMode={this.props.smallBrowserMode} artists={this.props.artists} filters={this.props.searchModifiers.get('filters')} orderBy={this.props.searchModifiers.get('orderBy')} showMap={this.props.showMap} handleFilterChange={this.handleFilterChange} handleGenderFilterChange={this.handleGenderFilterChange} handleOrderByChange={this.handleOrderByChange} handleToggleMap={this.handleToggleMap} /> </header> <section className="main-content"> <Artists artists={this.props.artists} filters={this.props.searchModifiers.get('filters')} orderBy={this.props.searchModifiers.get('orderBy')} showMap={this.props.showMap} limit={200} /> </section> </div> ); } } function select(state) { return { smallBrowserMode: state.smallBrowserMode, searchModifiers: state.searchModifiers, artists: state.artists, showMap: state.showMap }; } export default connect(select)(App);
src/containers/App/index.js
YUzhva/create-react-redux-app
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { getAPIData } from './actions'; import { selectApiData } from './selectors'; import logo from './images/logo.svg'; const getMyIp = (apiData) => ( (apiData && apiData.origin) && apiData.origin.split(', ')[1] ); class App extends Component { componentWillMount() { this.props.actions.getAPIData(); } render() { return ( <div className="app"> <div className="app-header"> <img src={logo} className="app-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="app-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> <p className="app-intro"> Your IP is: {getMyIp(this.props.apiData)} </p> </div> ); } } App.defaultProps = { apiData: {}, }; App.propTypes = { actions: PropTypes.object.isRequired, apiData: PropTypes.object, }; const mapStateToProps = (state) => ({ apiData: selectApiData(state), }); const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators({ getAPIData }, dispatch), }); export default connect(mapStateToProps, mapDispatchToProps)(App);
App/Components/GoogleMap.js
OUCHUNYU/Ralli
import React, { Component } from 'react'; import Button from './Common/button' import GroupsPage from './GroupsPage' import UserProfilePage from './UserProfilePage' import GroupsInvitePage from './GroupsInvitePage' import EventFeed from './EventFeed' import CreateMarker from './CreateMarker' import markersApi from '../Utils/markersApi' import messagesApi from '../Utils/messagesApi' import Firebase from 'firebase' import QuestionBox from './QuestionBox' import MapView from 'react-native-maps' import CustomCallout from './CustomCallout' import { StyleSheet, PropTypes, View, Text, Dimensions, TouchableOpacity, NavigatorIOS, AlertIOS, Image, TouchableHighlight, LinkingIOS, Animated } from 'react-native'; var { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; const SPACE = 0.01; class GoogleMap extends Component { componentWillMount(){ this.markerRef.on("value", function(res) { var allMarkers = []; for(var i in res.val()) { allMarkers.push(res.val()[i]) } this.setState({ markers: allMarkers }) this.render() }.bind(this)) } constructor(props) { super(props); this.markerRef = new Firebase('https://ralli.firebaseio.com/markers'); this.state = { bounceValue: new Animated.Value(0), region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, markers: ["placeholder"] }; } onMarkerPress() {} onPressGroups() { this.props.navigator.push ({ title: 'Groups Page', component: GroupsPage, passProps: {userData: this.props.userData, userId: this.props.userId} }) } onPressProfile() { this.props.navigator.push ({ title: 'Profile Page', component: UserProfilePage, passProps: {userData: this.props.userData, userId: this.props.userId} }) } onPressFeed() { this.props.navigator.push ({ title: 'Feed', component: EventFeed, passProps: {userData: this.props.userData, userId: this.props.userId} }) } onPressCreateMarker () { this.props.navigator.push ({ title: 'Make a Rally', component: CreateMarker, passProps: { userId: this.props.userId, userData: this.props.userData } }) } onPressSurprise() { // function to get a a random number between range because js if (this.props.userData.markers) { function getRandomIntInclusive(min, max) { return Math.floor(Math.random() * (max - min)) + min; } // need latest array of user markers (realtime) let len = this.props.userData.markers.length let eventIndex = getRandomIntInclusive(0, len) let randEventId = this.props.userData.markers[eventIndex] new Firebase('https://ralli.firebaseio.com/markers/' + randEventId) .once("value") .then((res) => this.props.navigator.push ({ title: 'Surprise', component: QuestionBox, passProps: { userId: this.props.userId, userData: this.props.userData, eventInfo: res.val() } }) ) } else { AlertIOS.alert( 'Sorry ' + this.props.userData.username, "Looks like you've not been invited to any events." ) } } iAmGoingButton(item) { let eventOwnerId = item.creator; let message = this.props.userData.username + " is going to your event: " + item.title messagesApi.individualUserMessenger(eventOwnerId, message) } onRegionChange(region) { this.state.region = region; } onLikeButton() { this.state.bounceValue.setValue(1.5); Animated.spring( this.state.bounceValue, { toValue: 0.8, friction: 1, } ).start(); } markerCenter() { } render() { const { region, markers } = this.state; let markersList = this.state.markers.map((item, index) => { return ( <MapView.Marker ref="m3" key={index} image={this.state.iconLoaded ? 'markerLoaded' : 'marker'} showsUserLocation={true} followUserLocation={true} coordinate={markers[index].coordinate} calloutAnchor={{ x: 0.1, y: 0.1 }} calloutOffset={{ x: -8, y: 29 }} > <Image source={require('./Common/other-small-icon.png')} onLoadEnd={() => {if (!this.state.iconLoaded) this.setState({iconLoaded: true});}}/> <MapView.Callout tooltip> <TouchableOpacity onPress={this.markerCenter.bind(this)}> <CustomCallout style={styles.calloutOpacity}> <View style={styles.wrapper}> <Text style={styles.calloutHeader}>{markers[index].title}</Text> </View> <Text style={styles.calloutText}> {markers[index].address}</Text> <Text style={styles.calloutText}> {markers[index].description}</Text> <Text style={styles.calloutText}> {markers[index].timeStart}</Text> <Text style={styles.calloutText}> Group: {markers[index].groups}</Text> <Image style={styles.calloutImage} source={require('./Common/sbpete.png')}/> <Button onPress={this.iAmGoingButton.bind(this, item)} text="I'm Going"></Button> </CustomCallout> </TouchableOpacity> </MapView.Callout> </MapView.Marker> ) }); return ( <View style={styles.container}> <MapView style={styles.map} initialRegion={region} showsUserLocation={true} followUserLocation={true}> {markersList} </MapView> <View style={styles.buttonContainer}> <TouchableOpacity onPress={this.onPressGroups.bind(this)} style={[styles.bubble, styles.button]}> <Image source={require('./Common/usergroup.png')} style={styles.icongood} /> </TouchableOpacity> <TouchableOpacity onPress={this.onPressProfile.bind(this)} style={[styles.bubble, styles.button]}> <Image source={require('./Common/profile.png')} style={styles.icon}/> </TouchableOpacity> <TouchableOpacity onPress={this.onPressCreateMarker.bind(this)} style={[styles.bubble, styles.button]}> <Image source={require('./Common/Untitled.png')} style={styles.middleicon}/> </TouchableOpacity> <TouchableOpacity onPress={this.onPressFeed.bind(this)} style={[styles.bubble, styles.button]}> <Image source={require('./Common/activityfeed.png')} style={styles.icon} /> </TouchableOpacity> <TouchableOpacity onPress={this.onPressSurprise.bind(this)} style={[styles.bubble, styles.button]}> <Image source={require('./Common/question.png')} style={styles.icon} /> </TouchableOpacity> </View> </View> ); } } let styles = StyleSheet.create({ container: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'flex-end', alignItems: 'center', }, map: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'red', }, bubble: { flex: 1, backgroundColor: 'rgba(255,255,255,0.7)', paddingHorizontal: 18, paddingVertical: 12, }, latlng: { width: 200, alignItems: 'stretch', }, button: { height: height * .08, width: width * .20, alignItems: 'center', justifyContent: 'center' }, buttonContainer: { flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'flex-end', backgroundColor: 'transparent', }, calloutHeader: { fontSize: 24, color: '#fff', marginBottom: 5, flex: 1 }, calloutText: { color: '#fff', flex: 1 }, calloutOpacity: { borderRadius: 8, opacity: .8 }, icon: { height: 25, width: 25, }, icongood: { height: 32, width: 32, }, middleicon: { height: 33, width: 33 }, calloutImage: { height: height * .15, width: width * .25, alignSelf: 'center', marginTop: 5, borderRadius: 3, borderWidth: 1, }, wrapper: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }, likebutton: { marginTop: -10, flex: 1, height: 32, width: 22 } }); GoogleMap.propTypes = { userData: React.PropTypes.object.isRequired, userId: React.PropTypes.string.isRequired }; export default GoogleMap
src/svg-icons/places/pool.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesPool = (props) => ( <SvgIcon {...props}> <path d="M22 21c-1.11 0-1.73-.37-2.18-.64-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.46.27-1.07.64-2.18.64s-1.73-.37-2.18-.64c-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.46.27-1.08.64-2.19.64-1.11 0-1.73-.37-2.18-.64-.37-.23-.6-.36-1.15-.36s-.78.13-1.15.36c-.46.27-1.08.64-2.19.64v-2c.56 0 .78-.13 1.15-.36.46-.27 1.08-.64 2.19-.64s1.73.37 2.18.64c.37.23.59.36 1.15.36.56 0 .78-.13 1.15-.36.46-.27 1.08-.64 2.19-.64 1.11 0 1.73.37 2.18.64.37.22.6.36 1.15.36s.78-.13 1.15-.36c.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.23.59.36 1.15.36v2zm0-4.5c-1.11 0-1.73-.37-2.18-.64-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.45.27-1.07.64-2.18.64s-1.73-.37-2.18-.64c-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.45.27-1.07.64-2.18.64s-1.73-.37-2.18-.64c-.37-.22-.6-.36-1.15-.36s-.78.13-1.15.36c-.47.27-1.09.64-2.2.64v-2c.56 0 .78-.13 1.15-.36.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.22.6.36 1.15.36.56 0 .78-.13 1.15-.36.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.22.6.36 1.15.36s.78-.13 1.15-.36c.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.22.6.36 1.15.36v2zM8.67 12c.56 0 .78-.13 1.15-.36.46-.27 1.08-.64 2.19-.64 1.11 0 1.73.37 2.18.64.37.22.6.36 1.15.36s.78-.13 1.15-.36c.12-.07.26-.15.41-.23L10.48 5C8.93 3.45 7.5 2.99 5 3v2.5c1.82-.01 2.89.39 4 1.5l1 1-3.25 3.25c.31.12.56.27.77.39.37.23.59.36 1.15.36z"/><circle cx="16.5" cy="5.5" r="2.5"/> </SvgIcon> ); PlacesPool = pure(PlacesPool); PlacesPool.displayName = 'PlacesPool'; PlacesPool.muiName = 'SvgIcon'; export default PlacesPool;
src/svg-icons/action/event-seat.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionEventSeat = (props) => ( <SvgIcon {...props}> <path d="M4 18v3h3v-3h10v3h3v-6H4zm15-8h3v3h-3zM2 10h3v3H2zm15 3H7V5c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2v8z"/> </SvgIcon> ); ActionEventSeat = pure(ActionEventSeat); ActionEventSeat.displayName = 'ActionEventSeat'; ActionEventSeat.muiName = 'SvgIcon'; export default ActionEventSeat;
files/rxjs/4.0.0/rx.all.js
ezekutor/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'function': true, 'object': true }; var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeSelf = objectTypes[typeof self] && self.Object && self, freeWindow = objectTypes[typeof window] && window && window.Object && window, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global; var root = root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this; var Rx = { internals: {}, config: { Promise: root.Promise }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, identity = Rx.helpers.identity = function (x) { return x; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;} var errorObj = {e: {}}; function tryCatcherGen(tryCatchTarget) { return function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } }; } var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } return tryCatcherGen(fn); }; function thrower(e) { throw e; } Rx.config.longStackSupport = false; var hasStacks = false, stacks = tryCatch(function () { throw new Error(); })(); hasStacks = !!stacks.e && !!stacks.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.'; this.name = 'EmptyError'; Error.call(this); }; EmptyError.prototype = Object.create(Error.prototype); var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; this.name = 'ObjectDisposedError'; Error.call(this); }; ObjectDisposedError.prototype = Object.create(Error.prototype); var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; this.name = 'ArgumentOutOfRangeError'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Object.create(Error.prototype); var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; this.name = 'NotSupportedError'; Error.call(this); }; NotSupportedError.prototype = Object.create(Error.prototype); var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; this.name = 'NotImplementedError'; Error.call(this); }; NotImplementedError.prototype = Object.create(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 = 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 BinaryDisposable(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; } 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; }; 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]; } } 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 disposableFixup = Disposable._fixup = function (result) { return isDisposable(result) ? result : disposableEmpty; }; // Single assignment var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { this.isDisposed = false; this.current = null; }; SingleAssignmentDisposable.prototype.getDisposable = function () { return this.current; }; SingleAssignmentDisposable.prototype.setDisposable = function (value) { if (this.current) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed; !shouldDispose && (this.current = value); shouldDispose && value && value.dispose(); }; SingleAssignmentDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; old && old.dispose(); } }; // Multiple assignment disposable var SerialDisposable = Rx.SerialDisposable = function () { this.isDisposed = false; this.current = null; }; SerialDisposable.prototype.getDisposable = function () { return this.current; }; SerialDisposable.prototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; SerialDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; var BinaryDisposable = Rx.BinaryDisposable = function (first, second) { this._first = first; this._second = second; this.isDisposed = false; }; BinaryDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old1 = this._first; this._first = null; old1 && old1.dispose(); var old2 = this._second; this._second = null; old2 && old2.dispose(); } }; var NAryDisposable = Rx.NAryDisposable = function (disposables) { this._disposables = disposables; this.isDisposed = false; }; NAryDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; for (var i = 0, len = this._disposables.length; i < len; i++) { this._disposables[i].dispose(); } this._disposables.length = 0; } }; /** * 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.schedule(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 disposableFixup(this.action(this.scheduler, this.state)); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler() { } /** Determines whether the given object is a scheduler */ Scheduler.isScheduler = function (s) { return s instanceof Scheduler; }; var schedulerProto = Scheduler.prototype; /** * 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.schedule = function (state, action) { throw new NotImplementedError(); }; /** * 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.scheduleFuture = function (state, dueTime, action) { var dt = dueTime; dt instanceof Date && (dt = dt - this.now()); dt = Scheduler.normalize(dt); if (dt === 0) { return this.schedule(state, action); } return this._scheduleFuture(state, dt, action); }; schedulerProto._scheduleFuture = function (state, dueTime, action) { throw new NotImplementedError(); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** Gets the current time according to the local machine's system clock. */ Scheduler.prototype.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); action(state, innerAction); return group; function innerAction(state2) { var isAdded = false, isDone = false; var d = scheduler.schedule(state2, scheduleWork); if (!isDone) { group.add(d); isAdded = true; } function scheduleWork(_, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } action(state3, innerAction); return disposableEmpty; } } } function invokeRecDate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); action(state, innerAction); return group; function innerAction(state2, dueTime1) { var isAdded = false, isDone = false; var d = scheduler.scheduleFuture(state2, dueTime1, scheduleWork); if (!isDone) { group.add(d); isAdded = true; } function scheduleWork(_, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } action(state3, innerAction); return disposableEmpty; } } } /** * 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.scheduleRecursive = function (state, action) { return this.schedule([state, action], invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative or 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 | Date} dueTime Relative or absolute 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.scheduleRecursiveFuture = function (state, dueTime, action) { return this.scheduleFuture([state, action], dueTime, invokeRecDate); }; }(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 {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.schedulePeriodic = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveFuture(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var ImmediateScheduler = (function (__super__) { inherits(ImmediateScheduler, __super__); function ImmediateScheduler() { __super__.call(this); } ImmediateScheduler.prototype.schedule = function (state, action) { return disposableFixup(action(this, state)); }; return ImmediateScheduler; }(Scheduler)); var immediateScheduler = Scheduler.immediate = new ImmediateScheduler(); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var CurrentThreadScheduler = (function (__super__) { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } inherits(CurrentThreadScheduler, __super__); function CurrentThreadScheduler() { __super__.call(this); } CurrentThreadScheduler.prototype.schedule = function (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) { thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; }; CurrentThreadScheduler.prototype.scheduleRequired = function () { return !queue; }; return CurrentThreadScheduler; }(Scheduler)); var currentThreadScheduler = Scheduler.currentThread = new CurrentThreadScheduler(); var scheduleMethod, clearMethod; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else if (!!root.WScript) { localSetTimeout = function (fn, time) { root.WScript.Sleep(time); fn(); }; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; clearMethod = function (handle) { delete tasksByHandle[handle]; }; function runTask(handle) { if (currentlyRunning) { localSetTimeout(function () { runTask(handle); }, 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunning = true; var result = tryCatch(task)(); clearMethod(handle); currentlyRunning = false; if (result === errorObj) { thrower(result.e); } } } } var reNative = new RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (isFunction(setImmediate)) { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; setImmediate(function () { runTask(id); }); return id; }; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; process.nextTick(function () { runTask(id); }); return id; }; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { runTask(event.data.substring(MSG_PREFIX.length)); } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else if (root.attachEvent) { root.attachEvent('onmessage', onGlobalPostMessage); } else { root.onmessage = onGlobalPostMessage; } scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; root.postMessage(MSG_PREFIX + currentId, '*'); return id; }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (e) { runTask(e.data); }; scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; channel.port2.postMessage(id); return id; }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); var id = nextHandle++; tasksByHandle[id] = action; scriptElement.onreadystatechange = function () { runTask(id); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); return id; }; } else { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; localSetTimeout(function () { runTask(id); }, 0); return id; }; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var DefaultScheduler = (function (__super__) { inherits(DefaultScheduler, __super__); function DefaultScheduler() { __super__.call(this); } function DefaultSchedulerDisposable(id) { this._id = id; this.isDisposed = false; } DefaultSchedulerDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; localClearTimeout(this._id); } }; DefaultScheduler.prototype.schedule = function (state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { !disposable.isDisposed && disposable.setDisposable(disposableFixup(action(scheduler, state))); }); return new BinaryDisposable(disposable, new DefaultSchedulerDisposable(id)); }; DefaultScheduler.prototype._scheduleFuture = function (state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime), disposable = new SingleAssignmentDisposable(); if (dt === 0) { return scheduler.schedule(state, action); } var id = localSetTimeout(function () { !disposable.isDisposed && disposable.setDisposable(disposableFixup(action(scheduler, state))); }, dt); return new BinaryDisposable(disposable, new DefaultSchedulerDisposable(id)); }; return DefaultScheduler; }(Scheduler)); var defaultScheduler = Scheduler['default'] = Scheduler.async = new DefaultScheduler(); var CatchScheduler = (function (__super__) { inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this); } CatchScheduler.prototype.schedule = function (state, action) { return this._scheduler.schedule(state, this._wrap(action)); }; CatchScheduler.prototype._scheduleFuture = function (state, dueTime, action) { return this._scheduler.schedule(state, dueTime, this._wrap(action)); }; CatchScheduler.prototype.now = function () { return this._scheduler.now(); }; CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { var res = tryCatch(action)(parent._getRecursiveWrapper(self), state); if (res === errorObj) { if (!parent._handler(res.e)) { thrower(res.e); } return disposableEmpty; } return disposableFixup(ret); }; }; 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.schedulePeriodic = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodic(state, period, function (state1) { if (failed) { return null; } var res = tryCatch(action)(state1); if (res === errorObj) { failed = true; if (!self._handler(res.e)) { thrower(res.e); } d.dispose(); return null; } return ret; })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification() { } Notification.prototype._accept = function (onNext, onError, onCompleted) { throw new NotImplementedError(); }; Notification.prototype._acceptObservable = function (onNext, onError, onCompleted) { throw new NotImplementedError(); }; /** * 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 (o) { return scheduler.schedule(self, function (_, notification) { notification._acceptObservable(o); notification.kind === 'N' && o.onCompleted(); }); }); }; return Notification; })(); var OnNextNotification = (function (__super__) { inherits(OnNextNotification, __super__); function OnNextNotification(value) { this.value = value; this.kind = 'N'; } OnNextNotification.prototype._accept = function (onNext) { return onNext(this.value); }; OnNextNotification.prototype._acceptObservable = function (o) { return o.onNext(this.value); }; OnNextNotification.prototype.toString = function () { return 'OnNext(' + this.value + ')'; }; return OnNextNotification; }(Notification)); var OnErrorNotification = (function (__super__) { inherits(OnErrorNotification, __super__); function OnErrorNotification(error) { this.error = error; this.kind = 'E'; } OnErrorNotification.prototype._accept = function (onNext, onError) { return onError(this.error); }; OnErrorNotification.prototype._acceptObservable = function (o) { return o.onError(this.error); }; OnErrorNotification.prototype.toString = function () { return 'OnError(' + this.error + ')'; }; return OnErrorNotification; }(Notification)); var OnCompletedNotification = (function (__super__) { inherits(OnCompletedNotification, __super__); function OnCompletedNotification() { this.kind = 'C'; } OnCompletedNotification.prototype._accept = function (onNext, onError, onCompleted) { return onCompleted(); }; OnCompletedNotification.prototype._acceptObservable = function (o) { return o.onCompleted(); }; OnCompletedNotification.prototype.toString = function () { return 'OnCompleted()'; }; return OnCompletedNotification; }(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 (value) { return new OnNextNotification(value); }; /** * 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 (error) { return new OnErrorNotification(error); }; /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = function () { return new OnCompletedNotification(); }; /** * 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 () { var self = this; return new AnonymousObserver( function (x) { self.onNext(x); }, function (err) { self.onError(err); }, function () { self.onCompleted(); }); }; /** * 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. * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { var cb = bindCallback(handler, thisArg, 1); return new AnonymousObserver(function (x) { return cb(notificationCreateOnNext(x)); }, function (e) { return cb(notificationCreateOnError(e)); }, function () { return cb(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; } // 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) { !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; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(this, function (parent, self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } var res = tryCatch(work)(); if (res === errorObj) { parent.queue = []; parent.hasFaulted = true; return thrower(res.e); } self(parent); })); } }; 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 makeSubscribe(self, subscribe) { return function (o) { var oldOnError = o.onError; o.onError = function (e) { makeStackTraceLong(e, self); oldOnError.call(o, e); }; return subscribe.call(self, o); }; } function Observable() { if (Rx.config.longStackSupport && hasStacks) { var oldSubscribe = this._subscribe; var e = tryCatch(thrower)(new Error()).e; this.stack = e.stack.substring(e.stack.indexOf('\n') + 1); this._subscribe = makeSubscribe(this, oldSubscribe); } } observableProto = Observable.prototype; /** * Determines whether the given object is an Observable * @param {Any} An object to determine whether it is an Observable * @returns {Boolean} true if an Observable, else false. */ Observable.isObservable = function (o) { return o && isFunction(o.subscribe); }; /** * Subscribes an o to the observable sequence. * @param {Mixed} [oOrOnNext] 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 (oOrOnNext, onError, onCompleted) { return this._subscribe(typeof oOrOnNext === 'object' ? oOrOnNext : observerCreate(oOrOnNext, 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 && !ado.fail(errorObj.e)) { thrower(errorObj.e); } ado.setDisposable(fixSubscriber(sub)); } function ObservableBase() { __super__.call(this); } ObservableBase.prototype._subscribe = function (o) { var ado = new AutoDetachObserver(o), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(state, setDisposable); } else { setDisposable(null, state); } return ado; }; ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); var FlatMapObservable = Rx.FlatMapObservable = (function(__super__) { inherits(FlatMapObservable, __super__); function FlatMapObservable(source, selector, resultSelector, thisArg) { this.resultSelector = isFunction(resultSelector) ? resultSelector : null; this.selector = bindCallback(isFunction(selector) ? selector : function() { return selector; }, thisArg, 3); this.source = source; __super__.call(this); } FlatMapObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new InnerObserver(o, this.selector, this.resultSelector, this)); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(observer, selector, resultSelector, source) { this.i = 0; this.selector = selector; this.resultSelector = resultSelector; this.source = source; this.o = observer; AbstractObserver.call(this); } InnerObserver.prototype._wrapResult = function(result, x, i) { return this.resultSelector ? result.map(function(y, i2) { return this.resultSelector(x, y, i, i2); }, this) : result; }; InnerObserver.prototype.next = function(x) { var i = this.i++; var result = tryCatch(this.selector)(x, i, this.source); if (result === errorObj) { return this.o.onError(result.e); } isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = Observable.from(result)); this.o.onNext(this._wrapResult(result, x, i)); }; InnerObserver.prototype.error = function(e) { this.o.onError(e); }; InnerObserver.prototype.onCompleted = function() { this.o.onCompleted(); }; return FlatMapObservable; }(ObservableBase)); var Enumerable = Rx.internals.Enumerable = function () { }; function IsDisposedDisposable(state) { this._s = state; this.isDisposed = false; } IsDisposedDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; this._s.isDisposed = true; } }; var ConcatEnumerableObservable = (function(__super__) { inherits(ConcatEnumerableObservable, __super__); function ConcatEnumerableObservable(sources) { this.sources = sources; __super__.call(this); } ConcatEnumerableObservable.prototype.subscribeCore = function (o) { var state = { isDisposed: false }, subscription = new SerialDisposable(); var cancelable = currentThreadScheduler.scheduleRecursive(this.sources[$iterator$](), function (e, self) { if (state.isDisposed) { return; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } 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(new InnerObserver(o, self, e))); }); return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(o, s, e) { this._o = o; this._s = s; this._e = e; AbstractObserver.call(this); } InnerObserver.prototype.onNext = function (x) { this._o.onNext(x); }; InnerObserver.prototype.onError = function (e) { this._o.onError(e); }; InnerObserver.prototype.onCompleted = function () { this._s(this._e); }; return ConcatEnumerableObservable; }(ObservableBase)); Enumerable.prototype.concat = function () { return new ConcatEnumerableObservable(this); }; var CatchErrorObservable = (function(__super__) { inherits(CatchErrorObservable, __super__); function CatchErrorObservable(sources) { this.sources = sources; __super__.call(this); } CatchErrorObservable.prototype.subscribeCore = function (o) { var e = this.sources[$iterator$](); var state = { isDisposed: false }, subscription = new SerialDisposable(); var cancelable = currentThreadScheduler.scheduleRecursive(null, function (lastException, self) { if (state.isDisposed) { return; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } if (currentItem.done) { return lastException !== null ? o.onError(lastException) : 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(new InnerObserver(o, self))); }); return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(o, recurse) { this._o = o; this._recurse = recurse; AbstractObserver.call(this); } InnerObserver.prototype.next = function (x) { this._o.onNext(x); }; InnerObserver.prototype.error = function (e) { this._recurse(e); }; InnerObserver.prototype.completed = function () { this._o.onCompleted(); }; return CatchErrorObservable; }(ObservableBase)); Enumerable.prototype.catchError = function () { return new CatchErrorObservable(this); }; 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 state = { isDisposed: false }, lastException, subscription = new SerialDisposable(); var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, self) { if (state.isDisposed) { return; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } 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 BinaryDisposable(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 NAryDisposable([notificationDisposable, subscription, cancelable, new IsDisposedDisposable(state)]); }); }; var RepeatEnumerable = (function (__super__) { inherits(RepeatEnumerable, __super__); function RepeatEnumerable(v, c) { this.v = v; this.c = c == null ? -1 : c; } RepeatEnumerable.prototype[$iterator$] = function () { return new RepeatEnumerator(this); }; function RepeatEnumerator(p) { this.v = p.v; this.l = p.c; } RepeatEnumerator.prototype.next = function () { if (this.l === 0) { return doneEnumerator; } if (this.l > 0) { this.l--; } return { done: false, value: this.v }; }; return RepeatEnumerable; }(Enumerable)); var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { return new RepeatEnumerable(value, repeatCount); }; var OfEnumerable = (function(__super__) { inherits(OfEnumerable, __super__); function OfEnumerable(s, fn, thisArg) { this.s = s; this.fn = fn ? bindCallback(fn, thisArg, 3) : null; } OfEnumerable.prototype[$iterator$] = function () { return new OfEnumerator(this); }; function OfEnumerator(p) { this.i = -1; this.s = p.s; this.l = this.s.length; this.fn = p.fn; } OfEnumerator.prototype.next = function () { return ++this.i < this.l ? { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } : doneEnumerator; }; return OfEnumerable; }(Enumerable)); var enumerableOf = Enumerable.of = function (source, selector, thisArg) { return new OfEnumerable(source, selector, thisArg); }; var ObserveOnObservable = (function (__super__) { inherits(ObserveOnObservable, __super__); function ObserveOnObservable(source, s) { this.source = source; this._s = s; __super__.call(this); } ObserveOnObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new ObserveOnObserver(this._s, o)); }; return ObserveOnObservable; }(ObservableBase)); /** * 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) { return new ObserveOnObservable(this, scheduler); }; var SubscribeOnObservable = (function (__super__) { inherits(SubscribeOnObservable, __super__); function SubscribeOnObservable(source, s) { this.source = source; this._s = s; __super__.call(this); } function scheduleMethod(scheduler, state) { var source = state[0], d = state[1], o = state[2]; d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(o))); } SubscribeOnObservable.prototype.subscribeCore = function (o) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(this._s.schedule([this.source, d, o], scheduleMethod)); return d; }; return SubscribeOnObservable; }(ObservableBase)); /** * 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) { return new SubscribeOnObservable(this, scheduler); }; var FromPromiseObservable = (function(__super__) { inherits(FromPromiseObservable, __super__); function FromPromiseObservable(p) { this.p = p; __super__.call(this); } FromPromiseObservable.prototype.subscribeCore = function(o) { this.p .then(function (data) { o.onNext(data); o.onCompleted(); }, function (err) { o.onError(err); }); return disposableEmpty; }; return FromPromiseObservable; }(ObservableBase)); /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new FromPromiseObservable(promise); }; /* * 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; source.subscribe(function (v) { value = v; }, reject, function () { resolve(value); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new InnerObserver(o)); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(o) { this.o = o; this.a = []; AbstractObserver.call(this); } InnerObserver.prototype.next = function (x) { this.a.push(x); }; InnerObserver.prototype.error = function (e) { this.o.onError(e); }; InnerObserver.prototype.completed = function () { this.o.onNext(this.a); this.o.onCompleted(); }; return ToArrayObservable; }(ObservableBase)); /** * 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 = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; var Defer = (function(__super__) { inherits(Defer, __super__); function Defer(factory) { this._f = factory; __super__.call(this); } Defer.prototype.subscribeCore = function (o) { var result = tryCatch(this._f)(); if (result === errorObj) { return observableThrow(result.e).subscribe(o);} isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(o); }; return Defer; }(ObservableBase)); /** * 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 Defer(observableFactory); }; var EmptyObservable = (function(__super__) { inherits(EmptyObservable, __super__); function EmptyObservable(scheduler) { this.scheduler = scheduler; __super__.call(this); } EmptyObservable.prototype.subscribeCore = function (observer) { var sink = new EmptySink(observer, this.scheduler); return sink.run(); }; function EmptySink(observer, scheduler) { this.observer = observer; this.scheduler = scheduler; } function scheduleItem(s, state) { state.onCompleted(); return disposableEmpty; } EmptySink.prototype.run = function () { var state = this.observer; return this.scheduler === immediateScheduler ? scheduleItem(null, state) : this.scheduler.schedule(state, scheduleItem); }; return EmptyObservable; }(ObservableBase)); var EMPTY_OBSERVABLE = new EmptyObservable(immediateScheduler); /** * 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 scheduler === immediateScheduler ? EMPTY_OBSERVABLE : new EmptyObservable(scheduler); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (o) { var sink = new FromSink(o, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(o, parent) { this.o = o; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), o = this.o, mapper = this.parent.mapper; function loopRecursive(i, recurse) { var next = tryCatch(it.next).call(it); if (next === errorObj) { return o.onError(next.e); } if (next.done) { return o.onCompleted(); } var result = next.value; if (isFunction(mapper)) { result = tryCatch(mapper)(result, i); if (result === errorObj) { return o.onError(result.e); } } o.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursive(0, loopRecursive); }; return FromSink; }()); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(s) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(s) { 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.scheduleRecursive(0, loopRecursive); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; var GenerateObservable = (function (__super__) { inherits(GenerateObservable, __super__); function GenerateObservable(state, cndFn, itrFn, resFn, s) { this._state = state; this._cndFn = cndFn; this._itrFn = itrFn; this._resFn = resFn; this._s = s; this._first = true; __super__.call(this); } function scheduleRecursive(self, recurse) { if (self._first) { self._first = false; } else { self._state = tryCatch(self._itrFn)(self._state); if (self._state === errorObj) { return self._o.onError(self._state.e); } } var hasResult = tryCatch(self._cndFn)(self._state); if (hasResult === errorObj) { return self._o.onError(hasResult.e); } if (hasResult) { var result = tryCatch(self._resFn)(self._state); if (result === errorObj) { return self._o.onError(result.e); } self._o.onNext(result); recurse(self); } else { self._o.onCompleted(); } } GenerateObservable.prototype.subscribeCore = function (o) { this._o = o; return this._s.scheduleRecursive(this, scheduleRecursive); }; return GenerateObservable; }(ObservableBase)); /** * 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 GenerateObservable(initialState, condition, iterate, resultSelector, scheduler); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; /** * Creates an Observable sequence from changes to an array using Array.observe. * @param {Array} array An array to observe changes. * @returns {Observable} An observable sequence containing changes to an array from Array.observe. */ Observable.ofArrayChanges = function(array) { if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); } if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') } return new AnonymousObservable(function(observer) { function observerFn(changes) { for(var i = 0, len = changes.length; i < len; i++) { observer.onNext(changes[i]); } } Array.observe(array, observerFn); return function () { Array.unobserve(array, observerFn); }; }); }; /** * Creates an Observable sequence from changes to an object using Object.observe. * @param {Object} obj An object to observe changes. * @returns {Observable} An observable sequence containing changes to an object from Object.observe. */ Observable.ofObjectChanges = function(obj) { if (obj == null) { throw new TypeError('object must not be null or undefined.'); } if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Object.observe is not supported on your platform') } return new AnonymousObservable(function(observer) { function observerFn(changes) { for(var i = 0, len = changes.length; i < len; i++) { observer.onNext(changes[i]); } } Object.observe(obj, observerFn); return function () { Object.unobserve(obj, observerFn); }; }); }; var NeverObservable = (function(__super__) { inherits(NeverObservable, __super__); function NeverObservable() { __super__.call(this); } NeverObservable.prototype.subscribeCore = function (observer) { return disposableEmpty; }; return NeverObservable; }(ObservableBase)); var NEVER_OBSERVABLE = new NeverObservable(); /** * 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 NEVER_OBSERVABLE; }; var PairsObservable = (function(__super__) { inherits(PairsObservable, __super__); function PairsObservable(obj, scheduler) { this.obj = obj; this.keys = Object.keys(obj); this.scheduler = scheduler; __super__.call(this); } PairsObservable.prototype.subscribeCore = function (observer) { var sink = new PairsSink(observer, this); return sink.run(); }; return PairsObservable; }(ObservableBase)); function PairsSink(observer, parent) { this.observer = observer; this.parent = parent; } PairsSink.prototype.run = function () { var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length; function loopRecursive(i, recurse) { if (i < len) { var key = keys[i]; observer.onNext([key, obj[key]]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursive(0, loopRecursive); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new PairsObservable(obj, scheduler); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.rangeCount = 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.rangeCount, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursive(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; var RepeatObservable = (function(__super__) { inherits(RepeatObservable, __super__); function RepeatObservable(value, repeatCount, scheduler) { this.value = value; this.repeatCount = repeatCount == null ? -1 : repeatCount; this.scheduler = scheduler; __super__.call(this); } RepeatObservable.prototype.subscribeCore = function (observer) { var sink = new RepeatSink(observer, this); return sink.run(); }; return RepeatObservable; }(ObservableBase)); function RepeatSink(observer, parent) { this.observer = observer; this.parent = parent; } RepeatSink.prototype.run = function () { var observer = this.observer, value = this.parent.value; function loopRecursive(i, recurse) { if (i === -1 || i > 0) { observer.onNext(value); i > 0 && i--; } if (i === 0) { return observer.onCompleted(); } recurse(i); } return this.parent.scheduler.scheduleRecursive(this.parent.repeatCount, loopRecursive); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RepeatObservable(value, repeatCount, scheduler); }; var JustObservable = (function(__super__) { inherits(JustObservable, __super__); function JustObservable(value, scheduler) { this.value = value; this.scheduler = scheduler; __super__.call(this); } JustObservable.prototype.subscribeCore = function (observer) { var sink = new JustSink(observer, this.value, this.scheduler); return sink.run(); }; function JustSink(observer, value, scheduler) { this.observer = observer; this.value = value; this.scheduler = scheduler; } function scheduleItem(s, state) { var value = state[0], observer = state[1]; observer.onNext(value); observer.onCompleted(); return disposableEmpty; } JustSink.prototype.run = function () { var state = [this.value, this.observer]; return this.scheduler === immediateScheduler ? scheduleItem(null, state) : this.scheduler.schedule(state, scheduleItem); }; return JustObservable; }(ObservableBase)); /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just' or browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new JustObservable(value, scheduler); }; var ThrowObservable = (function(__super__) { inherits(ThrowObservable, __super__); function ThrowObservable(error, scheduler) { this.error = error; this.scheduler = scheduler; __super__.call(this); } ThrowObservable.prototype.subscribeCore = function (o) { var sink = new ThrowSink(o, this); return sink.run(); }; function ThrowSink(o, p) { this.o = o; this.p = p; } function scheduleItem(s, state) { var e = state[0], o = state[1]; o.onError(e); } ThrowSink.prototype.run = function () { return this.p.scheduler.schedule([this.p.error, this.o], scheduleItem); }; return ThrowObservable; }(ObservableBase)); /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new ThrowObservable(error, scheduler); }; var UsingObservable = (function (__super__) { inherits(UsingObservable, __super__); function UsingObservable(resFn, obsFn) { this._resFn = resFn; this._obsFn = obsFn; __super__.call(this); } UsingObservable.prototype.subscribeCore = function (o) { var disposable = disposableEmpty; var resource = tryCatch(this._resFn)(); if (resource === errorObj) { return new BinaryDisposable(observableThrow(resource.e).subscribe(o), disposable); } resource && (disposable = resource); var source = tryCatch(this._obsFn)(resource); if (source === errorObj) { return new BinaryDisposable(observableThrow(source.e).subscribe(o), disposable); } return new BinaryDisposable(source.subscribe(o), disposable); }; return UsingObservable; }(ObservableBase)); /** * 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 UsingObservable(resourceFactory, observableFactory); }; /** * 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(); } } var leftSubscribe = observerCreate( function (left) { choiceL(); choice === leftChoice && observer.onNext(left); }, function (e) { choiceL(); choice === leftChoice && observer.onError(e); }, function () { choiceL(); choice === leftChoice && observer.onCompleted(); } ); var rightSubscribe = observerCreate( function (right) { choiceR(); choice === rightChoice && observer.onNext(right); }, function (e) { choiceR(); choice === rightChoice && observer.onError(e); }, function () { choiceR(); choice === rightChoice && observer.onCompleted(); } ); leftSubscription.setDisposable(leftSource.subscribe(leftSubscribe)); rightSubscription.setDisposable(rightSource.subscribe(rightSubscribe)); return new BinaryDisposable(leftSubscription, rightSubscription); }); }; function amb(p, c) { return p.amb(c); } /** * Propagates the observable sequence or Promise that reacts first. * @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 { var len = arguments.length; items = new Array(items); for(var i = 0; i < len; i++) { items[i] = arguments[i]; } } for (var i = 0, len = items.length; i < len; i++) { acc = amb(acc, items[i]); } return acc; }; var CatchObservable = (function (__super__) { inherits(CatchObservable, __super__); function CatchObservable(source, fn) { this.source = source; this._fn = fn; __super__.call(this); } CatchObservable.prototype.subscribeCore = function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(this.source.subscribe(new CatchObserver(o, subscription, this._fn))); return subscription; }; return CatchObservable; }(ObservableBase)); var CatchObserver = (function(__super__) { inherits(CatchObserver, __super__); function CatchObserver(o, s, fn) { this._o = o; this._s = s; this._fn = fn; __super__.call(this); } CatchObserver.prototype.next = function (x) { this._o.onNext(x); }; CatchObserver.prototype.completed = function () { return this._o.onCompleted(); }; CatchObserver.prototype.error = function (e) { var result = tryCatch(this._fn)(e); if (result === errorObj) { return this._o.onError(result.e); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); this._s.setDisposable(d); d.setDisposable(result.subscribe(this._o)); }; return CatchObserver; }(AbstractObserver)); /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @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'] = function (handlerOrSecond) { return isFunction(handlerOrSecond) ? new CatchObservable(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['catch'] = function () { var items; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { var len = arguments.length; items = new Array(len); for(var i = 0; i < len; i++) { items[i] = 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); }; function falseFactory() { return false; } function argumentsToArray() { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return args; } var CombineLatestObservable = (function(__super__) { inherits(CombineLatestObservable, __super__); function CombineLatestObservable(params, cb) { var len = params.length; this._params = params; this._cb = cb; this._hv = arrayInitialize(len, falseFactory); this._hvAll = false; this._done = arrayInitialize(len, falseFactory); this._v = new Array(len); __super__.call(this); } CombineLatestObservable.prototype.subscribeCore = function(observer) { var len = this._params.length, subscriptions = new Array(len); for (var i = 0; i < len; i++) { var source = this._params[i], sad = new SingleAssignmentDisposable(); subscriptions[i] = sad; isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(new CombineLatestObserver(observer, i, this))); } return new NAryDisposable(subscriptions); }; return CombineLatestObservable; }(ObservableBase)); var CombineLatestObserver = (function (__super__) { inherits(CombineLatestObserver, __super__); function CombineLatestObserver(o, i, p) { this._o = o; this._i = i; this._p = p; __super__.call(this); } CombineLatestObserver.prototype.next = function (x) { this._p._v[this._i] = x; this._p._hv[this._i] = true; if (this._p._hvAll || (this._p._hvAll = this._p._hv.every(identity))) { var res = tryCatch(this._p._cb).apply(null, this._p._v); if (res === errorObj) { return this._o.onError(res.e); } this._o.onNext(res); } else if (this._p._done.filter(function (x, j) { return j !== this._i; }, this).every(identity)) { this._o.onCompleted(); } }; CombineLatestObserver.prototype.error = function (e) { this._o.onError(e); }; CombineLatestObserver.prototype.completed = function () { this._p._done[this._i] = true; this._p._done.every(identity) && this._o.onCompleted(); }; return CombineLatestObserver; }(AbstractObserver)); /** * 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 = isFunction(args[len - 1]) ? args.pop() : argumentsToArray; Array.isArray(args[0]) && (args = args[0]); return new CombineLatestObservable(args, resultSelector); }; /** * 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); }; var ConcatObservable = (function(__super__) { inherits(ConcatObservable, __super__); function ConcatObservable(sources) { this.sources = sources; __super__.call(this); } ConcatObservable.prototype.subscribeCore = function(o) { var sink = new ConcatSink(this.sources, o); return sink.run(); }; function ConcatSink(sources, o) { this.sources = sources; this.o = o; } ConcatSink.prototype.run = function () { var isDisposed, subscription = new SerialDisposable(), sources = this.sources, length = sources.length, o = this.o; var cancelable = immediateScheduler.scheduleRecursive(0, function (i, self) { if (isDisposed) { return; } if (i === length) { return o.onCompleted(); } // Check if promise var currentValue = sources[i]; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () { self(i + 1); } )); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }; return ConcatObservable; }(ObservableBase)); /** * 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 new ConcatObservable(args); }; /** * 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 = 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; }; 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, 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, 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) { 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 MergeAllObservable; }(ObservableBase)); /** * 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 = 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(null, 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 BinaryDisposable(subscription, cancelable); }); }; var SkipUntilObservable = (function(__super__) { inherits(SkipUntilObservable, __super__); function SkipUntilObservable(source, other) { this._s = source; this._o = isPromise(other) ? observableFromPromise(other) : other; this._open = false; __super__.call(this); } SkipUntilObservable.prototype.subscribeCore = function(o) { var leftSubscription = new SingleAssignmentDisposable(); leftSubscription.setDisposable(this._s.subscribe(new SkipUntilSourceObserver(o, this))); isPromise(this._o) && (this._o = observableFromPromise(this._o)); var rightSubscription = new SingleAssignmentDisposable(); rightSubscription.setDisposable(this._o.subscribe(new SkipUntilOtherObserver(o, this, rightSubscription))); return new BinaryDisposable(leftSubscription, rightSubscription); }; return SkipUntilObservable; }(ObservableBase)); var SkipUntilSourceObserver = (function(__super__) { inherits(SkipUntilSourceObserver, __super__); function SkipUntilSourceObserver(o, p) { this._o = o; this._p = p; __super__.call(this); } SkipUntilSourceObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); }; SkipUntilSourceObserver.prototype.error = function (err) { this._o.onError(err); }; SkipUntilSourceObserver.prototype.onCompleted = function () { this._p._open && this._o.onCompleted(); }; return SkipUntilSourceObserver; }(AbstractObserver)); var SkipUntilOtherObserver = (function(__super__) { inherits(SkipUntilOtherObserver, __super__); function SkipUntilOtherObserver(o, p, r) { this._o = o; this._p = p; this._r = r; __super__.call(this); } SkipUntilOtherObserver.prototype.next = function () { this._p._open = true; this._r.dispose(); }; SkipUntilOtherObserver.prototype.error = function (err) { this._o.onError(err); }; SkipUntilOtherObserver.prototype.onCompleted = function () { this._r.dispose(); }; return SkipUntilOtherObserver; }(AbstractObserver)); /** * 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) { return new SkipUntilObservable(this, other); }; var SwitchObservable = (function(__super__) { inherits(SwitchObservable, __super__); function SwitchObservable(source) { this.source = source; __super__.call(this); } SwitchObservable.prototype.subscribeCore = function (o) { var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner)); return new BinaryDisposable(s, inner); }; inherits(SwitchObserver, AbstractObserver); function SwitchObserver(o, inner) { this.o = o; this.inner = inner; this.stopped = false; this.latest = 0; this.hasLatest = false; AbstractObserver.call(this); } SwitchObserver.prototype.next = function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++this.latest; this.hasLatest = true; this.inner.setDisposable(d); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe(new InnerObserver(this, id))); }; SwitchObserver.prototype.error = function (e) { this.o.onError(e); }; SwitchObserver.prototype.completed = function () { this.stopped = true; !this.hasLatest && this.o.onCompleted(); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(parent, id) { this.parent = parent; this.id = id; AbstractObserver.call(this); } InnerObserver.prototype.next = function (x) { this.parent.latest === this.id && this.parent.o.onNext(x); }; InnerObserver.prototype.error = function (e) { this.parent.latest === this.id && this.parent.o.onError(e); }; InnerObserver.prototype.completed = function () { if (this.parent.latest === this.id) { this.parent.hasLatest = false; this.parent.isStopped && this.parent.o.onCompleted(); } }; return SwitchObservable; }(ObservableBase)); /** * 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 () { return new SwitchObservable(this); }; var TakeUntilObservable = (function(__super__) { inherits(TakeUntilObservable, __super__); function TakeUntilObservable(source, other) { this.source = source; this.other = isPromise(other) ? observableFromPromise(other) : other; __super__.call(this); } TakeUntilObservable.prototype.subscribeCore = function(o) { return new BinaryDisposable( this.source.subscribe(o), this.other.subscribe(new TakeUntilObserver(o)) ); }; return TakeUntilObservable; }(ObservableBase)); var TakeUntilObserver = (function(__super__) { inherits(TakeUntilObserver, __super__); function TakeUntilObserver(o) { this._o = o; __super__.call(this); } TakeUntilObserver.prototype.next = function () { this._o.onCompleted(); }; TakeUntilObserver.prototype.error = function (err) { this._o.onError(err); }; TakeUntilObserver.prototype.onCompleted = noop; return TakeUntilObserver; }(AbstractObserver)); /** * 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) { return new TakeUntilObservable(this, other); }; function falseFactory() { return false; } function argumentsToArray() { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return args; } var WithLatestFromObservable = (function(__super__) { inherits(WithLatestFromObservable, __super__); function WithLatestFromObservable(source, sources, resultSelector) { var len = sources.length; this._s = source; this._ss = sources; this._cb = resultSelector; this._hv = arrayInitialize(len, falseFactory); this._hvAll = false; this._v = new Array(len); __super__.call(this); } WithLatestFromObservable.prototype.subscribeCore = function (o) { var n = this._ss.length, subscriptions = new Array(n + 1); for (var i = 0; i < n; i++) { var other = this._ss[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(new WithLatestFromOtherObserver(o, i, this))); subscriptions[i] = sad; } var sad = new SingleAssignmentDisposable(); sad.setDisposable(this._s.subscribe(new WithLatestFromSourceObserver(o, this))); subscriptions[n] = sad; return new NAryDisposable(subscriptions); }; return WithLatestFromObservable; }(ObservableBase)); var WithLatestFromOtherObserver = (function (__super__) { inherits(WithLatestFromOtherObserver, __super__); function WithLatestFromOtherObserver(o, i, p) { this._o = o; this._i = i; this._p = p; __super__.call(this); } WithLatestFromOtherObserver.prototype.next = function (x) { this._p._v[this._i] = x; this._p._hv[this._i] = true; this._p._hvAll = this._p._hv.every(identity); }; WithLatestFromOtherObserver.prototype.error = function (e) { this._o.onError(e); }; WithLatestFromOtherObserver.prototype.completed = noop; return WithLatestFromOtherObserver; }(AbstractObserver)); var WithLatestFromSourceObserver = (function (__super__) { inherits(WithLatestFromSourceObserver, __super__); function WithLatestFromSourceObserver(o, p) { this._o = o; this._p = p; __super__.call(this); } WithLatestFromSourceObserver.prototype.next = function (x) { var allValues = [x].concat(this._p._v); if (!this._p._hvAll) { return; } var res = tryCatch(this._p._cb).apply(null, allValues); if (res === errorObj) { return this._o.onError(res.e); } this._o.onNext(res); }; WithLatestFromSourceObserver.prototype.error = function (e) { this._o.onError(e); }; WithLatestFromSourceObserver.prototype.completed = function () { this._o.onCompleted(); }; return WithLatestFromSourceObserver; }(AbstractObserver)); /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { if (arguments.length === 0) { throw new Error('invalid arguments'); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray; Array.isArray(args[0]) && (args = args[0]); return new WithLatestFromObservable(this, args, resultSelector); }; function falseFactory() { return false; } function emptyArrayFactory() { return []; } var ZipObservable = (function(__super__) { inherits(ZipObservable, __super__); function ZipObservable(sources, resultSelector) { var len = sources.length; this._s = sources; this._cb = resultSelector; this._done = arrayInitialize(len, falseFactory); this._q = arrayInitialize(len, emptyArrayFactory); __super__.call(this); } ZipObservable.prototype.subscribeCore = function(observer) { var n = this._s.length, subscriptions = new Array(n); for (var i = 0; i < n; i++) { var source = this._s[i], sad = new SingleAssignmentDisposable(); subscriptions[i] = sad; isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(new ZipObserver(observer, i, this))); } return new NAryDisposable(subscriptions); }; return ZipObservable; }(ObservableBase)); var ZipObserver = (function (__super__) { inherits(ZipObserver, __super__); function ZipObserver(o, i, p) { this._o = o; this._i = i; this._p = p; __super__.call(this); } ZipObserver.prototype.next = function (x) { this._p._q[this._i].push(x); if (this._p._q.every(function (x) { return x.length > 0; })) { var queuedValues = this._p._q.map(function (x) { return x.shift(); }); var res = tryCatch(this._p._cb).apply(null, queuedValues); if (res === errorObj) { return this._o.onError(res.e); } this._o.onNext(res); } else if (this._p._done.filter(function (x, j) { return j !== this._i; }, this).every(identity)) { this._o.onCompleted(); } }; ZipObserver.prototype.error = function (e) { this._o.onError(e); }; ZipObserver.prototype.completed = function () { this._p._done[this._i] = true; this._p._done.every(identity) && this._o.onCompleted(); }; return ZipObserver; }(AbstractObserver)); /** * 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. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zip = function () { if (arguments.length === 0) { throw new Error('invalid arguments'); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray; Array.isArray(args[0]) && (args = args[0]); var parent = this; args.unshift(parent); return new ZipObservable(args, resultSelector); }; /** * 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]; } if (Array.isArray(args[0])) { args = isFunction(args[1]) ? args[0].concat(args[1]) : args[0]; } var first = args.shift(); return first.zip.apply(first, args); }; function falseFactory() { return false; } function emptyArrayFactory() { return []; } function argumentsToArray() { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return args; } /** * 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. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zipIterable = function () { if (arguments.length === 0) { throw new Error('invalid arguments'); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray; var parent = this; args.unshift(parent); return new AnonymousObservable(function (o) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); (isArrayLike(source) || isIterable(source)) && (source = observableFrom(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); if (queues.every(function (x) { return x.length > 0; })) { var queuedValues = queues.map(function (x) { return x.shift(); }), res = tryCatch(resultSelector).apply(parent, queuedValues); if (res === errorObj) { return o.onError(res.e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } }, function (e) { o.onError(e); }, function () { isDone[i] = true; isDone.every(identity) && o.onCompleted(); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; function asObservable(source) { return function subscribe(o) { return source.subscribe(o); }; } /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(asObservable(this), this); }; function toArray(x) { return x.toArray(); } function notEmpty(x) { return x.length > 0; } /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * @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) { typeof skip !== 'number' && (skip = count); return this.windowWithCount(count, skip) .flatMap(toArray) .filter(notEmpty); }; var DematerializeObservable = (function (__super__) { inherits(DematerializeObservable, __super__); function DematerializeObservable(source) { this.source = source; __super__.call(this); } DematerializeObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new DematerializeObserver(o)); }; return DematerializeObservable; }(ObservableBase)); var DematerializeObserver = (function (__super__) { inherits(DematerializeObserver, __super__); function DematerializeObserver(o) { this._o = o; __super__.call(this); } DematerializeObserver.prototype.next = function (x) { x.accept(this._o); }; DematerializeObserver.prototype.error = function (e) { this._o.onError(e); }; DematerializeObserver.prototype.completed = function () { this._o.onCompleted(); }; return DematerializeObserver; }(AbstractObserver)); /** * 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 () { return new DematerializeObservable(this); }; var DistinctUntilChangedObservable = (function(__super__) { inherits(DistinctUntilChangedObservable, __super__); function DistinctUntilChangedObservable(source, keyFn, comparer) { this.source = source; this.keyFn = keyFn; this.comparer = comparer; __super__.call(this); } DistinctUntilChangedObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new DistinctUntilChangedObserver(o, this.keyFn, this.comparer)); }; return DistinctUntilChangedObservable; }(ObservableBase)); var DistinctUntilChangedObserver = (function(__super__) { inherits(DistinctUntilChangedObserver, __super__); function DistinctUntilChangedObserver(o, keyFn, comparer) { this.o = o; this.keyFn = keyFn; this.comparer = comparer; this.hasCurrentKey = false; this.currentKey = null; __super__.call(this); } DistinctUntilChangedObserver.prototype.next = function (x) { var key = x, comparerEquals; if (isFunction(this.keyFn)) { key = tryCatch(this.keyFn)(x); if (key === errorObj) { return this.o.onError(key.e); } } if (this.hasCurrentKey) { comparerEquals = tryCatch(this.comparer)(this.currentKey, key); if (comparerEquals === errorObj) { return this.o.onError(comparerEquals.e); } } if (!this.hasCurrentKey || !comparerEquals) { this.hasCurrentKey = true; this.currentKey = key; this.o.onNext(x); } }; DistinctUntilChangedObserver.prototype.error = function(e) { this.o.onError(e); }; DistinctUntilChangedObserver.prototype.completed = function () { this.o.onCompleted(); }; return DistinctUntilChangedObserver; }(AbstractObserver)); /** * Returns an observable sequence that contains only distinct contiguous elements according to the keyFn and the comparer. * @param {Function} [keyFn] 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 (keyFn, comparer) { comparer || (comparer = defaultComparer); return new DistinctUntilChangedObservable(this, keyFn, comparer); }; var TapObservable = (function(__super__) { inherits(TapObservable,__super__); function TapObservable(source, observerOrOnNext, onError, onCompleted) { this.source = source; this._oN = observerOrOnNext; this._oE = onError; this._oC = onCompleted; __super__.call(this); } TapObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new InnerObserver(o, this)); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(o, p) { this.o = o; this.t = !p._oN || isFunction(p._oN) ? observerCreate(p._oN || noop, p._oE || noop, p._oC || noop) : p._oN; this.isStopped = false; AbstractObserver.call(this); } InnerObserver.prototype.next = function(x) { var res = tryCatch(this.t.onNext).call(this.t, x); if (res === errorObj) { this.o.onError(res.e); } this.o.onNext(x); }; InnerObserver.prototype.error = function(err) { var res = tryCatch(this.t.onError).call(this.t, err); if (res === errorObj) { return this.o.onError(res.e); } this.o.onError(err); }; InnerObserver.prototype.completed = function() { var res = tryCatch(this.t.onCompleted).call(this.t); if (res === errorObj) { return this.o.onError(res.e); } this.o.onCompleted(); }; return TapObservable; }(ObservableBase)); /** * 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 o. * @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) { return new TapObservable(this, observerOrOnNext, onError, onCompleted); }; /** * 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'] = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription = tryCatch(source.subscribe).call(source, observer); if (subscription === errorObj) { action(); return thrower(subscription.e); } return disposableCreate(function () { var r = tryCatch(subscription.dispose).call(subscription); action(); r === errorObj && thrower(r.e); }); }, this); }; var IgnoreElementsObservable = (function(__super__) { inherits(IgnoreElementsObservable, __super__); function IgnoreElementsObservable(source) { this.source = source; __super__.call(this); } IgnoreElementsObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o)); }; function InnerObserver(o) { this.o = o; this.isStopped = false; } InnerObserver.prototype.onNext = noop; InnerObserver.prototype.onError = function (err) { if(!this.isStopped) { this.isStopped = true; this.o.onError(err); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; return IgnoreElementsObservable; }(ObservableBase)); /** * 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 () { return new IgnoreElementsObservable(this); }; var MaterializeObservable = (function (__super__) { inherits(MaterializeObservable, __super__); function MaterializeObservable(source, fn) { this.source = source; __super__.call(this); } MaterializeObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new MaterializeObserver(o)); }; return MaterializeObservable; }(ObservableBase)); var MaterializeObserver = (function (__super__) { inherits(MaterializeObserver, __super__); function MaterializeObserver(o) { this._o = o; __super__.call(this); } MaterializeObserver.prototype.next = function (x) { this._o.onNext(notificationCreateOnNext(x)) }; MaterializeObserver.prototype.error = function (e) { this._o.onNext(notificationCreateOnError(e)); this._o.onCompleted(); }; MaterializeObserver.prototype.completed = function () { this._o.onNext(notificationCreateOnCompleted()); this._o.onCompleted(); }; return MaterializeObserver; }(AbstractObserver)); /** * 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 () { return new MaterializeObservable(this); }; /** * 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); }; var ScanObservable = (function(__super__) { inherits(ScanObservable, __super__); function ScanObservable(source, accumulator, hasSeed, seed) { this.source = source; this.accumulator = accumulator; this.hasSeed = hasSeed; this.seed = seed; __super__.call(this); } ScanObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new ScanObserver(o,this)); }; return ScanObservable; }(ObservableBase)); var ScanObserver = (function (__super__) { inherits(ScanObserver, __super__); function ScanObserver(o, parent) { this._o = o; this._p = parent; this._fn = parent.accumulator; this._hs = parent.hasSeed; this._s = parent.seed; this._ha = false; this._a = null; this._hv = false; this._i = 0; __super__.call(this); } ScanObserver.prototype.next = function (x) { !this._hv && (this._hv = true); if (this._ha) { this._a = tryCatch(this._fn)(this._a, x, this._i, this._p); } else { this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x; this._ha = true; } if (this._a === errorObj) { return this._o.onError(this._a.e); } this._o.onNext(this._a); this._i++; }; ScanObserver.prototype.error = function (e) { this._o.onError(e); }; ScanObserver.prototype.completed = function () { !this._hv && this._hs && this._o.onNext(this._s); this._o.onCompleted(); }; return ScanObserver; }(AbstractObserver)); /** * 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. * @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 = arguments[0]; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return new ScanObservable(this, accumulator, hasSeed, seed); }; var SkipLastObservable = (function (__super__) { inherits(SkipLastObservable, __super__); function SkipLastObservable(source, c) { this.source = source; this._c = c; __super__.call(this); } SkipLastObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new SkipLastObserver(o, this._c)); }; return SkipLastObservable; }(ObservableBase)); var SkipLastObserver = (function (__super__) { inherits(SkipLastObserver, __super__); function SkipLastObserver(o, c) { this._o = o; this._c = c; this._q = []; __super__.call(this); } SkipLastObserver.prototype.next = function (x) { this._q.push(x); this._q.length > this._c && this._o.onNext(this._q.shift()); }; SkipLastObserver.prototype.error = function (e) { this._o.onError(e); }; SkipLastObserver.prototype.completed = function () { this._o.onCompleted(); }; return SkipLastObserver; }(AbstractObserver)); /** * 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(); } return new SkipLastObservable(this, count); }; /** * 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(); }; var TakeLastObserver = (function (__super__) { inherits(TakeLastObserver, __super__); function TakeLastObserver(o, c) { this._o = o; this._c = c; this._q = []; __super__.call(this); } TakeLastObserver.prototype.next = function (x) { this._q.push(x); this._q.length > this._c && this._q.shift(); }; TakeLastObserver.prototype.error = function (e) { this._o.onError(e); }; TakeLastObserver.prototype.completed = function () { while (this._q.length > 0) { this._o.onNext(this._q.shift()); } this._o.onCompleted(); }; return TakeLastObserver; }(AbstractObserver)); /** * 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) { return source.subscribe(new TakeLastObserver(o, count)); }, source); }; var TakeLastBufferObserver = (function (__super__) { inherits(TakeLastBufferObserver, __super__); function TakeLastBufferObserver(o, c) { this._o = o; this._c = c; this._q = []; __super__.call(this); } TakeLastBufferObserver.prototype.next = function (x) { this._q.push(x); this._q.length > this._c && this._q.shift(); }; TakeLastBufferObserver.prototype.error = function (e) { this._o.onError(e); }; TakeLastBufferObserver.prototype.completed = function () { this._o.onNext(this._q); this._o.onCompleted(); }; return TakeLastBufferObserver; }(AbstractObserver)); /** * 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) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { return source.subscribe(new TakeLastBufferObserver(o, count)); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * @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(); }; var DefaultIfEmptyObserver = (function (__super__) { inherits(DefaultIfEmptyObserver, __super__); function DefaultIfEmptyObserver(o, d) { this._o = o; this._d = d; this._f = false; __super__.call(this); } DefaultIfEmptyObserver.prototype.next = function (x) { this._f = true; this._o.onNext(x); }; DefaultIfEmptyObserver.prototype.error = function (e) { this._o.onError(e); }; DefaultIfEmptyObserver.prototype.completed = function () { !this._f && this._o.onNext(defaultValue); this._o.onCompleted(); }; return DefaultIfEmptyObserver; }(AbstractObserver)); /** * 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 (o) { return source.subscribe(new DefaultIfEmptyObserver(o, defaultValue)); }, 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; }; var DistinctObservable = (function (__super__) { inherits(DistinctObservable, __super__); function DistinctObservable(source, keyFn, cmpFn) { this.source = source; this._keyFn = keyFn; this._cmpFn = cmpFn; __super__.call(this); } DistinctObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new DistinctObserver(o, this._keyFn, this._cmpFn)); }; return DistinctObservable; }(ObservableBase)); var DistinctObserver = (function (__super__) { inherits(DistinctObserver, __super__); function DistinctObserver(o, keyFn, cmpFn) { this._o = o; this._keyFn = keyFn; this._h = new HashSet(cmpFn); __super__.call(this); } DistinctObserver.prototype.next = function (x) { var key = x; if (isFunction(this._keyFn)) { key = tryCatch(this._keyFn)(x); if (key === errorObj) { return this._o.onError(key.e); } } this._h.push(key) && this._o.onNext(x); }; DistinctObserver.prototype.error = function (e) { this._o.onError(e); }; DistinctObserver.prototype.completed = function () { this._o.onCompleted(); }; return DistinctObserver; }(AbstractObserver)); /** * 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) { comparer || (comparer = defaultComparer); return new DistinctObservable(this, keySelector, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector) { return this.groupByUntil(keySelector, elementSelector, observableNever); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector) { var source = this; return new AnonymousObservable(function (o) { var map = new Map(), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable), handleError = function (e) { return function (item) { item.onError(e); }; }; groupDisposable.add( source.subscribe(function (x) { var key = tryCatch(keySelector)(x); if (key === errorObj) { map.forEach(handleError(key.e)); return o.onError(key.e); } var fireNewMapEntry = false, writer = map.get(key); if (writer === undefined) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); var duration = tryCatch(durationSelector)(durationGroup); if (duration === errorObj) { map.forEach(handleError(duration.e)); return o.onError(duration.e); } o.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); md.setDisposable(duration.take(1).subscribe( noop, function (e) { map.forEach(handleError(e)); o.onError(e); }, function () { if (map['delete'](key)) { writer.onCompleted(); } groupDisposable.remove(md); })); } var element = x; if (isFunction(elementSelector)) { element = tryCatch(elementSelector)(x); if (element === errorObj) { map.forEach(handleError(element.e)); return o.onError(element.e); } } writer.onNext(element); }, function (e) { map.forEach(handleError(e)); o.onError(e); }, function () { map.forEach(function (item) { item.onCompleted(); }); o.onCompleted(); })); return refCountDisposable; }, source); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } function innerMap(selector, self) { return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); } } MapObservable.prototype.internalMap = function (selector, thisArg) { return new MapObservable(this.source, innerMap(selector, this), thisArg); }; MapObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.selector, this)); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(o, selector, source) { this.o = o; this.selector = selector; this.source = source; this.i = 0; AbstractObserver.call(this); } InnerObserver.prototype.next = function(x) { var result = tryCatch(this.selector)(x, this.i++, this.source); if (result === errorObj) { return this.o.onError(result.e); } this.o.onNext(result); }; InnerObserver.prototype.error = function (e) { this.o.onError(e); }; InnerObserver.prototype.completed = function () { this.o.onCompleted(); }; return MapObservable; }(ObservableBase)); /** * 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); }; function plucker(args, len) { return function mapper(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; } } /** * 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 len = arguments.length, args = new Array(len); if (len === 0) { throw new Error('List of properties cannot be empty.'); } for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return this.map(plucker(args, len)); }; observableProto.flatMap = observableProto.selectMany = function(selector, resultSelector, thisArg) { return new FlatMapObservable(this, selector, resultSelector, thisArg).mergeAll(); }; // //Rx.Observable.prototype.flatMapWithMaxConcurrent = function(limit, selector, resultSelector, thisArg) { // return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(limit); //}; // /** * 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(); }; Rx.Observable.prototype.flatMapLatest = function(selector, resultSelector, thisArg) { return new FlatMapObservable(this, selector, resultSelector, thisArg).switchLatest(); }; var SkipObservable = (function(__super__) { inherits(SkipObservable, __super__); function SkipObservable(source, count) { this.source = source; this.skipCount = count; __super__.call(this); } SkipObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.skipCount)); }; function InnerObserver(o, c) { this.c = c; this.r = c; this.o = o; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } if (this.r <= 0) { this.o.onNext(x); } else { this.r--; } }; InnerObserver.prototype.onError = function(e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function() { if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function(e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return SkipObservable; }(ObservableBase)); /** * 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(); } return new SkipObservable(this, count); }; var SkipWhileObservable = (function (__super__) { inherits(SkipWhileObservable, __super__); function SkipWhileObservable(source, fn) { this.source = source; this._fn = fn; __super__.call(this); } SkipWhileObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new SkipWhileObserver(o, this)); }; return SkipWhileObservable; }(ObservableBase)); var SkipWhileObserver = (function (__super__) { inherits(SkipWhileObserver, __super__); function SkipWhileObserver(o, p) { this._o = o; this._p = p; this._i = 0; this._r = false; __super__.call(this); } SkipWhileObserver.prototype.next = function (x) { if (!this._r) { var res = tryCatch(this._p._fn)(x, this._i++, this._p); if (res === errorObj) { return this._o.onError(res.e); } this._r = !res; } this._r && this._o.onNext(x); }; SkipWhileObserver.prototype.error = function (e) { this._o.onError(e); }; SkipWhileObserver.prototype.completed = function () { this._o.onCompleted(); }; return SkipWhileObserver; }(AbstractObserver)); /** * 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 fn = bindCallback(predicate, thisArg, 3); return new SkipWhileObservable(this, fn); }; var TakeObservable = (function(__super__) { inherits(TakeObservable, __super__); function TakeObservable(source, count) { this.source = source; this.takeCount = count; __super__.call(this); } TakeObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.takeCount)); }; function InnerObserver(o, c) { this.o = o; this.c = c; this.r = c; this.isStopped = false; } InnerObserver.prototype = { onNext: function (x) { if (this.isStopped) { return; } if (this.r-- > 0) { this.o.onNext(x); this.r <= 0 && this.o.onCompleted(); } }, onError: function (err) { if (!this.isStopped) { this.isStopped = true; this.o.onError(err); } }, onCompleted: function () { if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }, dispose: function () { this.isStopped = true; }, fail: function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; } }; return TakeObservable; }(ObservableBase)); /** * 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). * @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); } return new TakeObservable(this, count); }; var TakeWhileObservable = (function (__super__) { inherits(TakeWhileObservable, __super__); function TakeWhileObservable(source, fn) { this.source = source; this._fn = fn; __super__.call(this); } TakeWhileObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new TakeWhileObserver(o, this)); }; return TakeWhileObservable; }(ObservableBase)); var TakeWhileObserver = (function (__super__) { inherits(TakeWhileObserver, __super__); function TakeWhileObserver(o, p) { this._o = o; this._p = p; this._i = 0; this._r = true; __super__.call(this); } TakeWhileObserver.prototype.next = function (x) { if (this._r) { this._r = tryCatch(this._p._fn)(x, this._i++, this._p); if (this._r === errorObj) { return this._o.onError(this._r.e); } } if (this._r) { this._o.onNext(x); } else { this._o.onCompleted(); } }; TakeWhileObserver.prototype.error = function (e) { this._o.onError(e); }; TakeWhileObserver.prototype.completed = function () { this._o.onCompleted(); }; return TakeWhileObserver; }(AbstractObserver)); /** * 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 fn = bindCallback(predicate, thisArg, 3); return new TakeWhileObservable(this, fn); }; 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 (o) { return this.source.subscribe(new InnerObserver(o, this.predicate, this)); }; function innerPredicate(predicate, self) { return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); } } FilterObservable.prototype.internalFilter = function(predicate, thisArg) { return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg); }; inherits(InnerObserver, AbstractObserver); function InnerObserver(o, predicate, source) { this.o = o; this.predicate = predicate; this.source = source; this.i = 0; AbstractObserver.call(this); } InnerObserver.prototype.next = function(x) { var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source); if (shouldYield === errorObj) { return this.o.onError(shouldYield.e); } shouldYield && this.o.onNext(x); }; InnerObserver.prototype.error = function (e) { this.o.onError(e); }; InnerObserver.prototype.completed = function () { this.o.onCompleted(); }; return FilterObservable; }(ObservableBase)); /** * 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); }; var ExtremaByObservable = (function (__super__) { inherits(ExtremaByObservable, __super__); function ExtremaByObservable(source, k, c) { this.source = source; this._k = k; this._c = c; __super__.call(this); } ExtremaByObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new ExtremaByObserver(o, this._k, this._c)); }; return ExtremaByObservable; }(ObservableBase)); var ExtremaByObserver = (function (__super__) { inherits(ExtremaByObserver, __super__); function ExtremaByObserver(o, k, c) { this._o = o; this._k = k; this._c = c; this._v = null; this._hv = false; this._l = []; __super__.call(this); } ExtremaByObserver.prototype.next = function (x) { var key = tryCatch(this._k)(x); if (key === errorObj) { return this._o.onError(key.e); } var comparison = 0; if (!this._hv) { this._hv = true; this._v = key; } else { comparison = tryCatch(this._c)(key, this._v); if (comparison === errorObj) { return this._o.onError(comparison.e); } } if (comparison > 0) { this._v = key; this._l = []; } if (comparison >= 0) { this._l.push(x); } }; ExtremaByObserver.prototype.error = function (e) { this._o.onError(e); }; ExtremaByObserver.prototype.completed = function () { this._o.onNext(this._l); this._o.onCompleted(); }; return ExtremaByObserver; }(AbstractObserver)); function firstOnly(x) { if (x.length === 0) { throw new EmptyError(); } return x[0]; } var ReduceObservable = (function(__super__) { inherits(ReduceObservable, __super__); function ReduceObservable(source, accumulator, hasSeed, seed) { this.source = source; this.accumulator = accumulator; this.hasSeed = hasSeed; this.seed = seed; __super__.call(this); } ReduceObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ReduceObserver(observer,this)); }; return ReduceObservable; }(ObservableBase)); var ReduceObserver = (function (__super__) { inherits(ReduceObserver, __super__); function ReduceObserver(o, parent) { this._o = o; this._p = parent; this._fn = parent.accumulator; this._hs = parent.hasSeed; this._s = parent.seed; this._ha = false; this._a = null; this._hv = false; this._i = 0; __super__.call(this); } ReduceObserver.prototype.next = function (x) { !this._hv && (this._hv = true); if (this._ha) { this._a = tryCatch(this._fn)(this._a, x, this._i, this._p); } else { this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x; this._ha = true; } if (this._a === errorObj) { return this._o.onError(this._a.e); } this._i++; }; ReduceObserver.prototype.error = function (e) { this._o.onError(e); }; ReduceObserver.prototype.completed = function () { this._hv && this._o.onNext(this._a); !this._hv && this._hs && this._o.onNext(this._s); !this._hv && !this._hs && this._o.onError(new EmptyError()); this._o.onCompleted(); }; return ReduceObserver; }(AbstractObserver)); /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function () { var hasSeed = false, seed, accumulator = arguments[0]; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return new ReduceObservable(this, accumulator, hasSeed, seed); }; var SomeObservable = (function (__super__) { inherits(SomeObservable, __super__); function SomeObservable(source, fn) { this.source = source; this._fn = fn; __super__.call(this); } SomeObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new SomeObserver(o, this._fn, this.source)); }; return SomeObservable; }(ObservableBase)); var SomeObserver = (function (__super__) { inherits(SomeObserver, __super__); function SomeObserver(o, fn, s) { this._o = o; this._fn = fn; this._s = s; this._i = 0; __super__.call(this); } SomeObserver.prototype.next = function (x) { var result = tryCatch(this._fn)(x, this._i++, this._s); if (result === errorObj) { return this._o.onError(result.e); } if (Boolean(result)) { this._o.onNext(true); this._o.onCompleted(); } }; SomeObserver.prototype.error = function (e) { this._o.onError(e); }; SomeObserver.prototype.completed = function () { this._o.onNext(false); this._o.onCompleted(); }; return SomeObserver; }(AbstractObserver)); /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = function (predicate, thisArg) { var fn = bindCallback(predicate, thisArg, 3); return new SomeObservable(this, fn); }; var IsEmptyObservable = (function (__super__) { inherits(IsEmptyObservable, __super__); function IsEmptyObservable(source) { this.source = source; __super__.call(this); } IsEmptyObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new IsEmptyObserver(o)); }; return IsEmptyObservable; }(ObservableBase)); var IsEmptyObserver = (function(__super__) { inherits(IsEmptyObserver, __super__); function IsEmptyObserver(o) { this._o = o; __super__.call(this); } IsEmptyObserver.prototype.next = function () { this._o.onNext(false); this._o.onCompleted(); }; IsEmptyObserver.prototype.error = function (e) { this._o.onError(e); }; IsEmptyObserver.prototype.completed = function () { this._o.onNext(true); this._o.onCompleted(); }; return IsEmptyObserver; }(AbstractObserver)); /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return new IsEmptyObservable(this); }; var EveryObservable = (function (__super__) { inherits(EveryObservable, __super__); function EveryObservable(source, fn) { this.source = source; this._fn = fn; __super__.call(this); } EveryObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new EveryObserver(o, this._fn, this.source)); }; return EveryObservable; }(ObservableBase)); var EveryObserver = (function (__super__) { inherits(EveryObserver, __super__); function EveryObserver(o, fn, s) { this._o = o; this._fn = fn; this._s = s; this._i = 0; __super__.call(this); } EveryObserver.prototype.next = function (x) { var result = tryCatch(this._fn)(x, this._i++, this._s); if (result === errorObj) { return this._o.onError(result.e); } if (!Boolean(result)) { this._o.onNext(false); this._o.onCompleted(); } }; EveryObserver.prototype.error = function (e) { this._o.onError(e); }; EveryObserver.prototype.completed = function () { this._o.onNext(true); this._o.onCompleted(); }; return EveryObserver; }(AbstractObserver)); /** * Determines whether all elements of an observable sequence satisfy a condition. * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = function (predicate, thisArg) { var fn = bindCallback(predicate, thisArg, 3); return new EveryObservable(this, fn); }; var IncludesObservable = (function (__super__) { inherits(IncludesObservable, __super__); function IncludesObservable(source, elem, idx) { var n = +idx || 0; Math.abs(n) === Infinity && (n = 0); this.source = source; this._elem = elem; this._n = n; __super__.call(this); } IncludesObservable.prototype.subscribeCore = function (o) { if (this._n < 0) { o.onNext(false); o.onCompleted(); return disposableEmpty; } return this.source.subscribe(new IncludesObserver(o, this._elem, this._n)); }; return IncludesObservable; }(ObservableBase)); var IncludesObserver = (function (__super__) { inherits(IncludesObserver, __super__); function IncludesObserver(o, elem, n) { this._o = o; this._elem = elem; this._n = n; this._i = 0; __super__.call(this); } function comparer(a, b) { return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b))); } IncludesObserver.prototype.next = function (x) { if (this._i++ >= this._n && comparer(x, this._elem)) { this._o.onNext(true); this._o.onCompleted(); } }; IncludesObserver.prototype.error = function (e) { this._o.onError(e); }; IncludesObserver.prototype.completed = function () { this._o.onNext(false); this._o.onCompleted(); }; return IncludesObserver; }(AbstractObserver)); /** * Determines whether an observable sequence includes a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index. */ observableProto.includes = function (searchElement, fromIndex) { return new IncludesObservable(this, searchElement, fromIndex); }; var CountObservable = (function (__super__) { inherits(CountObservable, __super__); function CountObservable(source, fn) { this.source = source; this._fn = fn; __super__.call(this); } CountObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new CountObserver(o, this._fn, this.source)); }; return CountObservable; }(ObservableBase)); var CountObserver = (function (__super__) { inherits(CountObserver, __super__); function CountObserver(o, fn, s) { this._o = o; this._fn = fn; this._s = s; this._i = 0; this._c = 0; __super__.call(this); } CountObserver.prototype.next = function (x) { if (this._fn) { var result = tryCatch(this._fn)(x, this._i++, this._s); if (result === errorObj) { return this._o.onError(result.e); } Boolean(result) && (this._c++); } else { this._c++; } }; CountObserver.prototype.error = function (e) { this._o.onError(e); }; CountObserver.prototype.completed = function () { this._o.onNext(this._c); this._o.onCompleted(); }; return CountObserver; }(AbstractObserver)); /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { var fn = bindCallback(predicate, thisArg, 3); return new CountObservable(this, fn); }; var IndexOfObservable = (function (__super__) { inherits(IndexOfObservable, __super__); function IndexOfObservable(source, e, n) { this.source = source; this._e = e; this._n = n; __super__.call(this); } IndexOfObservable.prototype.subscribeCore = function (o) { if (this._n < 0) { o.onNext(-1); o.onCompleted(); return disposableEmpty; } return this.source.subscribe(new IndexOfObserver(o, this._e, this._n)); }; return IndexOfObservable; }(ObservableBase)); var IndexOfObserver = (function (__super__) { inherits(IndexOfObserver, __super__); function IndexOfObserver(o, e, n) { this._o = o; this._e = e; this._n = n; this._i = 0; __super__.call(this); } IndexOfObserver.prototype.next = function (x) { if (this._i >= this._n && x === this._e) { this._o.onNext(this._i); this._o.onCompleted(); } this._i++; }; IndexOfObserver.prototype.error = function (e) { this._o.onError(e); }; IndexOfObserver.prototype.completed = function () { this._o.onNext(-1); this._o.onCompleted(); }; return IndexOfObserver; }(AbstractObserver)); /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.indexOf = function(searchElement, fromIndex) { var n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); return new IndexOfObservable(this, searchElement, n); }; var SumObservable = (function (__super__) { inherits(SumObservable, __super__); function SumObservable(source, fn) { this.source = source; this._fn = fn; __super__.call(this); } SumObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new SumObserver(o, this._fn, this.source)); }; return SumObservable; }(ObservableBase)); var SumObserver = (function (__super__) { inherits(SumObserver, __super__); function SumObserver(o, fn, s) { this._o = o; this._fn = fn; this._s = s; this._i = 0; this._c = 0; __super__.call(this); } SumObserver.prototype.next = function (x) { if (this._fn) { var result = tryCatch(this._fn)(x, this._i++, this._s); if (result === errorObj) { return this._o.onError(result.e); } this._c += result; } else { this._c += x; } }; SumObserver.prototype.error = function (e) { this._o.onError(e); }; SumObserver.prototype.completed = function () { this._o.onNext(this._c); this._o.onCompleted(); }; return SumObserver; }(AbstractObserver)); /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { var fn = bindCallback(keySelector, thisArg, 3); return new SumObservable(this, fn); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return new ExtremaByObservable(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return new ExtremaByObservable(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; var AverageObservable = (function (__super__) { inherits(AverageObservable, __super__); function AverageObservable(source, fn) { this.source = source; this._fn = fn; __super__.call(this); } AverageObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new AverageObserver(o, this._fn, this.source)); }; return AverageObservable; }(ObservableBase)); var AverageObserver = (function(__super__) { inherits(AverageObserver, __super__); function AverageObserver(o, fn, s) { this._o = o; this._fn = fn; this._s = s; this._c = 0; this._t = 0; __super__.call(this); } AverageObserver.prototype.next = function (x) { if(this._fn) { var r = tryCatch(this._fn)(x, this._c++, this._s); if (r === errorObj) { return this._o.onError(r.e); } this._t += r; } else { this._c++; this._t += x; } }; AverageObserver.prototype.error = function (e) { this._o.onError(e); }; AverageObserver.prototype.completed = function () { if (this._c === 0) { return this._o.onError(new EmptyError()); } this._o.onNext(this._t / this._c); this._o.onCompleted(); }; return AverageObserver; }(AbstractObserver)); /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { var source = this, fn; if (isFunction(keySelector)) { fn = bindCallback(keySelector, thisArg, 3); } return new AverageObservable(source, fn); }; /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { if (qr.length > 0) { var v = qr.shift(); var equal = tryCatch(comparer)(v, x); if (equal === errorObj) { return o.onError(equal.e); } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (doner) { o.onNext(false); o.onCompleted(); } else { ql.push(x); } }, function(e) { o.onError(e); }, function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { o.onNext(false); o.onCompleted(); } else if (doner) { o.onNext(true); o.onCompleted(); } } }); (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second)); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { if (ql.length > 0) { var v = ql.shift(); var equal = tryCatch(comparer)(v, x); if (equal === errorObj) { return o.onError(equal.e); } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (donel) { o.onNext(false); o.onCompleted(); } else { qr.push(x); } }, function(e) { o.onError(e); }, function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { o.onNext(false); o.onCompleted(); } else if (donel) { o.onNext(true); o.onCompleted(); } } }); return new BinaryDisposable(subscription1, subscription2); }, first); }; var ElementAtObservable = (function (__super__) { inherits(ElementAtObservable, __super__); function ElementAtObservable(source, i, d) { this.source = source; this._i = i; this._d = d; __super__.call(this); } ElementAtObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new ElementAtObserver(o, this._i, this._d)); }; return ElementAtObservable; }(ObservableBase)); var ElementAtObserver = (function (__super__) { inherits(ElementAtObserver, __super__); function ElementAtObserver(o, i, d) { this._o = o; this._i = i; this._d = d; __super__.call(this); } ElementAtObserver.prototype.next = function (x) { if (this._i-- === 0) { this._o.onNext(x); this._o.onCompleted(); } }; ElementAtObserver.prototype.error = function (e) { this._o.onError(e); }; ElementAtObserver.prototype.completed = function () { if (this._d === undefined) { this._o.onError(new ArgumentOutOfRangeError()); } else { this._o.onNext(this._d); this._o.onCompleted(); } }; return ElementAtObserver; }(AbstractObserver)); /** * Returns the element at a specified index in a sequence or default value if not found. * @param {Number} index The zero-based index of the element to retrieve. * @param {Any} [defaultValue] The default value to use if elementAt does not find a value. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index, defaultValue) { if (index < 0) { throw new ArgumentOutOfRangeError(); } return new ElementAtObservable(this, index, defaultValue); }; var SingleObserver = (function(__super__) { inherits(SingleObserver, __super__); function SingleObserver(o, obj, s) { this._o = o; this._obj = obj; this._s = s; this._i = 0; this._hv = false; this._v = null; __super__.call(this); } SingleObserver.prototype.next = function (x) { var shouldYield = false; if (this._obj.predicate) { var res = tryCatch(this._obj.predicate)(x, this._i++, this._s); if (res === errorObj) { return this._o.onError(res.e); } Boolean(res) && (shouldYield = true); } else if (!this._obj.predicate) { shouldYield = true; } if (shouldYield) { if (this._hv) { return this._o.onError(new Error('Sequence contains more than one matching element')); } this._hv = true; this._v = x; } }; SingleObserver.prototype.error = function (e) { this._o.onError(e); }; SingleObserver.prototype.completed = function () { if (this._hv) { this._o.onNext(this._v); this._o.onCompleted(); } else if (this._obj.defaultValue === undefined) { this._o.onError(new EmptyError()); } else { this._o.onNext(this._obj.defaultValue); this._o.onCompleted(); } }; return SingleObserver; }(AbstractObserver)); /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { var obj = {}, source = this; if (typeof arguments[0] === 'object') { obj = arguments[0]; } else { obj = { predicate: arguments[0], thisArg: arguments[1], defaultValue: arguments[2] }; } if (isFunction (obj.predicate)) { var fn = obj.predicate; obj.predicate = bindCallback(fn, obj.thisArg, 3); } return new AnonymousObservable(function (o) { return source.subscribe(new SingleObserver(o, obj, source)); }, source); }; var FirstObservable = (function (__super__) { inherits(FirstObservable, __super__); function FirstObservable(source, obj) { this.source = source; this._obj = obj; __super__.call(this); } FirstObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new FirstObserver(o, this._obj, this.source)); }; return FirstObservable; }(ObservableBase)); var FirstObserver = (function(__super__) { inherits(FirstObserver, __super__); function FirstObserver(o, obj, s) { this._o = o; this._obj = obj; this._s = s; this._i = 0; __super__.call(this); } FirstObserver.prototype.next = function (x) { if (this._obj.predicate) { var res = tryCatch(this._obj.predicate)(x, this._i++, this._s); if (res === errorObj) { return this._o.onError(res.e); } if (Boolean(res)) { this._o.onNext(x); this._o.onCompleted(); } } else if (!this._obj.predicate) { this._o.onNext(x); this._o.onCompleted(); } }; FirstObserver.prototype.error = function (e) { this._o.onError(e); }; FirstObserver.prototype.completed = function () { if (this._obj.defaultValue === undefined) { this._o.onError(new EmptyError()); } else { this._o.onNext(this._obj.defaultValue); this._o.onCompleted(); } }; return FirstObserver; }(AbstractObserver)); /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function () { var obj = {}, source = this; if (typeof arguments[0] === 'object') { obj = arguments[0]; } else { obj = { predicate: arguments[0], thisArg: arguments[1], defaultValue: arguments[2] }; } if (isFunction (obj.predicate)) { var fn = obj.predicate; obj.predicate = bindCallback(fn, obj.thisArg, 3); } return new FirstObservable(this, obj); }; var LastObservable = (function (__super__) { inherits(LastObservable, __super__); function LastObservable(source, obj) { this.source = source; this._obj = obj; __super__.call(this); } LastObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new LastObserver(o, this._obj, this.source)); }; return LastObservable; }(ObservableBase)); var LastObserver = (function(__super__) { inherits(LastObserver, __super__); function LastObserver(o, obj, s) { this._o = o; this._obj = obj; this._s = s; this._i = 0; this._hv = false; this._v = null; __super__.call(this); } LastObserver.prototype.next = function (x) { var shouldYield = false; if (this._obj.predicate) { var res = tryCatch(this._obj.predicate)(x, this._i++, this._s); if (res === errorObj) { return this._o.onError(res.e); } Boolean(res) && (shouldYield = true); } else if (!this._obj.predicate) { shouldYield = true; } if (shouldYield) { this._hv = true; this._v = x; } }; LastObserver.prototype.error = function (e) { this._o.onError(e); }; LastObserver.prototype.completed = function () { if (this._hv) { this._o.onNext(this._v); this._o.onCompleted(); } else if (this._obj.defaultValue === undefined) { this._o.onError(new EmptyError()); } else { this._o.onNext(this._obj.defaultValue); this._o.onCompleted(); } }; return LastObserver; }(AbstractObserver)); /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function () { var obj = {}, source = this; if (typeof arguments[0] === 'object') { obj = arguments[0]; } else { obj = { predicate: arguments[0], thisArg: arguments[1], defaultValue: arguments[2] }; } if (isFunction (obj.predicate)) { var fn = obj.predicate; obj.predicate = bindCallback(fn, obj.thisArg, 3); } return new LastObservable(this, obj); }; var FindValueObserver = (function(__super__) { inherits(FindValueObserver, __super__); function FindValueObserver(observer, source, callback, yieldIndex) { this._o = observer; this._s = source; this._cb = callback; this._y = yieldIndex; this._i = 0; __super__.call(this); } FindValueObserver.prototype.next = function (x) { var shouldRun = tryCatch(this._cb)(x, this._i, this._s); if (shouldRun === errorObj) { return this._o.onError(shouldRun.e); } if (shouldRun) { this._o.onNext(this._y ? this._i : x); this._o.onCompleted(); } else { this._i++; } }; FindValueObserver.prototype.error = function (e) { this._o.onError(e); }; FindValueObserver.prototype.completed = function () { this._y && this._o.onNext(-1); this._o.onCompleted(); }; return FindValueObserver; }(AbstractObserver)); function findValue (source, predicate, thisArg, yieldIndex) { var callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { return source.subscribe(new FindValueObserver(o, source, callback, yieldIndex)); }, source); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; var ToSetObservable = (function (__super__) { inherits(ToSetObservable, __super__); function ToSetObservable(source) { this.source = source; __super__.call(this); } ToSetObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new ToSetObserver(o)); }; return ToSetObservable; }(ObservableBase)); var ToSetObserver = (function (__super__) { inherits(ToSetObserver, __super__); function ToSetObserver(o) { this._o = o; this._s = new root.Set(); __super__.call(this); } ToSetObserver.prototype.next = function (x) { this._s.add(x); }; ToSetObserver.prototype.error = function (e) { this._o.onError(e); }; ToSetObserver.prototype.completed = function () { this._o.onNext(this._s); this._o.onCompleted(); }; return ToSetObserver; }(AbstractObserver)); /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { if (typeof root.Set === 'undefined') { throw new TypeError(); } return new ToSetObservable(this); }; var ToMapObservable = (function (__super__) { inherits(ToMapObservable, __super__); function ToMapObservable(source, k, e) { this.source = source; this._k = k; this._e = e; __super__.call(this); } ToMapObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new ToMapObserver(o, this._k, this._e)); }; return ToMapObservable; }(ObservableBase)); var ToMapObserver = (function (__super__) { inherits(ToMapObserver, __super__); function ToMapObserver(o, k, e) { this._o = o; this._k = k; this._e = e; this._m = new root.Map(); __super__.call(this); } ToMapObserver.prototype.next = function (x) { var key = tryCatch(this._k)(x); if (key === errorObj) { return this._o.onError(key.e); } var elem = x; if (this._e) { elem = tryCatch(this._e)(x); if (elem === errorObj) { return this._o.onError(elem.e); } } this._m.set(key, elem); }; ToMapObserver.prototype.error = function (e) { this._o.onError(e); }; ToMapObserver.prototype.completed = function () { this._o.onNext(this._m); this._o.onCompleted(); }; return ToMapObserver; }(AbstractObserver)); /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { if (typeof root.Map === 'undefined') { throw new TypeError(); } return new ToMapObservable(this, keySelector, elementSelector); }; var SliceObservable = (function (__super__) { inherits(SliceObservable, __super__); function SliceObservable(source, b, e) { this.source = source; this._b = b; this._e = e; __super__.call(this); } SliceObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new SliceObserver(o, this._b, this._e)); }; return SliceObservable; }(ObservableBase)); var SliceObserver = (function (__super__) { inherits(SliceObserver, __super__); function SliceObserver(o, b, e) { this._o = o; this._b = b; this._e = e; this._i = 0; __super__.call(this); } SliceObserver.prototype.next = function (x) { if (this._i >= this._b) { if (this._e === this._i) { this._o.onCompleted(); } else { this._o.onNext(x); } } this._i++; }; SliceObserver.prototype.error = function (e) { this._o.onError(e); }; SliceObserver.prototype.completed = function () { this._o.onCompleted(); }; return SliceObserver; }(AbstractObserver)); /* * The slice() method returns a shallow copy of a portion of an Observable into a new Observable object. * Unlike the array version, this does not support negative numbers for being or end. * @param {Number} [begin] Zero-based index at which to begin extraction. If omitted, this will default to zero. * @param {Number} [end] Zero-based index at which to end extraction. slice extracts up to but not including end. * If omitted, this will emit the rest of the Observable object. * @returns {Observable} A shallow copy of a portion of an Observable into a new Observable object. */ observableProto.slice = function (begin, end) { var start = begin || 0; if (start < 0) { throw new Rx.ArgumentOutOfRangeError(); } if (typeof end === 'number' && end < start) { throw new Rx.ArgumentOutOfRangeError(); } return new SliceObservable(this, start, end); }; var LastIndexOfObservable = (function (__super__) { inherits(LastIndexOfObservable, __super__); function LastIndexOfObservable(source, e, n) { this.source = source; this._e = e; this._n = n; __super__.call(this); } LastIndexOfObservable.prototype.subscribeCore = function (o) { if (this._n < 0) { o.onNext(-1); o.onCompleted(); return disposableEmpty; } return this.source.subscribe(new LastIndexOfObserver(o, this._e, this._n)); }; return LastIndexOfObservable; }(ObservableBase)); var LastIndexOfObserver = (function (__super__) { inherits(LastIndexOfObserver, __super__); function LastIndexOfObserver(o, e, n) { this._o = o; this._e = e; this._n = n; this._v = 0; this._hv = false; this._i = 0; __super__.call(this); } LastIndexOfObserver.prototype.next = function (x) { if (this._i >= this._n && x === this._e) { this._hv = true; this._v = this._i; } this._i++; }; LastIndexOfObserver.prototype.error = function (e) { this._o.onError(e); }; LastIndexOfObserver.prototype.completed = function () { if (this._hv) { this._o.onNext(this._v); } else { this._o.onNext(-1); } this._o.onCompleted(); }; return LastIndexOfObserver; }(AbstractObserver)); /** * Returns the last index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the last index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.lastIndexOf = function(searchElement, fromIndex) { var n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); return new LastIndexOfObservable(this, searchElement, n); }; Observable.wrap = function (fn) { createObservable.__generatorFunction__ = fn; return createObservable; function createObservable() { return Observable.spawn.call(this, fn.apply(this, arguments)); } }; var spawn = Observable.spawn = function () { var gen = arguments[0], self = this, args = []; for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return new AnonymousObservable(function (o) { var g = new CompositeDisposable(); if (isFunction(gen)) { gen = gen.apply(self, args); } if (!gen || !isFunction(gen.next)) { o.onNext(gen); return o.onCompleted(); } processGenerator(); function processGenerator(res) { var ret = tryCatch(gen.next).call(gen, res); if (ret === errorObj) { return o.onError(ret.e); } next(ret); } function onError(err) { var ret = tryCatch(gen.next).call(gen, err); if (ret === errorObj) { return o.onError(ret.e); } next(ret); } function next(ret) { if (ret.done) { o.onNext(ret.value); o.onCompleted(); return; } var value = toObservable.call(self, ret.value); if (Observable.isObservable(value)) { g.add(value.subscribe(processGenerator, onError)); } else { onError(new TypeError('type not supported')); } } return g; }); }; function toObservable(obj) { if (!obj) { return obj; } if (Observable.isObservable(obj)) { return obj; } if (isPromise(obj)) { return Observable.fromPromise(obj); } if (isGeneratorFunction(obj) || isGenerator(obj)) { return spawn.call(this, obj); } if (isFunction(obj)) { return thunkToObservable.call(this, obj); } if (isArrayLike(obj) || isIterable(obj)) { return arrayToObservable.call(this, obj); } if (isObject(obj)) {return objectToObservable.call(this, obj);} return obj; } function arrayToObservable (obj) { return Observable.from(obj) .flatMap(toObservable) .toArray(); } function objectToObservable (obj) { var results = new obj.constructor(), keys = Object.keys(obj), observables = []; for (var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; var observable = toObservable.call(this, obj[key]); if(observable && Observable.isObservable(observable)) { defer(observable, key); } else { results[key] = obj[key]; } } return Observable.forkJoin.apply(Observable, observables).map(function() { return results; }); function defer (observable, key) { results[key] = undefined; observables.push(observable.map(function (next) { results[key] = next; })); } } function thunkToObservable(fn) { var self = this; return new AnonymousObservable(function (o) { fn.call(self, function () { var err = arguments[0], res = arguments[1]; if (err) { return o.onError(err); } if (arguments.length > 2) { var args = []; for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); } res = args; } o.onNext(res); o.onCompleted(); }); }); } function isGenerator(obj) { return isFunction (obj.next) && isFunction (obj.throw); } function isGeneratorFunction(obj) { var ctor = obj.constructor; if (!ctor) { return false; } if (ctor.name === 'GeneratorFunction' || ctor.displayName === 'GeneratorFunction') { return true; } return isGenerator(ctor.prototype); } function isObject(val) { return Object == val.constructor; } /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(null, function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; function createCbObservable(fn, ctx, selector, args) { var o = new AsyncSubject(); args.push(createCbHandler(o, ctx, selector)); fn.apply(ctx, args); return o.asObservable(); } function createCbHandler(o, ctx, selector) { return function handler () { var len = arguments.length, results = new Array(len); for(var i = 0; i < len; i++) { results[i] = arguments[i]; } if (isFunction(selector)) { results = tryCatch(selector).apply(ctx, results); if (results === errorObj) { return o.onError(results.e); } o.onNext(results); } else { if (results.length <= 1) { o.onNext(results[0]); } else { o.onNext(results); } } o.onCompleted(); }; } /** * Converts a callback function to an observable sequence. * * @param {Function} fn Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (fn, ctx, selector) { return function () { typeof ctx === 'undefined' && (ctx = this); var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return createCbObservable(fn, ctx, selector, args); }; }; function createNodeObservable(fn, ctx, selector, args) { var o = new AsyncSubject(); args.push(createNodeHandler(o, ctx, selector)); fn.apply(ctx, args); return o.asObservable(); } function createNodeHandler(o, ctx, selector) { return function handler () { var err = arguments[0]; if (err) { return o.onError(err); } var len = arguments.length, results = []; for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } if (isFunction(selector)) { var results = tryCatch(selector).apply(ctx, results); if (results === errorObj) { return o.onError(results.e); } o.onNext(results); } else { if (results.length <= 1) { o.onNext(results[0]); } else { o.onNext(results); } } o.onCompleted(); }; } /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} fn The function to call * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (fn, ctx, selector) { return function () { typeof ctx === 'undefined' && (ctx = this); var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return createNodeObservable(fn, ctx, selector, args); }; }; function ListenDisposable(e, n, fn) { this._e = e; this._n = n; this._fn = fn; this._e.addEventListener(this._n, this._fn, false); this.isDisposed = false; } ListenDisposable.prototype.dispose = function () { if (!this.isDisposed) { this._e.removeEventListener(this._n, this._fn, false); this.isDisposed = true; } }; function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList or HTMLCollection var elemToString = Object.prototype.toString.call(el); if (elemToString === '[object NodeList]' || elemToString === '[object HTMLCollection]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(new ListenDisposable(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; function eventHandler(o, selector) { return function handler () { var results = arguments[0]; if (isFunction(selector)) { results = tryCatch(selector).apply(null, arguments); if (results === errorObj) { return o.onError(results.e); } } o.onNext(results); }; } /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { // Handles jq, Angular.js, Zepto, Marionette, Ember.js if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } } return new AnonymousObservable(function (o) { return createEventListener( element, eventName, eventHandler(o, selector)); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @param {Scheduler} [scheduler] A scheduler used to schedule the remove handler. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (o) { function innerHandler () { var result = arguments[0]; if (isFunction(selector)) { result = tryCatch(selector).apply(null, arguments); if (result === errorObj) { return o.onError(result.e); } } o.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { isFunction(removeHandler) && removeHandler(innerHandler, returnValue); }); }).publish().refCount(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise = tryCatch(functionAsync)(); if (promise === errorObj) { return observableThrow(promise.e); } return observableFromPromise(promise); }; var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this); } PausableObservable.prototype._subscribe = function (o) { var conn = this.source.publish(), subscription = conn.subscribe(o), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new NAryDisposable([subscription, connection, pausable]); }; PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (o) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { return o.onError(err); } var res = tryCatch(resultSelector).apply(null, values); if (res === errorObj) { return o.onError(res.e); } o.onNext(res); } isDone && values[1] && o.onCompleted(); } return new BinaryDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { o.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && o.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, function (e) { o.onError(e); }, function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this); } PausableBufferedObservable.prototype._subscribe = function (o) { var q = [], previousShouldFire; function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } } var subscription = combineLatestSource( this.source, this.pauser.startWith(false).distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire !== previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { drainQueue(); } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { o.onNext(results.data); } else { q.push(results.data); } } }, function (err) { drainQueue(); o.onError(err); }, function () { drainQueue(); o.onCompleted(); } ); return subscription; }; PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function ControlledObservable (source, enableQueue, scheduler) { __super__.call(this); this.subject = new ControlledSubject(enableQueue, scheduler); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype._subscribe = function (o) { return this.source.subscribe(o); }; ControlledObservable.prototype.request = function (numberOfItems) { return this.subject.request(numberOfItems == null ? -1 : numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue, scheduler) { enableQueue == null && (enableQueue = true); __super__.call(this); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = null; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.scheduler = scheduler || currentThreadScheduler; } addProperties(ControlledSubject.prototype, Observer, { _subscribe: function (o) { return this.subject.subscribe(o); }, onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); this.disposeCurrentRequest(); } else { this.queue.push(Notification.createOnCompleted()); } }, onError: function (error) { this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); this.disposeCurrentRequest(); } else { this.queue.push(Notification.createOnError(error)); } }, onNext: function (value) { if (this.requestedCount <= 0) { this.enableQueue && this.queue.push(Notification.createOnNext(value)); } else { (this.requestedCount-- === 0) && this.disposeCurrentRequest(); this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while (this.queue.length > 0 && (numberOfItems > 0 || this.queue[0].kind !== 'N')) { var first = this.queue.shift(); first.accept(this.subject); if (first.kind === 'N') { numberOfItems--; } else { this.disposeCurrentRequest(); this.queue = []; } } } return numberOfItems; }, request: function (number) { this.disposeCurrentRequest(); var self = this; this.requestedDisposable = this.scheduler.schedule(number, function(s, i) { var remaining = self._processRequest(i); var stopped = self.hasCompleted || self.hasFailed; if (!stopped && remaining > 0) { self.requestedCount = remaining; return disposableCreate(function () { self.requestedCount = 0; }); // Scheduled item is still in progress. Return a new // disposable to allow the request to be interrupted // via dispose. } }); return this.requestedDisposable; }, disposeCurrentRequest: function () { if (this.requestedDisposable) { this.requestedDisposable.dispose(); this.requestedDisposable = null; } } }); return ControlledSubject; }(Observable)); /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request * @param {Scheduler} scheduler determines how the requests will be scheduled * @returns {Observable} The observable sequence which only propagates values on request. */ observableProto.controlled = function (enableQueue, scheduler) { if (enableQueue && isScheduler(enableQueue)) { scheduler = enableQueue; enableQueue = true; } if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue, scheduler); }; var StopAndWaitObservable = (function (__super__) { inherits(StopAndWaitObservable, __super__); function StopAndWaitObservable (source) { __super__.call(this); this.source = source; } function scheduleMethod(s, self) { self.source.request(1); } StopAndWaitObservable.prototype._subscribe = function (o) { this.subscription = this.source.subscribe(new StopAndWaitObserver(o, this, this.subscription)); return new BinaryDisposable( this.subscription, defaultScheduler.schedule(this, scheduleMethod) ); }; var StopAndWaitObserver = (function (__sub__) { inherits(StopAndWaitObserver, __sub__); function StopAndWaitObserver (observer, observable, cancel) { __sub__.call(this); this.observer = observer; this.observable = observable; this.cancel = cancel; this.scheduleDisposable = null; } StopAndWaitObserver.prototype.completed = function () { this.observer.onCompleted(); this.dispose(); }; StopAndWaitObserver.prototype.error = function (error) { this.observer.onError(error); this.dispose(); }; function innerScheduleMethod(s, self) { self.observable.source.request(1); } StopAndWaitObserver.prototype.next = function (value) { this.observer.onNext(value); this.scheduleDisposable = defaultScheduler.schedule(this, innerScheduleMethod); }; StopAndWaitObservable.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } if (this.scheduleDisposable) { this.scheduleDisposable.dispose(); this.scheduleDisposable = null; } __sub__.prototype.dispose.call(this); }; return StopAndWaitObserver; }(AbstractObserver)); return StopAndWaitObservable; }(Observable)); /** * Attaches a stop and wait observable to the current observable. * @returns {Observable} A stop and wait observable. */ ControlledObservable.prototype.stopAndWait = function () { return new StopAndWaitObservable(this); }; var WindowedObservable = (function (__super__) { inherits(WindowedObservable, __super__); function WindowedObservable(source, windowSize) { __super__.call(this); this.source = source; this.windowSize = windowSize; } function scheduleMethod(s, self) { self.source.request(self.windowSize); } WindowedObservable.prototype._subscribe = function (o) { this.subscription = this.source.subscribe(new WindowedObserver(o, this, this.subscription)); return new BinaryDisposable( this.subscription, defaultScheduler.schedule(this, scheduleMethod) ); }; var WindowedObserver = (function (__sub__) { inherits(WindowedObserver, __sub__); function WindowedObserver(observer, observable, cancel) { this.observer = observer; this.observable = observable; this.cancel = cancel; this.received = 0; this.scheduleDisposable = null; __sub__.call(this); } WindowedObserver.prototype.completed = function () { this.observer.onCompleted(); this.dispose(); }; WindowedObserver.prototype.error = function (error) { this.observer.onError(error); this.dispose(); }; function innerScheduleMethod(s, self) { self.observable.source.request(self.observable.windowSize); } WindowedObserver.prototype.next = function (value) { this.observer.onNext(value); this.received = ++this.received % this.observable.windowSize; this.received === 0 && (this.scheduleDisposable = defaultScheduler.schedule(this, innerScheduleMethod)); }; WindowedObserver.prototype.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } if (this.scheduleDisposable) { this.scheduleDisposable.dispose(); this.scheduleDisposable = null; } __sub__.prototype.dispose.call(this); }; return WindowedObserver; }(AbstractObserver)); return WindowedObservable; }(Observable)); /** * Creates a sliding windowed observable based upon the window size. * @param {Number} windowSize The number of items in the window * @returns {Observable} A windowed observable based upon the window size. */ ControlledObservable.prototype.windowed = function (windowSize) { return new WindowedObservable(this, windowSize); }; /** * Pipes the existing Observable sequence into a Node.js Stream. * @param {Stream} dest The destination Node.js stream. * @returns {Stream} The destination stream. */ observableProto.pipe = function (dest) { var source = this.pausableBuffered(); function onDrain() { source.resume(); } dest.addListener('drain', onDrain); source.subscribe( function (x) { !dest.write(String(x)) && source.pause(); }, function (err) { dest.emit('error', err); }, function () { // Hack check because STDIO is not closable !dest._isStdio && dest.end(); dest.removeListener('drain', onDrain); }); source.resume(); return dest; }; var MulticastObservable = (function (__super__) { inherits(MulticastObservable, __super__); function MulticastObservable(source, fn1, fn2) { this.source = source; this._fn1 = fn1; this._fn2 = fn2; __super__.call(this); } MulticastObservable.prototype.subscribeCore = function (o) { var connectable = this.source.multicast(this._fn1()); return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect()); }; return MulticastObservable; }(ObservableBase)); /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { return isFunction(subjectOrSubjectSelector) ? new MulticastObservable(this, subjectOrSubjectSelector, selector) : new ConnectableObservable(this, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param windowSize [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, windowSize, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, windowSize, scheduler) { return this.replay(null, bufferSize, windowSize, scheduler).refCount(); }; var InnerSubscription = function (s, o) { this._s = s; this._o = o; }; InnerSubscription.prototype.dispose = function () { if (!this._s.isDisposed && this._o !== null) { var idx = this._s.observers.indexOf(this._o); this._s.observers.splice(idx, 1); this._o = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { inherits(BehaviorSubject, __super__); function BehaviorSubject(value) { __super__.call(this); this.value = value; this.observers = []; this.isDisposed = false; this.isStopped = false; this.hasError = false; } addProperties(BehaviorSubject.prototype, Observer, { _subscribe: function (o) { checkDisposed(this); if (!this.isStopped) { this.observers.push(o); o.onNext(this.value); return new InnerSubscription(this, o); } if (this.hasError) { o.onError(this.error); } else { o.onCompleted(); } return disposableEmpty; }, /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. */ getValue: function () { checkDisposed(this); if (this.hasError) { throw this.error; } return this.value; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.error = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { var maxSafeInteger = Math.pow(2, 53) - 1; function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this); } addProperties(ReplaySubject.prototype, Observer.prototype, { _subscribe: function (o) { checkDisposed(this); var so = new ScheduledObserver(this.scheduler, o), subscription = createRemovableDisposable(this, so); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); var RefCountObservable = (function (__super__) { inherits(RefCountObservable, __super__); function RefCountObservable(source) { this.source = source; this._count = 0; this._connectableSubscription = null; __super__.call(this); } RefCountObservable.prototype.subscribeCore = function (o) { var shouldConnect = ++this._count === 1, subscription = this.source.subscribe(o); shouldConnect && (this._connectableSubscription = this.source.connect()); return new RefCountDisposable(this, subscription); }; function RefCountDisposable(p, s) { this._p = p; this._s = s; this.isDisposed = false; } RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; this._s.dispose(); --this._p._count === 0 && this._p._connectableSubscription.dispose(); } }; return RefCountObservable; }(ObservableBase)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { this.source = source; this._hasSubscription = false; this._subscription = null; this._sourceObservable = source.asObservable(); this._subject = subject; __super__.call(this); } function ConnectDisposable(parent) { this._p = parent; this.isDisposed = false; } ConnectDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; this._p._hasSubscription = false; } }; ConnectableObservable.prototype.connect = function () { if (!this._hasSubscription) { this._hasSubscription = true; this._subscription = new BinaryDisposable( this._sourceObservable.subscribe(this._subject), new ConnectDisposable(this) ); } return this._subscription; }; ConnectableObservable.prototype._subscribe = function (o) { return this._subject.subscribe(o); }; ConnectableObservable.prototype.refCount = function () { return new RefCountObservable(this); }; return ConnectableObservable; }(Observable)); /** * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`) * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source. */ observableProto.singleInstance = function() { var source = this, hasObservable = false, observable; function getObservable() { if (!hasObservable) { hasObservable = true; observable = source.finally(function() { hasObservable = false; }).publish().refCount(); } return observable; } return new AnonymousObservable(function(o) { return getObservable().subscribe(o); }); }; /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (o) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Map(), rightMap = new Map(); var handleError = function (e) { o.onError(e); }; group.add(left.subscribe( function (value) { var id = leftId++, md = new SingleAssignmentDisposable(); leftMap.set(id, value); group.add(md); var duration = tryCatch(leftDurationSelector)(value); if (duration === errorObj) { return o.onError(duration.e); } md.setDisposable(duration.take(1).subscribe( noop, handleError, function () { leftMap['delete'](id) && leftMap.size === 0 && leftDone && o.onCompleted(); group.remove(md); })); rightMap.forEach(function (v) { var result = tryCatch(resultSelector)(value, v); if (result === errorObj) { return o.onError(result.e); } o.onNext(result); }); }, handleError, function () { leftDone = true; (rightDone || leftMap.size === 0) && o.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++, md = new SingleAssignmentDisposable(); rightMap.set(id, value); group.add(md); var duration = tryCatch(rightDurationSelector)(value); if (duration === errorObj) { return o.onError(duration.e); } md.setDisposable(duration.take(1).subscribe( noop, handleError, function () { rightMap['delete'](id) && rightMap.size === 0 && rightDone && o.onCompleted(); group.remove(md); })); leftMap.forEach(function (v) { var result = tryCatch(resultSelector)(v, value); if (result === errorObj) { return o.onError(result.e); } o.onNext(result); }); }, handleError, function () { rightDone = true; (leftDone || rightMap.size === 0) && o.onCompleted(); }) ); return group; }, left); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (o) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Map(), rightMap = new Map(); var leftId = 0, rightId = 0; var handleError = function (e) { return function (v) { v.onError(e); }; }; function handleError(e) { }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.set(id, s); var result = tryCatch(resultSelector)(value, addRef(s, r)); if (result === errorObj) { leftMap.forEach(handleError(result.e)); return o.onError(result.e); } o.onNext(result); rightMap.forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var duration = tryCatch(leftDurationSelector)(value); if (duration === errorObj) { leftMap.forEach(handleError(duration.e)); return o.onError(duration.e); } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.forEach(handleError(e)); o.onError(e); }, function () { leftMap['delete'](id) && s.onCompleted(); group.remove(md); })); }, function (e) { leftMap.forEach(handleError(e)); o.onError(e); }, function () { o.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.set(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var duration = tryCatch(rightDurationSelector)(value); if (duration === errorObj) { leftMap.forEach(handleError(duration.e)); return o.onError(duration.e); } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.forEach(handleError(e)); o.onError(e); }, function () { rightMap['delete'](id); group.remove(md); })); leftMap.forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.forEach(handleError(e)); o.onError(e); }) ); return r; }, left); }; function toArray(x) { return x.toArray(); } /** * Projects each element of an observable sequence into zero or more buffers. * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function () { return this.window.apply(this, arguments) .flatMap(toArray); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { return win; }); } function observableWindowWithBoundaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var win = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); d.add(windowBoundaries.subscribe(function (w) { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); return r; }, source); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), win = new Subject(); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); function createWindowClose () { var windowClose; try { windowClose = windowClosingSelector(); } catch (e) { observer.onError(e); return; } isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); var m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); createWindowClose(); })); } createWindowClose(); return r; }, source); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { return [ this.filter(predicate, thisArg), this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; var WhileEnumerable = (function(__super__) { inherits(WhileEnumerable, __super__); function WhileEnumerable(c, s) { this.c = c; this.s = s; } WhileEnumerable.prototype[$iterator$] = function () { var self = this; return { next: function () { return self.c() ? { done: false, value: self.s } : { done: true, value: void 0 }; } }; }; return WhileEnumerable; }(Enumerable)); function enumerableWhile(condition, source) { return new WhileEnumerable(condition, source); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) { return enumerableOf(sources, resultSelector, thisArg).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); isScheduler(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (o) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(null, function (_, self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { o.onNext(x); var result = null; try { result = selector(x); } catch (e) { o.onError(e); } q.push(result); activeCount++; ensureActive(); }, function (e) { o.onError(e); }, function () { d.remove(m1); activeCount--; if (activeCount === 0) { o.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }, this); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = []; if (Array.isArray(arguments[0])) { allSources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } } return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result = tryCatch(resultSelector)(lastLeft, lastRight); if (result === errorObj) { return observer.onError(e); } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result = tryCatch(resultSelector)(lastLeft, lastRight); if (result === errorObj) { return observer.onError(result.e); } observer.onNext(result); observer.onCompleted(); } } }) ); return new BinaryDisposable(leftSubscription, rightSubscription); }, first); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = observableProto.extend = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }, source); }; var ChainObservable = (function (__super__) { inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { _subscribe: function (o) { var g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(this, function (_, self) { o.onNext(self.head); g.add(self.tail.mergeAll().subscribe(o)); })); return g; }, onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable['throw'](e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); var Map = root.Map || (function () { function Map() { this.size = 0; this._values = []; this._keys = []; } Map.prototype['delete'] = function (key) { var i = this._keys.indexOf(key); if (i === -1) { return false; } this._values.splice(i, 1); this._keys.splice(i, 1); this.size--; return true; }; Map.prototype.get = function (key) { var i = this._keys.indexOf(key); return i === -1 ? undefined : this._values[i]; }; Map.prototype.set = function (key, value) { var i = this._keys.indexOf(key); if (i === -1) { this._keys.push(key); this._values.push(value); this.size++; } else { this._values[i] = value; } return this; }; Map.prototype.forEach = function (cb, thisArg) { for (var i = 0; i < this.size; i++) { cb.call(thisArg, this._values[i], this._keys[i]); } }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * @param other Observable sequence to match in addition to the current pattern. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } function ActivePlan(joinObserverArray, onNext, onCompleted) { this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { var joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { this.joinObservers.forEach(function (v) { v.queue.shift(); }); }; ActivePlan.prototype.match = function () { var i, len, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { var firstValues = [], isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); var values = []; for (i = 0, len = firstValues.length; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; var JoinObserver = (function (__super__) { inherits(JoinObserver, __super__); function JoinObserver(source, onError) { __super__.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { return this.onError(notification.error); } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; JoinObserverPrototype.error = noop; JoinObserverPrototype.completed = noop; JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; JoinObserverPrototype.removeActivePlan = function (activePlan) { this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); this.activePlans.length === 0 && this.dispose(); }; JoinObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param {Function} selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var len = arguments.length, plans; if (Array.isArray(arguments[0])) { plans = arguments[0]; } else { plans = new Array(len); for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } } return new AnonymousObservable(function (o) { var activePlans = [], externalSubscriptions = new Map(); var outObserver = observerCreate( function (x) { o.onNext(x); }, function (err) { externalSubscriptions.forEach(function (v) { v.onError(err); }); o.onError(err); }, function (x) { o.onCompleted(); } ); try { for (var i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); activePlans.length === 0 && o.onCompleted(); })); } } catch (e) { observableThrow(e).subscribe(o); } var group = new CompositeDisposable(); externalSubscriptions.forEach(function (joinObserver) { joinObserver.subscribe(); group.add(joinObserver); }); return group; }); }; var TimerObservable = (function(__super__) { inherits(TimerObservable, __super__); function TimerObservable(dt, s) { this._dt = dt; this._s = s; __super__.call(this); } TimerObservable.prototype.subscribeCore = function (o) { return this._s.scheduleFuture(o, this._dt, scheduleMethod); }; function scheduleMethod(s, o) { o.onNext(0); o.onCompleted(); } return TimerObservable; }(ObservableBase)); function _observableTimer(dueTime, scheduler) { return new TimerObservable(dueTime, scheduler); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveFuture(0, d, function (count, self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count); self(count + 1, new Date(d)); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodic(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(new Date(scheduler.now() + dueTime), period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : defaultScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = defaultScheduler); if (periodOrScheduler != null && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if ((dueTime instanceof Date || typeof dueTime === 'number') && period === undefined) { return _observableTimer(dueTime, scheduler); } if (dueTime instanceof Date && period !== undefined) { return observableTimerDateAndPeriod(dueTime.getTime(), periodOrScheduler, scheduler); } return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayRelative(source, dueTime, scheduler) { return new AnonymousObservable(function (o) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.error; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { o.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveFuture(null, dueTime, function (_, self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(o); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { o.onError(e); } else if (shouldRecurse) { self(null, recurseDueTime); } })); } } }); return new BinaryDisposable(subscription, cancelable); }, source); } function observableDelayAbsolute(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayRelative(source, dueTime - scheduler.now(), scheduler); }); } function delayWithSelector(source, subscriptionDelay, delayDurationSelector) { var subDelay, selector; if (isFunction(subscriptionDelay)) { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (o) { var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable(); function start() { subscription.setDisposable(source.subscribe( function (x) { var delay = tryCatch(selector)(x); if (delay === errorObj) { return o.onError(delay.e); } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe( function () { o.onNext(x); delays.remove(d); done(); }, function (e) { o.onError(e); }, function () { o.onNext(x); delays.remove(d); done(); } )); }, function (e) { o.onError(e); }, function () { atEnd = true; subscription.dispose(); done(); } )); } function done () { atEnd && delays.length === 0 && o.onCompleted(); } if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(start, function (e) { o.onError(e); }, start)); } return new BinaryDisposable(subscription, delays); }, this); } /** * Time shifts the observable sequence by dueTime. * The relative time intervals between the values are preserved. * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function () { var firstArg = arguments[0]; if (typeof firstArg === 'number' || firstArg instanceof Date) { var dueTime = firstArg, scheduler = arguments[1]; isScheduler(scheduler) || (scheduler = defaultScheduler); return dueTime instanceof Date ? observableDelayAbsolute(this, dueTime, scheduler) : observableDelayRelative(this, dueTime, scheduler); } else if (Observable.isObservable(firstArg) || isFunction(firstArg)) { return delayWithSelector(this, firstArg, arguments[1]); } else { throw new Error('Invalid arguments'); } }; var DebounceObservable = (function (__super__) { inherits(DebounceObservable, __super__); function DebounceObservable(source, dt, s) { isScheduler(s) || (s = defaultScheduler); this.source = source; this._dt = dt; this._s = s; __super__.call(this); } DebounceObservable.prototype.subscribeCore = function (o) { var cancelable = new SerialDisposable(); return new BinaryDisposable( this.source.subscribe(new DebounceObserver(o, this.source, this._dt, this._s, cancelable)), cancelable); }; return DebounceObservable; }(ObservableBase)); var DebounceObserver = (function (__super__) { inherits(DebounceObserver, __super__); function DebounceObserver(observer, source, dueTime, scheduler, cancelable) { this._o = observer; this._s = source; this._d = dueTime; this._scheduler = scheduler; this._c = cancelable; this._v = null; this._hv = false; this._id = 0; __super__.call(this); } DebounceObserver.prototype.next = function (x) { this._hv = true; this._v = x; var currentId = ++this._id, d = new SingleAssignmentDisposable(); this._c.setDisposable(d); d.setDisposable(this._scheduler.scheduleFuture(this, this._d, function (_, self) { self._hv && self._id === currentId && self._o.onNext(x); self._hv = false; })); }; DebounceObserver.prototype.error = function (e) { this._c.dispose(); this._o.onError(e); this._hv = false; this._id++; }; DebounceObserver.prototype.completed = function () { this._c.dispose(); this._hv && this._o.onNext(this._v); this._o.onCompleted(); this._hv = false; this._id++; }; return DebounceObserver; }(AbstractObserver)); function debounceWithSelector(source, durationSelector) { return new AnonymousObservable(function (o) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe( function (x) { var throttle = tryCatch(durationSelector)(x); if (throttle === errorObj) { return o.onError(throttle.e); } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe( function () { hasValue && id === currentid && o.onNext(value); hasValue = false; d.dispose(); }, function (e) { o.onError(e); }, function () { hasValue && id === currentid && o.onNext(value); hasValue = false; d.dispose(); } )); }, function (e) { cancelable.dispose(); o.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); hasValue && o.onNext(value); o.onCompleted(); hasValue = false; id++; } ); return new BinaryDisposable(subscription, cancelable); }, source); } observableProto.debounce = function () { if (isFunction (arguments[0])) { return debounceWithSelector(this, arguments[0]); } else if (typeof arguments[0] === 'number') { return new DebounceObservable(this, arguments[0], arguments[1]); } else { throw new Error('Invalid arguments'); } }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = defaultScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (isScheduler(timeShiftOrScheduler)) { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleFuture(null, ts, function () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = defaultScheduler); return new AnonymousObservable(function (observer) { var timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleFuture(null, timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); if (++n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); } )); return refCountDisposable; }, source); }; function toArray(x) { return x.toArray(); } /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime(timeSpan, timeShiftOrScheduler, scheduler).flatMap(toArray); }; function toArray(x) { return x.toArray(); } /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).flatMap(toArray); }; var TimeIntervalObservable = (function (__super__) { inherits(TimeIntervalObservable, __super__); function TimeIntervalObservable(source, s) { this.source = source; this._s = s; __super__.call(this); } TimeIntervalObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new TimeIntervalObserver(o, this._s)); }; return TimeIntervalObservable; }(ObservableBase)); var TimeIntervalObserver = (function (__super__) { inherits(TimeIntervalObserver, __super__); function TimeIntervalObserver(o, s) { this._o = o; this._s = s; this._l = s.now(); __super__.call(this); } TimeIntervalObserver.prototype.next = function (x) { var now = this._s.now(), span = now - this._l; this._l = now; this._o.onNext({ value: x, interval: span }); }; TimeIntervalObserver.prototype.error = function (e) { this._o.onError(e); }; TimeIntervalObserver.prototype.completed = function () { this._o.onCompleted(); }; return TimeIntervalObserver; }(AbstractObserver)); /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new TimeIntervalObservable(this, scheduler); }; var TimestampObservable = (function (__super__) { inherits(TimestampObservable, __super__); function TimestampObservable(source, s) { this.source = source; this._s = s; __super__.call(this); } TimestampObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new TimestampObserver(o, this._s)); }; return TimestampObservable; }(ObservableBase)); var TimestampObserver = (function (__super__) { inherits(TimestampObserver, __super__); function TimestampObserver(o, s) { this._o = o; this._s = s; __super__.call(this); } TimestampObserver.prototype.next = function (x) { this._o.onNext({ value: x, timestamp: this._s.now() }); }; TimestampObserver.prototype.error = function (e) { this._o.onError(e); }; TimestampObserver.prototype.completed = function () { this._o.onCompleted(); }; return TimestampObserver; }(AbstractObserver)); /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.default); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new TimestampObservable(this, scheduler); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (o) { var atEnd = false, value, hasValue = false; function sampleSubscribe() { if (hasValue) { hasValue = false; o.onNext(value); } atEnd && o.onCompleted(); } var sourceSubscription = new SingleAssignmentDisposable(); sourceSubscription.setDisposable(source.subscribe( function (newValue) { hasValue = true; value = newValue; }, function (e) { o.onError(e); }, function () { atEnd = true; sourceSubscription.dispose(); } )); return new BinaryDisposable( sourceSubscription, sampler.subscribe(sampleSubscribe, function (e) { o.onError(e); }, sampleSubscribe) ); }, source); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; var TimeoutError = Rx.TimeoutError = function(message) { this.message = message || 'Timeout has occurred'; this.name = 'TimeoutError'; Error.call(this); }; TimeoutError.prototype = Object.create(Error.prototype); function timeoutWithSelector(source, firstTimeout, timeoutDurationSelector, other) { if (isFunction(firstTimeout)) { other = timeoutDurationSelector; timeoutDurationSelector = firstTimeout; firstTimeout = observableNever(); } other || (other = observableThrow(new TimeoutError())); return new AnonymousObservable(function (o) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false; function setTimer(timeout) { var myId = id, d = new SingleAssignmentDisposable(); function timerWins() { switched = (myId === id); return switched; } timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(o)); d.dispose(); }, function (e) { timerWins() && o.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(o)); })); }; setTimer(firstTimeout); function oWins() { var res = !switched; if (res) { id++; } return res; } original.setDisposable(source.subscribe(function (x) { if (oWins()) { o.onNext(x); var timeout = tryCatch(timeoutDurationSelector)(x); if (timeout === errorObj) { return o.onError(timeout.e); } setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { oWins() && o.onError(e); }, function () { oWins() && o.onCompleted(); })); return new BinaryDisposable(subscription, timer); }, source); } function timeout(source, dueTime, other, scheduler) { if (isScheduler(other)) { scheduler = other; other = observableThrow(new TimeoutError()); } if (other instanceof Error) { other = observableThrow(other); } isScheduler(scheduler) || (scheduler = defaultScheduler); return new AnonymousObservable(function (o) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler.scheduleFuture(null, dueTime, function () { switched = id === myId; if (switched) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(o)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; o.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; o.onError(e); } }, function () { if (!switched) { id++; o.onCompleted(); } })); return new BinaryDisposable(subscription, timer); }, source); } observableProto.timeout = function () { var firstArg = arguments[0]; if (firstArg instanceof Date || typeof firstArg === 'number') { return timeout(this, firstArg, arguments[1], arguments[2]); } else if (Observable.isObservable(firstArg) || isFunction(firstArg)) { return timeoutWithSelector(this, firstArg, arguments[1], arguments[2]); } else { throw new Error('Invalid arguments'); } }; var GenerateAbsoluteObservable = (function (__super__) { inherits(GenerateAbsoluteObservable, __super__); function GenerateAbsoluteObservable(state, cndFn, itrFn, resFn, timeFn, s) { this._state = state; this._cndFn = cndFn; this._itrFn = itrFn; this._resFn = resFn; this._timeFn = timeFn; this._s = s; this._first = true; this._hasResult = false; __super__.call(this); } function scheduleRecursive(self, recurse) { self._hasResult && self._o.onNext(self._state); if (self._first) { self._first = false; } else { self._state = tryCatch(self._itrFn)(self._state); if (self._state === errorObj) { return self._o.onError(self._state.e); } } self._hasResult = tryCatch(self._cndFn)(self._state); if (self._hasResult === errorObj) { return self._o.onError(self._hasResult.e); } if (self._hasResult) { var result = tryCatch(self._resFn)(self._state); if (result === errorObj) { return self._o.onError(result.e); } var time = tryCatch(self._timeFn)(self._state); if (time === errorObj) { return self._o.onError(time.e); } recurse(self, time); } else { self._o.onCompleted(); } } GenerateAbsoluteObservable.prototype.subscribeCore = function (o) { this._o = o; return this._s.scheduleRecursiveFuture(this, new Date(this._s.now()), scheduleRecursive); }; return GenerateAbsoluteObservable; }(ObservableBase)); /** * GenerateAbsolutes an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new GenerateAbsoluteObservable(initialState, condition, iterate, resultSelector, timeSelector, scheduler); }; var GenerateRelativeObservable = (function (__super__) { inherits(GenerateRelativeObservable, __super__); function GenerateRelativeObservable(state, cndFn, itrFn, resFn, timeFn, s) { this._state = state; this._cndFn = cndFn; this._itrFn = itrFn; this._resFn = resFn; this._timeFn = timeFn; this._s = s; this._first = true; this._hasResult = false; __super__.call(this); } function scheduleRecursive(self, recurse) { self._hasResult && self._o.onNext(self._state); if (self._first) { self._first = false; } else { self._state = tryCatch(self._itrFn)(self._state); if (self._state === errorObj) { return self._o.onError(self._state.e); } } self._hasResult = tryCatch(self._cndFn)(self._state); if (self._hasResult === errorObj) { return self._o.onError(self._hasResult.e); } if (self._hasResult) { var result = tryCatch(self._resFn)(self._state); if (result === errorObj) { return self._o.onError(result.e); } var time = tryCatch(self._timeFn)(self._state); if (time === errorObj) { return self._o.onError(time.e); } recurse(self, time); } else { self._o.onCompleted(); } } GenerateRelativeObservable.prototype.subscribeCore = function (o) { this._o = o; return this._s.scheduleRecursiveFuture(this, 0, scheduleRecursive); }; return GenerateRelativeObservable; }(ObservableBase)); /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new GenerateRelativeObservable(initialState, condition, iterate, resultSelector, timeSelector, scheduler); }; var DelaySubscription = (function(__super__) { inherits(DelaySubscription, __super__); function DelaySubscription(source, dt, s) { this.source = source; this._dt = dt; this._s = s; __super__.call(this); } DelaySubscription.prototype.subscribeCore = function (o) { var d = new SerialDisposable(); d.setDisposable(this._s.scheduleFuture([this.source, o, d], this._dt, scheduleMethod)); return d; }; function scheduleMethod(s, state) { var source = state[0], o = state[1], d = state[2]; d.setDisposable(source.subscribe(o)); } return DelaySubscription; }(ObservableBase)); /** * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds * * @param {Number} dueTime Relative or absolute time shift of the subscription. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new DelaySubscription(this, dueTime, scheduler); }; var SkipLastWithTimeObservable = (function (__super__) { inherits(SkipLastWithTimeObservable, __super__); function SkipLastWithTimeObservable(source, d, s) { this.source = source; this._d = d; this._s = s; __super__.call(this); } SkipLastWithTimeObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new SkipLastWithTimeObserver(o, this)); }; return SkipLastWithTimeObservable; }(ObservableBase)); var SkipLastWithTimeObserver = (function (__super__) { inherits(SkipLastWithTimeObserver, __super__); function SkipLastWithTimeObserver(o, p) { this._o = o; this._s = p._s; this._d = p._d; this._q = []; __super__.call(this); } SkipLastWithTimeObserver.prototype.next = function (x) { var now = this._s.now(); this._q.push({ interval: now, value: x }); while (this._q.length > 0 && now - this._q[0].interval >= this._d) { this._o.onNext(this._q.shift().value); } }; SkipLastWithTimeObserver.prototype.error = function (e) { this._o.onError(e); }; SkipLastWithTimeObserver.prototype.completed = function () { var now = this._s.now(); while (this._q.length > 0 && now - this._q[0].interval >= this._d) { this._o.onNext(this._q.shift().value); } this._o.onCompleted(); }; return SkipLastWithTimeObserver; }(AbstractObserver)); /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new SkipLastWithTimeObservable(this, duration, scheduler); }; var TakeLastWithTimeObservable = (function (__super__) { inherits(TakeLastWithTimeObservable, __super__); function TakeLastWithTimeObservable(source, d, s) { this.source = source; this._d = d; this._s = s; __super__.call(this); } TakeLastWithTimeObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new TakeLastWithTimeObserver(o, this._d, this._s)); }; return TakeLastWithTimeObservable; }(ObservableBase)); var TakeLastWithTimeObserver = (function (__super__) { inherits(TakeLastWithTimeObserver, __super__); function TakeLastWithTimeObserver(o, d, s) { this._o = o; this._d = d; this._s = s; this._q = []; __super__.call(this); } TakeLastWithTimeObserver.prototype.next = function (x) { var now = this._s.now(); this._q.push({ interval: now, value: x }); while (this._q.length > 0 && now - this._q[0].interval >= this._d) { this._q.shift(); } }; TakeLastWithTimeObserver.prototype.error = function (e) { this._o.onError(e); }; TakeLastWithTimeObserver.prototype.completed = function () { var now = this._s.now(); while (this._q.length > 0) { var next = this._q.shift(); if (now - next.interval <= this._d) { this._o.onNext(next.value); } } this._o.onCompleted(); }; return TakeLastWithTimeObserver; }(AbstractObserver)); /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new TakeLastWithTimeObservable(this, duration, scheduler); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = defaultScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); now - next.interval <= duration && res.push(next.value); } o.onNext(res); o.onCompleted(); }); }, source); }; var TakeWithTimeObservable = (function (__super__) { inherits(TakeWithTimeObservable, __super__); function TakeWithTimeObservable(source, d, s) { this.source = source; this._d = d; this._s = s; __super__.call(this); } function scheduleMethod(s, o) { o.onCompleted(); } TakeWithTimeObservable.prototype.subscribeCore = function (o) { return new BinaryDisposable( this._s.scheduleFuture(o, this._d, scheduleMethod), this.source.subscribe(o) ); }; return TakeWithTimeObservable; }(ObservableBase)); /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new TakeWithTimeObservable(this, duration, scheduler); }; var SkipWithTimeObservable = (function (__super__) { inherits(SkipWithTimeObservable, __super__); function SkipWithTimeObservable(source, d, s) { this.source = source; this._d = d; this._s = s; this._open = false; __super__.call(this); } function scheduleMethod(s, self) { self._open = true; } SkipWithTimeObservable.prototype.subscribeCore = function (o) { return new BinaryDisposable( this._s.scheduleFuture(this, this._d, scheduleMethod), this.source.subscribe(new SkipWithTimeObserver(o, this)) ); }; return SkipWithTimeObservable; }(ObservableBase)); var SkipWithTimeObserver = (function (__super__) { inherits(SkipWithTimeObserver, __super__); function SkipWithTimeObserver(o, p) { this._o = o; this._p = p; __super__.call(this); } SkipWithTimeObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); }; SkipWithTimeObserver.prototype.error = function (e) { this._o.onError(e); }; SkipWithTimeObserver.prototype.completed = function () { this._o.onCompleted(); }; return SkipWithTimeObserver; }(AbstractObserver)); /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new SkipWithTimeObservable(this, duration, scheduler); }; var SkipUntilWithTimeObservable = (function (__super__) { inherits(SkipUntilWithTimeObservable, __super__); function SkipUntilWithTimeObservable(source, startTime, scheduler) { this.source = source; this._st = startTime; this._s = scheduler; __super__.call(this); } function scheduleMethod(s, state) { state._open = true; } SkipUntilWithTimeObservable.prototype.subscribeCore = function (o) { this._open = false; return new BinaryDisposable( this._s.scheduleFuture(this, this._st, scheduleMethod), this.source.subscribe(new SkipUntilWithTimeObserver(o, this)) ); }; return SkipUntilWithTimeObservable; }(ObservableBase)); var SkipUntilWithTimeObserver = (function (__super__) { inherits(SkipUntilWithTimeObserver, __super__); function SkipUntilWithTimeObserver(o, p) { this._o = o; this._p = p; __super__.call(this); } SkipUntilWithTimeObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); }; SkipUntilWithTimeObserver.prototype.error = function (e) { this._o.onError(e); }; SkipUntilWithTimeObserver.prototype.completed = function () { this._o.onCompleted(); }; return SkipUntilWithTimeObserver; }(AbstractObserver)); /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new SkipUntilWithTimeObservable(this, startTime, scheduler); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); var source = this; return new AnonymousObservable(function (o) { return new BinaryDisposable( scheduler.scheduleFuture(o, endTime, function (_, o) { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttle = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (o) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; o.onNext(x); } },function (e) { o.onError(e); }, function () { o.onCompleted(); } ); }, source); }; var TransduceObserver = (function (__super__) { inherits(TransduceObserver, __super__); function TransduceObserver(o, xform) { this._o = o; this._xform = xform; __super__.call(this); } TransduceObserver.prototype.next = function (x) { var res = tryCatch(this._xform['@@transducer/step']).call(this._xform, this._o, x); if (res === errorObj) { this._o.onError(res.e); } }; TransduceObserver.prototype.error = function (e) { this._o.onError(e); }; TransduceObserver.prototype.completed = function () { this._xform['@@transducer/result'](this._o); }; return TransduceObserver; }(AbstractObserver)); function transformForObserver(o) { return { '@@transducer/init': function() { return o; }, '@@transducer/step': function(obs, input) { return obs.onNext(input); }, '@@transducer/result': function(obs) { return obs.onCompleted(); } }; } /** * 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; return new AnonymousObservable(function(o) { var xform = transducer(transformForObserver(o)); return source.subscribe(new TransduceObserver(o, xform)); }, source); }; /** * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.switchFirst = function () { var sources = this; return new AnonymousObservable(function (o) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () { g.remove(innerSubscription); hasCurrent = false; isStopped && g.length === 1 && o.onCompleted(); })); } }, function (e) { o.onError(e); }, function () { isStopped = true; !hasCurrent && g.length === 1 && o.onCompleted(); })); return g; }, this); }; observableProto.flatMapFirst = observableProto.selectManyFirst = function(selector, resultSelector, thisArg) { return new FlatMapObservable(this, selector, resultSelector, thisArg).switchFirst(); }; Rx.Observable.prototype.flatMapWithMaxConcurrent = function(limit, selector, resultSelector, thisArg) { return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(limit); }; /** Provides a set of extension methods for virtual time scheduling. */ var VirtualTimeScheduler = Rx.VirtualTimeScheduler = (function (__super__) { inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; VirtualTimeSchedulerPrototype.now = function () { return this.toAbsoluteTime(this.clock); }; VirtualTimeSchedulerPrototype.schedule = function (state, action) { return this.scheduleAbsolute(state, this.clock, action); }; VirtualTimeSchedulerPrototype.scheduleFuture = function (state, dueTime, action) { var dt = dueTime instanceof Date ? this.toRelativeTime(dueTime - this.now()) : this.toRelativeTime(dueTime); return this.scheduleRelative(state, dt, action); }; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toAbsoluteTime = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelativeTime = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodic = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsolute(state, runAt, action); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toAbsoluteTime = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelativeTime = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); function OnNextPredicate(predicate) { this.predicate = predicate; } OnNextPredicate.prototype.equals = function (other) { if (other === this) { return true; } if (other == null) { return false; } if (other.kind !== 'N') { return false; } return this.predicate(other.value); }; function OnErrorPredicate(predicate) { this.predicate = predicate; } OnErrorPredicate.prototype.equals = function (other) { if (other === this) { return true; } if (other == null) { return false; } if (other.kind !== 'E') { return false; } return this.predicate(other.error); }; var ReactiveTest = Rx.ReactiveTest = { /** Default virtual time used for creation of observable sequences in unit tests. */ created: 100, /** Default virtual time used to subscribe to observable sequences in unit tests. */ subscribed: 200, /** Default virtual time used to dispose subscriptions in unit tests. */ disposed: 1000, /** * Factory method for an OnNext notification record at a given time with a given value or a predicate function. * * 1 - ReactiveTest.onNext(200, 42); * 2 - ReactiveTest.onNext(200, function (x) { return x.length == 2; }); * * @param ticks Recorded virtual time the OnNext notification occurs. * @param value Recorded value stored in the OnNext notification or a predicate. * @return Recorded OnNext notification. */ onNext: function (ticks, value) { return typeof value === 'function' ? new Recorded(ticks, new OnNextPredicate(value)) : new Recorded(ticks, Notification.createOnNext(value)); }, /** * Factory method for an OnError notification record at a given time with a given error. * * 1 - ReactiveTest.onNext(200, new Error('error')); * 2 - ReactiveTest.onNext(200, function (e) { return e.message === 'error'; }); * * @param ticks Recorded virtual time the OnError notification occurs. * @param exception Recorded exception stored in the OnError notification. * @return Recorded OnError notification. */ onError: function (ticks, error) { return typeof error === 'function' ? new Recorded(ticks, new OnErrorPredicate(error)) : new Recorded(ticks, Notification.createOnError(error)); }, /** * Factory method for an OnCompleted notification record at a given time. * * @param ticks Recorded virtual time the OnCompleted notification occurs. * @return Recorded OnCompleted notification. */ onCompleted: function (ticks) { return new Recorded(ticks, Notification.createOnCompleted()); }, /** * Factory method for a subscription record based on a given subscription and disposal time. * * @param start Virtual time indicating when the subscription was created. * @param end Virtual time indicating when the subscription was disposed. * @return Subscription object. */ subscribe: function (start, end) { return new Subscription(start, end); } }; /** * Creates a new object recording the production of the specified value at the given virtual time. * * @constructor * @param {Number} time Virtual time the value was produced on. * @param {Mixed} value Value that was produced. * @param {Function} comparer An optional comparer. */ var Recorded = Rx.Recorded = function (time, value, comparer) { this.time = time; this.value = value; this.comparer = comparer || defaultComparer; }; /** * Checks whether the given recorded object is equal to the current instance. * * @param {Recorded} other Recorded object to check for equality. * @returns {Boolean} true if both objects are equal; false otherwise. */ Recorded.prototype.equals = function (other) { return this.time === other.time && this.comparer(this.value, other.value); }; /** * Returns a string representation of the current Recorded value. * * @returns {String} String representation of the current Recorded value. */ Recorded.prototype.toString = function () { return this.value.toString() + '@' + this.time; }; /** * Creates a new subscription object with the given virtual subscription and unsubscription time. * * @constructor * @param {Number} subscribe Virtual time at which the subscription occurred. * @param {Number} unsubscribe Virtual time at which the unsubscription occurred. */ var Subscription = Rx.Subscription = function (start, end) { this.subscribe = start; this.unsubscribe = end || Number.MAX_VALUE; }; /** * Checks whether the given subscription is equal to the current instance. * @param other Subscription object to check for equality. * @returns {Boolean} true if both objects are equal; false otherwise. */ Subscription.prototype.equals = function (other) { return this.subscribe === other.subscribe && this.unsubscribe === other.unsubscribe; }; /** * Returns a string representation of the current Subscription value. * @returns {String} String representation of the current Subscription value. */ Subscription.prototype.toString = function () { return '(' + this.subscribe + ', ' + (this.unsubscribe === Number.MAX_VALUE ? 'Infinite' : this.unsubscribe) + ')'; }; var MockDisposable = Rx.MockDisposable = function (scheduler) { this.scheduler = scheduler; this.disposes = []; this.disposes.push(this.scheduler.clock); }; MockDisposable.prototype.dispose = function () { this.disposes.push(this.scheduler.clock); }; var MockObserver = (function (__super__) { inherits(MockObserver, __super__); function MockObserver(scheduler) { __super__.call(this); this.scheduler = scheduler; this.messages = []; } var MockObserverPrototype = MockObserver.prototype; MockObserverPrototype.onNext = function (value) { this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnNext(value))); }; MockObserverPrototype.onError = function (e) { this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnError(e))); }; MockObserverPrototype.onCompleted = function () { this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnCompleted())); }; return MockObserver; })(Observer); function MockPromise(scheduler, messages) { var self = this; this.scheduler = scheduler; this.messages = messages; this.subscriptions = []; this.observers = []; for (var i = 0, len = this.messages.length; i < len; i++) { var message = this.messages[i], notification = message.value; (function (innerNotification) { scheduler.scheduleAbsolute(null, message.time, function () { var obs = self.observers.slice(0); for (var j = 0, jLen = obs.length; j < jLen; j++) { innerNotification.accept(obs[j]); } return disposableEmpty; }); })(notification); } } MockPromise.prototype.then = function (onResolved, onRejected) { var self = this; this.subscriptions.push(new Subscription(this.scheduler.clock)); var index = this.subscriptions.length - 1; var newPromise; var observer = Rx.Observer.create( function (x) { var retValue = onResolved(x); if (retValue && typeof retValue.then === 'function') { newPromise = retValue; } else { var ticks = self.scheduler.clock; newPromise = new MockPromise(self.scheduler, [Rx.ReactiveTest.onNext(ticks, undefined), Rx.ReactiveTest.onCompleted(ticks)]); } var idx = self.observers.indexOf(observer); self.observers.splice(idx, 1); self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock); }, function (err) { onRejected(err); var idx = self.observers.indexOf(observer); self.observers.splice(idx, 1); self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock); } ); this.observers.push(observer); return newPromise || new MockPromise(this.scheduler, this.messages); }; var HotObservable = (function (__super__) { inherits(HotObservable, __super__); function HotObservable(scheduler, messages) { __super__.call(this); var message, notification, observable = this; this.scheduler = scheduler; this.messages = messages; this.subscriptions = []; this.observers = []; for (var i = 0, len = this.messages.length; i < len; i++) { message = this.messages[i]; notification = message.value; (function (innerNotification) { scheduler.scheduleAbsolute(null, message.time, function () { var obs = observable.observers.slice(0); for (var j = 0, jLen = obs.length; j < jLen; j++) { innerNotification.accept(obs[j]); } return disposableEmpty; }); })(notification); } } HotObservable.prototype._subscribe = function (o) { var observable = this; this.observers.push(o); this.subscriptions.push(new Subscription(this.scheduler.clock)); var index = this.subscriptions.length - 1; return disposableCreate(function () { var idx = observable.observers.indexOf(o); observable.observers.splice(idx, 1); observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock); }); }; return HotObservable; })(Observable); var ColdObservable = (function (__super__) { inherits(ColdObservable, __super__); function ColdObservable(scheduler, messages) { __super__.call(this); this.scheduler = scheduler; this.messages = messages; this.subscriptions = []; } ColdObservable.prototype._subscribe = function (o) { var message, notification, observable = this; this.subscriptions.push(new Subscription(this.scheduler.clock)); var index = this.subscriptions.length - 1; var d = new CompositeDisposable(); for (var i = 0, len = this.messages.length; i < len; i++) { message = this.messages[i]; notification = message.value; (function (innerNotification) { d.add(observable.scheduler.scheduleRelative(null, message.time, function () { innerNotification.accept(o); return disposableEmpty; })); })(notification); } return disposableCreate(function () { observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock); d.dispose(); }); }; return ColdObservable; })(Observable); /** Virtual time scheduler used for testing applications and libraries built using Reactive Extensions. */ Rx.TestScheduler = (function (__super__) { inherits(TestScheduler, __super__); function baseComparer(x, y) { return x > y ? 1 : (x < y ? -1 : 0); } function TestScheduler() { __super__.call(this, 0, baseComparer); } /** * Schedules an action to be executed at the specified virtual time. * * @param state State passed to the action to be executed. * @param dueTime Absolute virtual time at which to execute the action. * @param action Action to be executed. * @return Disposable object used to cancel the scheduled action (best effort). */ TestScheduler.prototype.scheduleAbsolute = function (state, dueTime, action) { dueTime <= this.clock && (dueTime = this.clock + 1); return __super__.prototype.scheduleAbsolute.call(this, state, dueTime, action); }; /** * Adds a relative virtual time to an absolute virtual time value. * * @param absolute Absolute virtual time value. * @param relative Relative virtual time value to add. * @return Resulting absolute virtual time sum value. */ TestScheduler.prototype.add = function (absolute, relative) { return absolute + relative; }; /** * Converts the absolute virtual time value to a DateTimeOffset value. * * @param absolute Absolute virtual time value to convert. * @return Corresponding DateTimeOffset value. */ TestScheduler.prototype.toAbsoluteTime = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * * @param timeSpan TimeSpan value to convert. * @return Corresponding relative virtual time value. */ TestScheduler.prototype.toRelativeTime = function (timeSpan) { return timeSpan; }; /** * Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription. * * @param create Factory method to create an observable sequence. * @param created Virtual time at which to invoke the factory to create an observable sequence. * @param subscribed Virtual time at which to subscribe to the created observable sequence. * @param disposed Virtual time at which to dispose the subscription. * @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active. */ TestScheduler.prototype.startScheduler = function (createFn, settings) { settings || (settings = {}); settings.created == null && (settings.created = ReactiveTest.created); settings.subscribed == null && (settings.subscribed = ReactiveTest.subscribed); settings.disposed == null && (settings.disposed = ReactiveTest.disposed); var observer = this.createObserver(), source, subscription; this.scheduleAbsolute(null, settings.created, function () { source = createFn(); return disposableEmpty; }); this.scheduleAbsolute(null, settings.subscribed, function () { subscription = source.subscribe(observer); return disposableEmpty; }); this.scheduleAbsolute(null, settings.disposed, function () { subscription.dispose(); return disposableEmpty; }); this.start(); return observer; }; /** * Creates a hot observable using the specified timestamped notification messages either as an array or arguments. * @param messages Notifications to surface through the created sequence at their specified absolute virtual times. * @return Hot observable sequence that can be used to assert the timing of subscriptions and notifications. */ TestScheduler.prototype.createHotObservable = function () { var len = arguments.length, args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(len); for (var i = 0; i < len; i++) { args[i] = arguments[i]; } } return new HotObservable(this, args); }; /** * Creates a cold observable using the specified timestamped notification messages either as an array or arguments. * @param messages Notifications to surface through the created sequence at their specified virtual time offsets from the sequence subscription time. * @return Cold observable sequence that can be used to assert the timing of subscriptions and notifications. */ TestScheduler.prototype.createColdObservable = function () { var len = arguments.length, args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(len); for (var i = 0; i < len; i++) { args[i] = arguments[i]; } } return new ColdObservable(this, args); }; /** * Creates a resolved promise with the given value and ticks * @param {Number} ticks The absolute time of the resolution. * @param {Any} value The value to yield at the given tick. * @returns {MockPromise} A mock Promise which fulfills with the given value. */ TestScheduler.prototype.createResolvedPromise = function (ticks, value) { return new MockPromise(this, [Rx.ReactiveTest.onNext(ticks, value), Rx.ReactiveTest.onCompleted(ticks)]); }; /** * Creates a rejected promise with the given reason and ticks * @param {Number} ticks The absolute time of the resolution. * @param {Any} reason The reason for rejection to yield at the given tick. * @returns {MockPromise} A mock Promise which rejects with the given reason. */ TestScheduler.prototype.createRejectedPromise = function (ticks, reason) { return new MockPromise(this, [Rx.ReactiveTest.onError(ticks, reason)]); }; /** * Creates an observer that records received notification messages and timestamps those. * @return Observer that can be used to assert the timing of received notifications. */ TestScheduler.prototype.createObserver = function () { return new MockObserver(this); }; return TestScheduler; })(VirtualTimeScheduler); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.__subscribe).call(self, ado); if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; this.__subscribe = subscribe; __super__.call(this); } AnonymousObservable.prototype._subscribe = function (o) { var ado = new AutoDetachObserver(o), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(state, setDisposable); } else { setDisposable(null, state); } return ado; }; 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 UnderlyingObservable = (function (__super__) { inherits(UnderlyingObservable, __super__); function UnderlyingObservable(m, u) { this._m = m; this._u = u; __super__.call(this); } UnderlyingObservable.prototype.subscribeCore = function (o) { return new BinaryDisposable(this._m.getDisposable(), this._u.subscribe(o)); }; return UnderlyingObservable; }(ObservableBase)); var GroupedObservable = (function (__super__) { inherits(GroupedObservable, __super__); function GroupedObservable(key, underlyingObservable, mergedDisposable) { __super__.call(this); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new UnderlyingObservable(mergedDisposable, underlyingObservable); } GroupedObservable.prototype._subscribe = function (o) { return this.underlyingObservable.subscribe(o); }; return GroupedObservable; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { inherits(Subject, __super__); function Subject() { __super__.call(this); this.isDisposed = false; this.isStopped = false; this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { _subscribe: function (o) { checkDisposed(this); if (!this.isStopped) { this.observers.push(o); return new InnerSubscription(this, o); } if (this.hasError) { o.onError(this.error); return disposableEmpty; } o.onCompleted(); return disposableEmpty; }, /** * 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__) { 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); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer, { _subscribe: function (o) { checkDisposed(this); if (!this.isStopped) { this.observers.push(o); return new InnerSubscription(this, o); } if (this.hasError) { o.onError(this.error); } else if (this.hasValue) { o.onNext(this.value); o.onCompleted(); } else { o.onCompleted(); } return disposableEmpty; }, /** * 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.error = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this); } addProperties(AnonymousSubject.prototype, Observer.prototype, { _subscribe: function (o) { return this.observable.subscribe(o); }, onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Used to pause and resume streams. */ Rx.Pauser = (function (__super__) { inherits(Pauser, __super__); function Pauser() { __super__.call(this); } /** * Pauses the underlying sequence. */ Pauser.prototype.pause = function () { this.onNext(false); }; /** * Resumes the underlying sequence. */ Pauser.prototype.resume = function () { this.onNext(true); }; return Pauser; }(Subject)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
src/pages/page-2.js
jefflau/jefflau.net
import React from 'react' import Link from 'gatsby-link' const SecondPage = () => ( <div> <h1>Hi from the second page</h1> <p>Welcome to page 2</p> <Link to="/">Go back to the homepage</Link> </div> ) export default SecondPage
src/svg-icons/communication/call-end.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationCallEnd = (props) => ( <SvgIcon {...props}> <path d="M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7 0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"/> </SvgIcon> ); CommunicationCallEnd = pure(CommunicationCallEnd); CommunicationCallEnd.displayName = 'CommunicationCallEnd'; CommunicationCallEnd.muiName = 'SvgIcon'; export default CommunicationCallEnd;
examples/client.js
ninja/ruto
import 'babel-polyfill'; import {Provider} from 'react-redux'; import React from 'react'; import {Router, browserHistory} from 'react-router'; import {createClientStore} from './store'; import {render} from 'react-dom'; import {routes} from './routes'; const {JSON, document} = global; const state = JSON.parse(document.getElementById('state').innerHTML); const props = {history: browserHistory, routes}; createClientStore(state, store => { render( <Provider store={store}> <Router {...props}/> </Provider>, document.getElementById('app') ); });
node_modules/react-native/Libraries/Components/Navigation/NavigatorIOS.ios.js
foxsofter/RealtimeMessaging-ReactNative
/** * 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. * * @providesModule NavigatorIOS * @flow */ 'use strict'; var EventEmitter = require('EventEmitter'); var React = require('React'); var ReactIOSViewAttributes = require('ReactIOSViewAttributes'); var RCTNavigatorManager = require('NativeModules').NavigatorManager; var StyleSheet = require('StyleSheet'); var StaticContainer = require('StaticContainer.react'); var View = require('View'); var createReactIOSNativeComponentClass = require('createReactIOSNativeComponentClass'); var invariant = require('invariant'); var logError = require('logError'); var merge = require('merge'); var TRANSITIONER_REF = 'transitionerRef'; var PropTypes = React.PropTypes; var __uid = 0; function getuid() { return __uid++; } var RCTNavigator = createReactIOSNativeComponentClass({ validAttributes: merge(ReactIOSViewAttributes.UIView, { requestedTopOfStack: true }), uiViewClassName: 'RCTNavigator', }); var RCTNavigatorItem = createReactIOSNativeComponentClass({ validAttributes: { // TODO: Remove or fix the attributes that are not fully functional. // NavigatorIOS does not use them all, because some are problematic title: true, barTintColor: true, rightButtonTitle: true, onNavRightButtonTap: true, tintColor: true, backButtonTitle: true, titleTextColor: true, style: true, }, uiViewClassName: 'RCTNavItem', }); var NavigatorTransitionerIOS = React.createClass({ requestSchedulingNavigation: function(cb) { RCTNavigatorManager.requestSchedulingJavaScriptNavigation( (this: any).getNodeHandle(), logError, cb ); }, render: function() { return ( <RCTNavigator {...this.props}/> ); }, }); type Route = { component: Function; title: string; passProps: Object; backButtonTitle: string; rightButtonTitle: string; onRightButtonPress: Function; wrapperStyle: any; }; type State = { idStack: Array<number>; routeStack: Array<Route>; requestedTopOfStack: number; observedTopOfStack: number; progress: number; fromIndex: number; toIndex: number; makingNavigatorRequest: boolean; updatingAllIndicesAtOrBeyond: number; } type Event = Object; /** * Think of `<NavigatorIOS>` as simply a component that renders an * `RCTNavigator`, and moves the `RCTNavigator`'s `requestedTopOfStack` pointer * forward and backward. The `RCTNavigator` interprets changes in * `requestedTopOfStack` to be pushes and pops of children that are rendered. * `<NavigatorIOS>` always ensures that whenever the `requestedTopOfStack` * pointer is moved, that we've also rendered enough children so that the * `RCTNavigator` can carry out the push/pop with those children. * `<NavigatorIOS>` also removes children that will no longer be needed * (after the pop of a child has been fully completed/animated out). */ /** * NavigatorIOS wraps UIKit navigation and allows you to add back-swipe * functionality across your app. * * #### Routes * A route is an object used to describe each page in the navigator. The first * route is provided to NavigatorIOS as `initialRoute`: * * ``` * render: function() { * return ( * <NavigatorIOS * initialRoute={{ * component: MyView, * title: 'My View Title', * passProps: { myProp: 'foo' }, * }} * /> * ); * }, * ``` * * Now MyView will be rendered by the navigator. It will recieve the route * object in the `route` prop, a navigator, and all of the props specified in * `passProps`. * * See the initialRoute propType for a complete definition of a route. * * #### Navigator * * A `navigator` is an object of navigation functions that a view can call. It * is passed as a prop to any component rendered by NavigatorIOS. * * ``` * var MyView = React.createClass({ * _handleBackButtonPress: function() { * this.props.navigator.pop(); * }, * _handleNextButtonPress: function() { * this.props.navigator.push(nextRoute); * }, * ... * }); * ``` * * A navigation object contains the following functions: * * - `push(route)` - Navigate forward to a new route * - `pop()` - Go back one page * - `popN(n)` - Go back N pages at once. When N=1, behavior matches `pop()` * - `replace(route)` - Replace the route for the current page and immediately * load the view for the new route * - `replacePrevious(route)` - Replace the route/view for the previous page * - `replacePreviousAndPop(route)` - Replaces the previous route/view and * transitions back to it * - `resetTo(route)` - Replaces the top item and popToTop * - `popToRoute(route)` - Go back to the item for a particular route object * - `popToTop()` - Go back to the top item * * Navigator functions are also available on the NavigatorIOS component: * * ``` * var MyView = React.createClass({ * _handleNavigationRequest: function() { * this.refs.nav.push(otherRoute); * }, * render: () => ( * <NavigatorIOS * ref="nav" * initialRoute={...} * /> * ), * }); * ``` * */ var NavigatorIOS = React.createClass({ propTypes: { /** * NavigatorIOS uses "route" objects to identify child views, their props, * and navigation bar configuration. "push" and all the other navigation * operations expect routes to be like this: */ initialRoute: PropTypes.shape({ /** * The React Class to render for this route */ component: PropTypes.func.isRequired, /** * The title displayed in the nav bar and back button for this route */ title: PropTypes.string.isRequired, /** * Specify additional props passed to the component. NavigatorIOS will * automatically provide "route" and "navigator" components */ passProps: PropTypes.object, /** * If set, the left header button will appear with this name. Note that * this doesn't apply for the header of the current view, but the ones * of the views that are pushed afterward. */ backButtonTitle: PropTypes.string, /** * If set, the right header button will appear with this name */ rightButtonTitle: PropTypes.string, /** * Called when the right header button is pressed */ onRightButtonPress: PropTypes.func, /** * Styles for the navigation item containing the component */ wrapperStyle: View.propTypes.style, }).isRequired, /** * The default wrapper style for components in the navigator. * A common use case is to set the backgroundColor for every page */ itemWrapperStyle: View.propTypes.style, /** * The color used for buttons in the navigation bar */ tintColor: PropTypes.string, }, navigator: (undefined: ?Object), componentWillMount: function() { // Precompute a pack of callbacks that's frequently generated and passed to // instances. this.navigator = { push: this.push, pop: this.pop, popN: this.popN, replace: this.replace, replacePrevious: this.replacePrevious, replacePreviousAndPop: this.replacePreviousAndPop, resetTo: this.resetTo, popToRoute: this.popToRoute, popToTop: this.popToTop, }; }, getInitialState: function(): State { return { idStack: [getuid()], routeStack: [this.props.initialRoute], // The navigation index that we wish to push/pop to. requestedTopOfStack: 0, // The last index that native has sent confirmation of completed push/pop // for. At this point, we can discard any views that are beyond the // `requestedTopOfStack`. A value of `null` means we have not received // any confirmation, ever. We may receive an `observedTopOfStack` without // ever requesting it - native can instigate pops of its own with the // backswipe gesture. observedTopOfStack: 0, progress: 1, fromIndex: 0, toIndex: 0, // Whether or not we are making a navigator request to push/pop. (Used // for performance optimization). makingNavigatorRequest: false, // Whether or not we are updating children of navigator and if so (not // `null`) which index marks the beginning of all updates. Used for // performance optimization. updatingAllIndicesAtOrBeyond: 0, }; }, _toFocusOnNavigationComplete: (undefined: any), _handleFocusRequest: function(item: any) { if (this.state.makingNavigatorRequest) { this._toFocusOnNavigationComplete = item; } else { this._getFocusEmitter().emit('focus', item); } }, _focusEmitter: (undefined: ?EventEmitter), _getFocusEmitter: function(): EventEmitter { // Flow not yet tracking assignments to instance fields. var focusEmitter = this._focusEmitter; if (!focusEmitter) { focusEmitter = new EventEmitter(); this._focusEmitter = focusEmitter; } return focusEmitter; }, getChildContext: function(): { onFocusRequested: Function; focusEmitter: EventEmitter; } { return { onFocusRequested: this._handleFocusRequest, focusEmitter: this._getFocusEmitter(), }; }, childContextTypes: { onFocusRequested: React.PropTypes.func, focusEmitter: React.PropTypes.instanceOf(EventEmitter), }, _tryLockNavigator: function(cb: () => void) { this.refs[TRANSITIONER_REF].requestSchedulingNavigation( (acquiredLock) => acquiredLock && cb() ); }, _handleNavigatorStackChanged: function(e: Event) { var newObservedTopOfStack = e.nativeEvent.stackLength - 1; invariant( newObservedTopOfStack <= this.state.requestedTopOfStack, 'No navigator item should be pushed without JS knowing about it %s %s', newObservedTopOfStack, this.state.requestedTopOfStack ); var wasWaitingForConfirmation = this.state.requestedTopOfStack !== this.state.observedTopOfStack; if (wasWaitingForConfirmation) { invariant( newObservedTopOfStack === this.state.requestedTopOfStack, 'If waiting for observedTopOfStack to reach requestedTopOfStack, ' + 'the only valid observedTopOfStack should be requestedTopOfStack.' ); } // Mark the most recent observation regardless of if we can lock the // navigator. `observedTopOfStack` merely represents what we've observed // and this first `setState` is only executed to update debugging // overlays/navigation bar. // Also reset progress, toIndex, and fromIndex as they might not end // in the correct states for a two possible reasons: // Progress isn't always 0 or 1 at the end, the system rounds // If the Navigator is offscreen these values won't be updated // TOOD: Revisit this decision when no longer relying on native navigator. var nextState = { observedTopOfStack: newObservedTopOfStack, makingNavigatorRequest: false, updatingAllIndicesAtOrBeyond: null, progress: 1, toIndex: newObservedTopOfStack, fromIndex: newObservedTopOfStack, }; this.setState(nextState, this._eliminateUnneededChildren); }, _eliminateUnneededChildren: function() { // Updating the indices that we're deleting and that's all. (Truth: Nothing // even uses the indices in this case, but let's make this describe the // truth anyways). var updatingAllIndicesAtOrBeyond = this.state.routeStack.length > this.state.observedTopOfStack + 1 ? this.state.observedTopOfStack + 1 : null; this.setState({ idStack: this.state.idStack.slice(0, this.state.observedTopOfStack + 1), routeStack: this.state.routeStack.slice(0, this.state.observedTopOfStack + 1), // Now we rerequest the top of stack that we observed. requestedTopOfStack: this.state.observedTopOfStack, makingNavigatorRequest: true, updatingAllIndicesAtOrBeyond: updatingAllIndicesAtOrBeyond, }); }, push: function(route: Route) { invariant(!!route, 'Must supply route to push'); // Make sure all previous requests are caught up first. Otherwise reject. if (this.state.requestedTopOfStack === this.state.observedTopOfStack) { this._tryLockNavigator(() => { var nextStack = this.state.routeStack.concat([route]); var nextIDStack = this.state.idStack.concat([getuid()]); this.setState({ // We have to make sure that we've also supplied enough views to // satisfy our request to adjust the `requestedTopOfStack`. idStack: nextIDStack, routeStack: nextStack, requestedTopOfStack: nextStack.length - 1, makingNavigatorRequest: true, updatingAllIndicesAtOrBeyond: nextStack.length - 1, }); }); } }, popN: function(n: number) { if (n === 0) { return; } // Make sure all previous requests are caught up first. Otherwise reject. if (this.state.requestedTopOfStack === this.state.observedTopOfStack) { if (this.state.requestedTopOfStack > 0) { this._tryLockNavigator(() => { invariant( this.state.requestedTopOfStack - n >= 0, 'Cannot pop below 0' ); this.setState({ requestedTopOfStack: this.state.requestedTopOfStack - n, makingNavigatorRequest: true, // Not actually updating the indices yet until we get the native // `onNavigationComplete`. updatingAllIndicesAtOrBeyond: null, }); }); } } }, pop: function() { this.popN(1); }, /** * Replace a route in the navigation stack. * * `index` specifies the route in the stack that should be replaced. * If it's negative, it counts from the back. */ replaceAtIndex: function(route: Route, index: number) { invariant(!!route, 'Must supply route to replace'); if (index < 0) { index += this.state.routeStack.length; } if (this.state.routeStack.length <= index) { return; } // I don't believe we need to lock for a replace since there's no // navigation actually happening var nextIDStack = this.state.idStack.slice(); var nextRouteStack = this.state.routeStack.slice(); nextIDStack[index] = getuid(); nextRouteStack[index] = route; this.setState({ idStack: nextIDStack, routeStack: nextRouteStack, makingNavigatorRequest: false, updatingAllIndicesAtOrBeyond: index, }); }, /** * Replaces the top of the navigation stack. */ replace: function(route: Route) { this.replaceAtIndex(route, -1); }, /** * Replace the current route's parent. */ replacePrevious: function(route: Route) { this.replaceAtIndex(route, -2); }, popToTop: function() { this.popToRoute(this.state.routeStack[0]); }, popToRoute: function(route: Route) { var indexOfRoute = this.state.routeStack.indexOf(route); invariant( indexOfRoute !== -1, 'Calling pop to route for a route that doesn\'t exist!' ); var numToPop = this.state.routeStack.length - indexOfRoute - 1; this.popN(numToPop); }, replacePreviousAndPop: function(route: Route) { // Make sure all previous requests are caught up first. Otherwise reject. if (this.state.requestedTopOfStack !== this.state.observedTopOfStack) { return; } if (this.state.routeStack.length < 2) { return; } this._tryLockNavigator(() => { this.replacePrevious(route); this.setState({ requestedTopOfStack: this.state.requestedTopOfStack - 1, makingNavigatorRequest: true, }); }); }, resetTo: function(route: Route) { invariant(!!route, 'Must supply route to push'); // Make sure all previous requests are caught up first. Otherwise reject. if (this.state.requestedTopOfStack !== this.state.observedTopOfStack) { return; } this.replaceAtIndex(route, 0); this.popToRoute(route); }, handleNavigationComplete: function(e: Event) { if (this._toFocusOnNavigationComplete) { this._getFocusEmitter().emit('focus', this._toFocusOnNavigationComplete); this._toFocusOnNavigationComplete = null; } this._handleNavigatorStackChanged(e); }, _routeToStackItem: function(route: Route, i: number) { var Component = route.component; var shouldUpdateChild = this.state.updatingAllIndicesAtOrBeyond !== null && this.state.updatingAllIndicesAtOrBeyond >= i; return ( <StaticContainer key={'nav' + i} shouldUpdate={shouldUpdateChild}> <RCTNavigatorItem title={route.title} style={[ styles.stackItem, this.props.itemWrapperStyle, route.wrapperStyle ]} backButtonTitle={route.backButtonTitle} rightButtonTitle={route.rightButtonTitle} onNavRightButtonTap={route.onRightButtonPress} tintColor={this.props.tintColor}> <Component navigator={this.navigator} route={route} {...route.passProps} /> </RCTNavigatorItem> </StaticContainer> ); }, renderNavigationStackItems: function() { var shouldRecurseToNavigator = this.state.makingNavigatorRequest || this.state.updatingAllIndicesAtOrBeyond !== null; // If not recursing update to navigator at all, may as well avoid // computation of navigator children. var items = shouldRecurseToNavigator ? this.state.routeStack.map(this._routeToStackItem) : null; return ( <StaticContainer shouldUpdate={shouldRecurseToNavigator}> <NavigatorTransitionerIOS ref={TRANSITIONER_REF} style={styles.transitioner} vertical={this.props.vertical} requestedTopOfStack={this.state.requestedTopOfStack} onNavigationComplete={this.handleNavigationComplete}> {items} </NavigatorTransitionerIOS> </StaticContainer> ); }, render: function() { return ( <View style={this.props.style}> {this.renderNavigationStackItems()} </View> ); } }); var styles = StyleSheet.create({ stackItem: { backgroundColor: 'white', overflow: 'hidden', position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, }, transitioner: { flex: 1, }, }); module.exports = NavigatorIOS;
django/webcode/webcode/frontend/node_modules/react-bootstrap/es/Label.js
OpenKGB/webcode
import _Object$values from 'babel-runtime/core-js/object/values'; import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, bsStyles, getClassSet, splitBsProps } from './utils/bootstrapUtils'; import { State, Style } from './utils/StyleConfig'; var Label = function (_React$Component) { _inherits(Label, _React$Component); function Label() { _classCallCheck(this, Label); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Label.prototype.hasContent = function hasContent(children) { var result = false; React.Children.forEach(children, function (child) { if (result) { return; } if (child || child === 0) { result = true; } }); return result; }; Label.prototype.render = function render() { var _props = this.props, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['className', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), { // Hack for collapsing on IE8. hidden: !this.hasContent(children) }); return React.createElement( 'span', _extends({}, elementProps, { className: classNames(className, classes) }), children ); }; return Label; }(React.Component); export default bsClass('label', bsStyles([].concat(_Object$values(State), [Style.DEFAULT, Style.PRIMARY]), Style.DEFAULT, Label));
react/react-16.2.0/packages/react-dom/src/__tests__/ReactDOMServerIntegrationElements-test.js
isubham/isubham.github.io
/** * 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. * * @emails react-core */ 'use strict'; const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); const TEXT_NODE_TYPE = 3; let React; let ReactDOM; let ReactDOMServer; function initModules() { jest.resetModuleRegistry(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); // Make them available to the helpers. return { ReactDOM, ReactDOMServer, }; } const { resetModules, itRenders, itThrowsWhenRendering, serverRender, streamRender, clientRenderOnServerString, } = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerIntegration', () => { beforeEach(() => { resetModules(); }); describe('elements and children', function() { function expectNode(node, type, value) { expect(node).not.toBe(null); expect(node.nodeType).toBe(type); expect(node.nodeValue).toMatch(value); } function expectTextNode(node, text) { expectNode(node, TEXT_NODE_TYPE, text); } describe('text children', function() { itRenders('a div with text', async render => { const e = await render(<div>Text</div>); expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text'); }); itRenders('a div with text with flanking whitespace', async render => { // prettier-ignore const e = await render(<div> Text </div>); expect(e.childNodes.length).toBe(1); expectNode(e.childNodes[0], TEXT_NODE_TYPE, ' Text '); }); itRenders('a div with an empty text child', async render => { const e = await render(<div>{''}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('a div with multiple empty text children', async render => { const e = await render( <div> {''} {''} {''} </div>, ); if (render === serverRender || render === streamRender) { // For plain server markup result we should have no text nodes if // they're all empty. expect(e.childNodes.length).toBe(0); expect(e.textContent).toBe(''); } else { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], ''); expectTextNode(e.childNodes[1], ''); expectTextNode(e.childNodes[2], ''); } }); itRenders('a div with multiple whitespace children', async render => { // prettier-ignore const e = await render(<div>{' '}{' '}{' '}</div>); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // For plain server markup result we have comments between. // If we're able to hydrate, they remain. expect(e.childNodes.length).toBe(5); expectTextNode(e.childNodes[0], ' '); expectTextNode(e.childNodes[2], ' '); expectTextNode(e.childNodes[4], ' '); } else { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], ' '); expectTextNode(e.childNodes[1], ' '); expectTextNode(e.childNodes[2], ' '); } }); itRenders('a div with text sibling to a node', async render => { const e = await render( <div> Text<span>More Text</span> </div>, ); let spanNode; expect(e.childNodes.length).toBe(2); spanNode = e.childNodes[1]; expectTextNode(e.childNodes[0], 'Text'); expect(spanNode.tagName).toBe('SPAN'); expect(spanNode.childNodes.length).toBe(1); expectNode(spanNode.firstChild, TEXT_NODE_TYPE, 'More Text'); }); itRenders('a non-standard element with text', async render => { const e = await render(<nonstandard>Text</nonstandard>); expect(e.tagName).toBe('NONSTANDARD'); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text'); }); itRenders('a custom element with text', async render => { const e = await render(<custom-element>Text</custom-element>); expect(e.tagName).toBe('CUSTOM-ELEMENT'); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text'); }); itRenders('a leading blank child with a text sibling', async render => { const e = await render(<div>{''}foo</div>); if (render === serverRender || render === streamRender) { expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], ''); expectTextNode(e.childNodes[1], 'foo'); } }); itRenders('a trailing blank child with a text sibling', async render => { const e = await render(<div>foo{''}</div>); // with Fiber, there are just two text nodes. if (render === serverRender || render === streamRender) { expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[1], ''); } }); itRenders('an element with two text children', async render => { const e = await render( <div> {'foo'} {'bar'} </div>, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server render output there's a comment between them. expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[2], 'bar'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[1], 'bar'); } }); itRenders( 'a component returning text node between two text nodes', async render => { const B = () => 'b'; const e = await render( <div> {'a'} <B /> {'c'} </div>, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server render output there's a comment between them. expect(e.childNodes.length).toBe(5); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[2], 'b'); expectTextNode(e.childNodes[4], 'c'); } else { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[1], 'b'); expectTextNode(e.childNodes[2], 'c'); } }, ); itRenders('a tree with sibling host and text nodes', async render => { class X extends React.Component { render() { return [null, [<Y key="1" />], false]; } } function Y() { return [<Z key="1" />, ['c']]; } function Z() { return null; } const e = await render( <div> {[['a'], 'b']} <div> <X key="1" /> d </div> e </div>, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server render output there's comments between text nodes. expect(e.childNodes.length).toBe(5); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[2], 'b'); expect(e.childNodes[3].childNodes.length).toBe(3); expectTextNode(e.childNodes[3].childNodes[0], 'c'); expectTextNode(e.childNodes[3].childNodes[2], 'd'); expectTextNode(e.childNodes[4], 'e'); } else { expect(e.childNodes.length).toBe(4); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[1], 'b'); expect(e.childNodes[2].childNodes.length).toBe(2); expectTextNode(e.childNodes[2].childNodes[0], 'c'); expectTextNode(e.childNodes[2].childNodes[1], 'd'); expectTextNode(e.childNodes[3], 'e'); } }); }); describe('number children', function() { itRenders('a number as single child', async render => { const e = await render(<div>{3}</div>); expect(e.textContent).toBe('3'); }); // zero is falsey, so it could look like no children if the code isn't careful. itRenders('zero as single child', async render => { const e = await render(<div>{0}</div>); expect(e.textContent).toBe('0'); }); itRenders('an element with number and text children', async render => { const e = await render( <div> {'foo'} {40} </div>, ); // with Fiber, there are just two text nodes. if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server markup there's a comment between. expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[2], '40'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[1], '40'); } }); }); describe('null, false, and undefined children', function() { itRenders('null single child as blank', async render => { const e = await render(<div>{null}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('false single child as blank', async render => { const e = await render(<div>{false}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('undefined single child as blank', async render => { const e = await render(<div>{undefined}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('a null component children as empty', async render => { const NullComponent = () => null; const e = await render( <div> <NullComponent /> </div>, ); expect(e.childNodes.length).toBe(0); }); itRenders('null children as blank', async render => { const e = await render(<div>{null}foo</div>); expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); }); itRenders('false children as blank', async render => { const e = await render(<div>{false}foo</div>); expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); }); itRenders('null and false children together as blank', async render => { const e = await render( <div> {false} {null}foo{null} {false} </div>, ); expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); }); itRenders('only null and false children as blank', async render => { const e = await render( <div> {false} {null} {null} {false} </div>, ); expect(e.childNodes.length).toBe(0); }); }); describe('elements with implicit namespaces', function() { itRenders('an svg element', async render => { const e = await render(<svg />); expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('svg'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); }); itRenders('svg child element with an attribute', async render => { let e = await render(<svg viewBox="0 0 0 0" />); expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('svg'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); expect(e.getAttribute('viewBox')).toBe('0 0 0 0'); }); itRenders( 'svg child element with a namespace attribute', async render => { let e = await render( <svg> <image xlinkHref="http://i.imgur.com/w7GCRPb.png" /> </svg>, ); e = e.firstChild; expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('image'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); expect(e.getAttributeNS('http://www.w3.org/1999/xlink', 'href')).toBe( 'http://i.imgur.com/w7GCRPb.png', ); }, ); itRenders('svg child element with a badly cased alias', async render => { let e = await render( <svg> <image xlinkhref="http://i.imgur.com/w7GCRPb.png" /> </svg>, 1, ); e = e.firstChild; expect(e.hasAttributeNS('http://www.w3.org/1999/xlink', 'href')).toBe( false, ); expect(e.getAttribute('xlinkhref')).toBe( 'http://i.imgur.com/w7GCRPb.png', ); }); itRenders('svg element with a tabIndex attribute', async render => { let e = await render(<svg tabIndex="1" />); expect(e.tabIndex).toBe(1); }); itRenders( 'svg element with a badly cased tabIndex attribute', async render => { let e = await render(<svg tabindex="1" />, 1); expect(e.tabIndex).toBe(1); }, ); itRenders('svg element with a mixed case name', async render => { let e = await render( <svg> <filter> <feMorphology /> </filter> </svg>, ); e = e.firstChild.firstChild; expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('feMorphology'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); }); itRenders('a math element', async render => { const e = await render(<math />); expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('math'); expect(e.namespaceURI).toBe('http://www.w3.org/1998/Math/MathML'); }); }); // specially wrapped components // (see the big switch near the beginning ofReactDOMComponent.mountComponent) itRenders('an img', async render => { const e = await render(<img />); expect(e.childNodes.length).toBe(0); expect(e.nextSibling).toBe(null); expect(e.tagName).toBe('IMG'); }); itRenders('a button', async render => { const e = await render(<button />); expect(e.childNodes.length).toBe(0); expect(e.nextSibling).toBe(null); expect(e.tagName).toBe('BUTTON'); }); itRenders('a div with dangerouslySetInnerHTML', async render => { const e = await render( <div dangerouslySetInnerHTML={{__html: "<span id='child'/>"}} />, ); expect(e.childNodes.length).toBe(1); expect(e.firstChild.tagName).toBe('SPAN'); expect(e.firstChild.getAttribute('id')).toBe('child'); expect(e.firstChild.childNodes.length).toBe(0); }); describe('newline-eating elements', function() { itRenders( 'a newline-eating tag with content not starting with \\n', async render => { const e = await render(<pre>Hello</pre>); expect(e.textContent).toBe('Hello'); }, ); itRenders( 'a newline-eating tag with content starting with \\n', async render => { const e = await render(<pre>{'\nHello'}</pre>); expect(e.textContent).toBe('\nHello'); }, ); itRenders('a normal tag with content starting with \\n', async render => { const e = await render(<div>{'\nHello'}</div>); expect(e.textContent).toBe('\nHello'); }); }); describe('different component implementations', function() { function checkFooDiv(e) { expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'foo'); } itRenders('stateless components', async render => { const StatelessComponent = () => <div>foo</div>; checkFooDiv(await render(<StatelessComponent />)); }); itRenders('ES6 class components', async render => { class ClassComponent extends React.Component { render() { return <div>foo</div>; } } checkFooDiv(await render(<ClassComponent />)); }); itRenders('factory components', async render => { const FactoryComponent = () => { return { render: function() { return <div>foo</div>; }, }; }; checkFooDiv(await render(<FactoryComponent />)); }); }); describe('component hierarchies', async function() { itRenders('single child hierarchies of components', async render => { const Component = props => <div>{props.children}</div>; let e = await render( <Component> <Component> <Component> <Component /> </Component> </Component> </Component>, ); for (var i = 0; i < 3; i++) { expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(1); e = e.firstChild; } expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(0); }); itRenders('multi-child hierarchies of components', async render => { const Component = props => <div>{props.children}</div>; const e = await render( <Component> <Component> <Component /> <Component /> </Component> <Component> <Component /> <Component /> </Component> </Component>, ); expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(2); for (var i = 0; i < 2; i++) { var child = e.childNodes[i]; expect(child.tagName).toBe('DIV'); expect(child.childNodes.length).toBe(2); for (var j = 0; j < 2; j++) { var grandchild = child.childNodes[j]; expect(grandchild.tagName).toBe('DIV'); expect(grandchild.childNodes.length).toBe(0); } } }); itRenders('a div with a child', async render => { const e = await render( <div id="parent"> <div id="child" /> </div>, ); expect(e.id).toBe('parent'); expect(e.childNodes.length).toBe(1); expect(e.childNodes[0].id).toBe('child'); expect(e.childNodes[0].childNodes.length).toBe(0); }); itRenders('a div with multiple children', async render => { const e = await render( <div id="parent"> <div id="child1" /> <div id="child2" /> </div>, ); expect(e.id).toBe('parent'); expect(e.childNodes.length).toBe(2); expect(e.childNodes[0].id).toBe('child1'); expect(e.childNodes[0].childNodes.length).toBe(0); expect(e.childNodes[1].id).toBe('child2'); expect(e.childNodes[1].childNodes.length).toBe(0); }); itRenders( 'a div with multiple children separated by whitespace', async render => { const e = await render( <div id="parent"> <div id="child1" /> <div id="child2" /> </div>, ); expect(e.id).toBe('parent'); let child1, child2, textNode; expect(e.childNodes.length).toBe(3); child1 = e.childNodes[0]; textNode = e.childNodes[1]; child2 = e.childNodes[2]; expect(child1.id).toBe('child1'); expect(child1.childNodes.length).toBe(0); expectTextNode(textNode, ' '); expect(child2.id).toBe('child2'); expect(child2.childNodes.length).toBe(0); }, ); itRenders( 'a div with a single child surrounded by whitespace', async render => { // prettier-ignore const e = await render(<div id="parent"> <div id="child" /> </div>); // eslint-disable-line no-multi-spaces let textNode1, child, textNode2; expect(e.childNodes.length).toBe(3); textNode1 = e.childNodes[0]; child = e.childNodes[1]; textNode2 = e.childNodes[2]; expect(e.id).toBe('parent'); expectTextNode(textNode1, ' '); expect(child.id).toBe('child'); expect(child.childNodes.length).toBe(0); expectTextNode(textNode2, ' '); }, ); itRenders('a composite with multiple children', async render => { const Component = props => props.children; const e = await render( <Component>{['a', 'b', [undefined], [[false, 'c']]]}</Component>, ); let parent = e.parentNode; if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // For plain server markup result we have comments between. // If we're able to hydrate, they remain. expect(parent.childNodes.length).toBe(5); expectTextNode(parent.childNodes[0], 'a'); expectTextNode(parent.childNodes[2], 'b'); expectTextNode(parent.childNodes[4], 'c'); } else { expect(parent.childNodes.length).toBe(3); expectTextNode(parent.childNodes[0], 'a'); expectTextNode(parent.childNodes[1], 'b'); expectTextNode(parent.childNodes[2], 'c'); } }); }); describe('escaping >, <, and &', function() { itRenders('>,<, and & as single child', async render => { const e = await render(<div>{'<span>Text&quot;</span>'}</div>); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, '<span>Text&quot;</span>'); }); itRenders('>,<, and & as multiple children', async render => { const e = await render( <div> {'<span>Text1&quot;</span>'} {'<span>Text2&quot;</span>'} </div>, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], '<span>Text1&quot;</span>'); expectTextNode(e.childNodes[2], '<span>Text2&quot;</span>'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], '<span>Text1&quot;</span>'); expectTextNode(e.childNodes[1], '<span>Text2&quot;</span>'); } }); }); describe('carriage return and null character', () => { // HTML parsing normalizes CR and CRLF to LF. // It also ignores null character. // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream // If we have a mismatch, it might be caused by that (and should not be reported). // We won't be patching up in this case as that matches our past behavior. itRenders( 'an element with one text child with special characters', async render => { const e = await render(<div>{'foo\rbar\r\nbaz\nqux\u0000'}</div>); if (render === serverRender || render === streamRender) { expect(e.childNodes.length).toBe(1); // Everything becomes LF when parsed from server HTML. // Null character is ignored. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\nbar\nbaz\nqux'); } else { expect(e.childNodes.length).toBe(1); // Client rendering (or hydration) uses JS value with CR. // Null character stays. expectNode( e.childNodes[0], TEXT_NODE_TYPE, 'foo\rbar\r\nbaz\nqux\u0000', ); } }, ); itRenders( 'an element with two text children with special characters', async render => { const e = await render( <div> {'foo\rbar'} {'\r\nbaz\nqux\u0000'} </div>, ); if (render === serverRender || render === streamRender) { // We have three nodes because there is a comment between them. expect(e.childNodes.length).toBe(3); // Everything becomes LF when parsed from server HTML. // Null character is ignored. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\nbar'); expectNode(e.childNodes[2], TEXT_NODE_TYPE, '\nbaz\nqux'); } else if (render === clientRenderOnServerString) { // We have three nodes because there is a comment between them. expect(e.childNodes.length).toBe(3); // Hydration uses JS value with CR and null character. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\rbar'); expectNode(e.childNodes[2], TEXT_NODE_TYPE, '\r\nbaz\nqux\u0000'); } else { expect(e.childNodes.length).toBe(2); // Client rendering uses JS value with CR and null character. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\rbar'); expectNode(e.childNodes[1], TEXT_NODE_TYPE, '\r\nbaz\nqux\u0000'); } }, ); itRenders( 'an element with an attribute value with special characters', async render => { const e = await render(<a title={'foo\rbar\r\nbaz\nqux\u0000'} />); if ( render === serverRender || render === streamRender || render === clientRenderOnServerString ) { // Everything becomes LF when parsed from server HTML. // Null character in an attribute becomes the replacement character. // Hydration also ends up with LF because we don't patch up attributes. expect(e.title).toBe('foo\nbar\nbaz\nqux\uFFFD'); } else { // Client rendering uses JS value with CR and null character. expect(e.title).toBe('foo\rbar\r\nbaz\nqux\u0000'); } }, ); }); describe('components that throw errors', function() { itThrowsWhenRendering( 'a function returning undefined', async render => { const UndefinedComponent = () => undefined; await render(<UndefinedComponent />, 1); }, 'UndefinedComponent(...): Nothing was returned from render. ' + 'This usually means a return statement is missing. Or, to ' + 'render nothing, return null.', ); itThrowsWhenRendering( 'a class returning undefined', async render => { class UndefinedComponent extends React.Component { render() { return undefined; } } await render(<UndefinedComponent />, 1); }, 'UndefinedComponent(...): Nothing was returned from render. ' + 'This usually means a return statement is missing. Or, to ' + 'render nothing, return null.', ); itThrowsWhenRendering( 'a function returning an object', async render => { const ObjectComponent = () => ({x: 123}); await render(<ObjectComponent />, 1); }, 'Objects are not valid as a React child (found: object with keys {x}).' + (__DEV__ ? ' If you meant to render a collection of children, use ' + 'an array instead.' : ''), ); itThrowsWhenRendering( 'a class returning an object', async render => { class ObjectComponent extends React.Component { render() { return {x: 123}; } } await render(<ObjectComponent />, 1); }, 'Objects are not valid as a React child (found: object with keys {x}).' + (__DEV__ ? ' If you meant to render a collection of children, use ' + 'an array instead.' : ''), ); itThrowsWhenRendering( 'top-level object', async render => { await render({x: 123}); }, 'Objects are not valid as a React child (found: object with keys {x}).' + (__DEV__ ? ' If you meant to render a collection of children, use ' + 'an array instead.' : ''), ); }); }); });
src/AppBar/AppBar.spec.js
hai-cea/material-ui
/* eslint-env mocha */ import React from 'react'; import {spy} from 'sinon'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import AppBar, {getStyles} from './AppBar'; import getMuiTheme from '../styles/getMuiTheme'; import IconButton from '../IconButton'; import FlatButton from '../FlatButton'; describe('<AppBar />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); it('renders children by default', () => { const testChildren = <div />; const wrapper = shallowWithContext( <AppBar>{testChildren}</AppBar> ); assert.ok(wrapper.contains(testChildren), 'should contain the children'); }); it('renders className', () => { const wrapper = shallowWithContext( <AppBar className="testClassName" /> ); assert.ok(wrapper.is('.testClassName'), 'should contain the className'); }); it('renders iconClassNameLeft', () => { const iconClassName = 'muidocs-icon-navigation-expand-more'; const wrapper = shallowWithContext( <AppBar iconClassNameLeft={iconClassName} /> ); assert.strictEqual(wrapper.find(IconButton).get(0).props.iconClassName, iconClassName, 'should contain iconClassNameLeft'); }); it('renders iconClassNameRight', () => { const iconClassName = 'muidocs-icon-navigation-expand-more'; const wrapper = shallowWithContext( <AppBar iconClassNameRight={iconClassName} /> ); assert.strictEqual(wrapper.find(IconButton).get(1).props.iconClassName, iconClassName, 'should contain iconClassNameRight'); }); it('renders iconClassNameLeft and iconClassNameRight', () => { const iconClassNameLeft = 'muidocs-icon-action-home'; const iconClassNameRight = 'muidocs-icon-navigation-expand-more'; const wrapper = shallowWithContext( <AppBar iconClassNameLeft={iconClassNameLeft} iconClassNameRight={iconClassNameRight} /> ); assert.strictEqual(wrapper.find(IconButton).get(0).props.iconClassName, iconClassNameLeft, 'should contain iconClassNameLeft'); assert.strictEqual(wrapper.find(IconButton).get(1).props.iconClassName, iconClassNameRight, 'should contain iconClassNameRight'); }); describe('iconElementLeft', () => { it('renders the node', () => { const wrapper = shallowWithContext( <AppBar iconElementLeft={<span className="icon" />} /> ); assert.strictEqual(wrapper.find('.icon').length, 1, 'should contain iconElementLeft'); }); it('renders the IconButton with a correct style', () => { const wrapper = shallowWithContext( <AppBar iconElementLeft={<IconButton><div /></IconButton>} /> ); assert.strictEqual( Object.keys(wrapper.find(IconButton).get(0).props.iconStyle).length > 0, true, 'should add some properties to the iconStyle' ); }); it('should triggers the onClick', () => { const handleClick = spy(); const wrapper = shallowWithContext( <AppBar iconElementLeft={<IconButton onClick={handleClick}><div /></IconButton>} /> ); wrapper.find(IconButton).simulate('click'); assert.strictEqual(handleClick.callCount, 1); }); }); describe('iconElementRight', () => { it('renders the node', () => { const wrapper = shallowWithContext( <AppBar iconElementRight={<span className="icon" />} /> ); assert.strictEqual(wrapper.find('.icon').length, 1, 'should contain iconElementRight'); }); it('renders the FlatButton with a correct style', () => { const wrapper = shallowWithContext( <AppBar iconElementRight={<FlatButton><div /></FlatButton>} /> ); assert.strictEqual( Object.keys(wrapper.find(FlatButton).get(0).props.style).length > 1, true, 'should add some properties to the style' ); }); }); describe('onLeftIconButtonClick', () => { it('should trigger the onClick', () => { const onLeftIconButtonClick = spy(); const wrapper = shallowWithContext( <AppBar onLeftIconButtonClick={onLeftIconButtonClick} /> ); wrapper.find(IconButton).simulate('click'); assert.strictEqual(onLeftIconButtonClick.callCount, 1, 'should have called onLeftIconButtonClick callback function'); }); it('should forward the onClick to onLeftIconButtonClick', () => { const handleClick = spy(); const wrapper = shallowWithContext( <AppBar iconElementLeft={<IconButton><div /></IconButton>} onLeftIconButtonClick={handleClick} /> ); wrapper.find(IconButton).simulate('click'); assert.strictEqual(handleClick.callCount, 1); }); }); describe('onRightIconButtonClick', () => { it('should trigger the onClick', () => { const handleRightIconButtonClick = spy(); const wrapper = shallowWithContext( <AppBar onRightIconButtonClick={handleRightIconButtonClick} iconClassNameRight="foo" /> ); wrapper.find(IconButton).at(1).simulate('click'); assert.strictEqual(handleRightIconButtonClick.callCount, 1, 'should have called onRightIconButtonClick callback function'); }); it('should forward the onClick to onRightIconButtonClick', () => { const handleClick = spy(); const wrapper = shallowWithContext( <AppBar iconElementRight={<IconButton><div /></IconButton>} onRightIconButtonClick={handleClick} /> ); wrapper.find(IconButton).at(1).simulate('click'); assert.strictEqual(handleClick.callCount, 1); }); }); it('call onTitleClick callback', () => { const onTitleClick = spy(); const wrapper = shallowWithContext( <AppBar title="Title" onTitleClick={onTitleClick} /> ); wrapper.find('h1').simulate('click'); assert.strictEqual(onTitleClick.callCount, 1, 'should have called onTitleClick callback function'); }); it('hide menu icon when showMenuIconButton is false', () => { const wrapper = shallowWithContext( <AppBar title="Title" showMenuIconButton={false} /> ); assert.strictEqual(wrapper.find(IconButton).length, 0, 'should not have menu icon'); }); it('renders AppBar and overwrite styles', () => { const style = { backgroundColor: 'red', }; const wrapper = shallowWithContext( <AppBar title="Title" style={style} /> ); assert.strictEqual(wrapper.get(0).props.style.backgroundColor, style.backgroundColor, 'should have backgroundColor to red'); }); it('renders title', () => { const wrapper = shallowWithContext( <AppBar title="Title" /> ); assert.strictEqual(wrapper.find('h1').length, 1, 'should have title'); }); it('renders title and overwrite title styles', () => { const titleStyle = { backgroundColor: 'red', }; const wrapper = shallowWithContext( <AppBar title="Title" titleStyle={titleStyle} /> ); assert.strictEqual(wrapper.find('h1').length, 1, 'should have title'); assert.strictEqual(wrapper.find('h1').get(0).props.style.backgroundColor, titleStyle.backgroundColor, 'should have backgroundColor to red'); }); it('renders zDepth to paper component', () => { const wrapper = shallowWithContext( <AppBar title="Title" zDepth={2} /> ); assert.strictEqual(wrapper.find('Paper').get(0).props.zDepth, 2, 'should have zDepth to 2'); }); it('menuElementLeft\'s style should be iconButtonStyle', () => { const wrapper = shallowWithContext( <AppBar /> ); const menuElementLeft = wrapper.find(IconButton).get(0); const style = menuElementLeft.props.style; const iconButtonStyle = getStyles(wrapper.props(), wrapper.context()).iconButtonStyle; assert.deepEqual(style, iconButtonStyle, 'style should be iconButtonStyle'); }); it('if pass iconStyleLeft={marginTop}, change the marginTop only', () => { const wrapper = shallowWithContext( <AppBar iconStyleLeft={{marginTop: 99}} /> ); const menuElementLeft = wrapper.find(IconButton).get(0); const style = menuElementLeft.props.style; const iconButtonStyle = getStyles(wrapper.props(), wrapper.context()).iconButtonStyle; const expectedStyle = Object.assign({}, iconButtonStyle, {marginTop: 99}); assert.deepEqual(style, expectedStyle, 'should be change style.marginTop only'); }); it('if pass iconElementLeft and iconStyleLeft={marginTop}, change the marginTop/muiPrepared only', () => { const wrapper = shallowWithContext( <AppBar iconElementLeft={<span>foo</span>} iconStyleLeft={{marginTop: 99}} /> ); const menuElementLeft = wrapper.find('div').get(0); const style = menuElementLeft.props.style; const iconButtonStyle = getStyles(wrapper.props(), wrapper.context()).iconButtonStyle; const expectedStyle = Object.assign({}, iconButtonStyle, {marginTop: 99, muiPrepared: true}); assert.deepEqual(style, expectedStyle, 'should be change style.marginTop/muiPrepared only'); }); });
web/node_modules/material-ui/svg-icons/action/perm-phone-msg.js
Jorginho211/TFG
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ActionPermPhoneMsg = function ActionPermPhoneMsg(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM12 3v10l3-3h6V3h-9z' }) ); }; ActionPermPhoneMsg = (0, _pure2.default)(ActionPermPhoneMsg); ActionPermPhoneMsg.displayName = 'ActionPermPhoneMsg'; ActionPermPhoneMsg.muiName = 'SvgIcon'; exports.default = ActionPermPhoneMsg;
eslint-rules/__tests__/warning-and-invariant-args-test.js
agileurbanite/react
/** * Copyright 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; var rule = require('../warning-and-invariant-args'); var RuleTester = require('eslint').RuleTester; var ruleTester = new RuleTester(); ruleTester.run('eslint-rules/warning-and-invariant-args', rule, { valid: [ "warning(true, 'hello, world');", "warning(true, 'expected %s, got %s', 42, 24);", "invariant(true, 'hello, world');", "invariant(true, 'expected %s, got %s', 42, 24);", ], invalid: [ { code: "warning('hello, world');", errors: [ { message: 'warning takes at least two arguments', }, ], }, { code: 'warning(true, null);', errors: [ { message: 'The second argument to warning must be a string literal', }, ], }, { code: 'var g = 5; invariant(true, g);', errors: [ { message: 'The second argument to invariant must be a string literal', }, ], }, { code: "warning(true, 'expected %s, got %s');", errors: [ { message: 'Expected 4 arguments in call to warning based on the number of ' + '"%s" substitutions, but got 2', }, ], }, { code: "warning(true, 'foo is a bar under foobar', 'junk argument');", errors: [ { message: 'Expected 2 arguments in call to warning based on the number of ' + '"%s" substitutions, but got 3', }, ], }, { code: "invariant(true, 'error!');", errors: [ { message: 'The invariant format should be able to uniquely identify this ' + 'invariant. Please, use a more descriptive format than: error!', }, ], }, { code: "warning(true, 'error!');", errors: [ { message: 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: error!', }, ], }, { code: "warning(true, '%s %s, %s %s: %s (%s)', 1, 2, 3, 4, 5, 6);", errors: [ { message: 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + '%s %s, %s %s: %s (%s)', }, ], }, ], });
src/components/Filter/Filter.js
swessar/gifs
import React from 'react'; import SearchBar from '../SearchBar/SearchBar'; import Images from '../Images/Images'; export default class Filter extends React.Component { constructor(props) { super(props); const { images } = this.props; this.state = { query: '', results: images } } componentWillReceiveProps(nextProps) { if (this.state.query) { this.doSearch(this.state.query); } else { this.setState({ results: nextProps.images, }); } } doSearch(searchText) { const { images } = this.props; var filteredImages = {}; Object.keys(images).map((key) => { for(var i = 0; i < images[key].keywords.length; i++) { if (images[key].keywords[i].indexOf(searchText) != -1) { filteredImages[key] = images[key]; } } }); this.setState({ query: searchText, results: filteredImages }); } render() { const { query, results } = this.state; return ( <div className="Filter"> <SearchBar query={query} doSearch={this.doSearch.bind(this)} count={Object.keys(results).length} /> <Images images={results} doSearch={this.doSearch.bind(this)} /> </div> ) } }
app/javascript/mastodon/features/report/components/status_check_box.js
foozmeat/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Toggle from 'react-toggle'; export default class StatusCheckBox extends React.PureComponent { static propTypes = { status: ImmutablePropTypes.map.isRequired, checked: PropTypes.bool, onToggle: PropTypes.func.isRequired, disabled: PropTypes.bool, }; render () { const { status, checked, onToggle, disabled } = this.props; const content = { __html: status.get('contentHtml') }; if (status.get('reblog')) { return null; } return ( <div className='status-check-box'> <div className='status__content' dangerouslySetInnerHTML={content} /> <div className='status-check-box-toggle'> <Toggle checked={checked} onChange={onToggle} disabled={disabled} /> </div> </div> ); } }
packages/material-ui-icons/src/Straighten.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H3V8h2v4h2V8h2v4h2V8h2v4h2V8h2v4h2V8h2v8z" /></React.Fragment> , 'Straighten');
src/routes.js
jjtaft/cityscoop
import React from 'react'; import { Router, Route, IndexRoute, hashHistory, } from 'react-router'; import Layout from 'components'; import { Home, Add } from 'containers'; // App routes const Routes = ( <Router history={hashHistory}> <Route path="/" component={Layout}> {/* IndexRoute renders Home container by default */} <IndexRoute component={Home} /> <Route path="Add" component={Add} /> </Route> </Router> ); export default Routes;
frontend/src/components/dashboard/partnerDashboard/numberOfCfeisBySector.js
unicef/un-partner-portal
import React from 'react'; import PropTypes from 'prop-types'; import Paper from 'material-ui/Paper'; import Button from 'material-ui/Button'; import Grid from 'material-ui/Grid'; import Divider from 'material-ui/Divider'; import Typography from 'material-ui/Typography'; import { withStyles } from 'material-ui/styles'; import { toPairs, isEmpty, map } from 'ramda'; import { Link } from 'react-router'; import GridColumn from '../../common/grid/gridColumn'; import PaddedContent from '../../common/paddedContent'; import CaptionTypography from '../../common/typography/captionTypography'; import VerticalBarChart from '../../common/charts/verticalBarChart'; const messages = { title: 'New Calls for Expressions of Interest by Sector', caption: 'in last 10 days', button: 'view all', number: 'number', }; const styleSheet = theme => ({ number: { paddingRight: theme.spacing.unit * 2, }, }); const NumberOfCfeisBySector = (props) => { const { newCfeiBySectors = {} } = props; let data; if (!isEmpty(newCfeiBySectors)) { data = map( ([sector, count]) => ({ name: sector, count }), toPairs(newCfeiBySectors)); } return ( <Paper> <PaddedContent> <GridColumn> <Typography type="headline">{messages.title}</Typography> <CaptionTypography>{messages.caption}</CaptionTypography> <Divider /> <VerticalBarChart data={data} containerProps={{ width: '100%', height: 500 }} barChartProps={{ margin: { left: 0, right: 16, top: 16 }, barCategoryGap: 8 }} barProps={{ fill: '#DCC0E4', barSize: 24 }} /> <Grid container justify="flex-end"> <Grid item> <Button component={Link} to="/cfei/open/" color="accent">{messages.button}</Button> </Grid> </Grid> </GridColumn> </PaddedContent> </Paper> ); }; NumberOfCfeisBySector.propTypes = { newCfeiBySectors: PropTypes.object, }; export default withStyles(styleSheet, { name: 'NumberOfCfeisBySector;' })(NumberOfCfeisBySector);
ajax/libs/qooxdoo/2.1/q.js
the-destro/cdnjs
/** qooxdoo v.2.1 | (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.ui.queue":false,"qx.optimization.variants":true,"qx.revision":"","qx.theme":"qx.theme.Modern","qx.version":"2.1"}; for (var k in envinfo) qx.$$environment[k] = envinfo[k]; qx.$$packageData = {}; /** qooxdoo v.2.1 | (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 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", "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; }); }, /** * 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: http://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()){ 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 && /Trident\/([^\);]+)(\)|;)/.test(agent)){ if(RegExp.$1 == "4.0"){ version = "8.0"; } else if(RegExp.$1 == "5.0"){ version = "9.0"; }; }; }; } 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; }, /** * Internal helper to check for MSHTML. * @return {Boolean} true, if its MSHTML. */ __isMshtml : function(){ return window.navigator.cpuClass && /MSIE\s+([^\);]+)(\)|;)/.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/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/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/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/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/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/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/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/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/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/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/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/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/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"); } }, 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); } }); /* ************************************************************************ 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/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/plugins/xregexp-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> * The implementation does not force a lowerCamelCase or upperCamelCase version. * (think java variables that start with lower case versus classnames that start with capital letter) * The first letter of the parameter keeps its case. * * @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(); }); this.__stringsMap[str] = result; }; return result; }, /** * Converts a camelcased string to a hyphenated (separated by '-') string. * * Example: * <pre class='javascript'>qx.lang.String.hyphenate("ILikeCookies"); //returns "I-like-cookies"</pre> * The implementation does not force a lowerCamelCase or upperCamelCase version. * (think java variables that start with lower case versus classnames that start with capital letter) * The first letter of the parameter keeps its case. * * @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()); }); 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(){ var value = "red 1px 1px 3px"; var el = document.createElement("div"); var style = qx.bom.Style.getAppliedStyle(el, "textShadow", value); return !style; }, /** * 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.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_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"){ if(name === "msie"){ 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", // 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 {@see qx.bom.element.Style}. */ qx.Bootstrap.define("qx.bom.Style", { statics : { /** Vendor-specific style property prefixes **/ VENDOR_PREFIXES : ["Webkit", "Moz", "O", "ms", "Khtml"], /** * 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; }, /** * 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/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/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/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.lang.String.hyphenate(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.lang.String.hyphenate(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.lang.String.hyphenate(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 var currentStyle = element.currentStyle[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 return computed ? computed[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){ 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/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/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 * * @type {Map} * @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){ var source = this.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 = target.length - 1;i >= 0;i--){ var descendants = target[i].getElementsByTagName("*"); for(var j = 0;j < descendants.length;j++){ target.push(descendants[j]); }; }; // make sure no emitter object has been copied target.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(target[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){ 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|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){ return !(/Fennec|HTC.Magic|Nexus|android.+mobile/i.test(userAgentString)) && (/Android|ipad|tablet|playbook|silk|kindle|psp/i.test(userAgentString)); } }, 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> * The implementation does not force a lowerCamelCase or upperCamelCase version. * The first letter of the parameter keeps its case. * * @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("ILikeCookies"); //returns "I-like-cookies"</pre> * The implementation does not force a lowerCamelCase or upperCamelCase version. * The first letter of the parameter keeps its case. * * @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 chould ba 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.lang.String.hyphenate(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; }, /** * 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")){ // http://developer.mozilla.org/en/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){ 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: 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) ************************************************************************ */ /** * 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++){ this[i].innerHTML = ""; }; 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 args {String[]|Element[]} HTML string(s) or DOM element(s) * @return {qxWeb} The collection for chaining */ before : function(args){ if(!qx.lang.Type.isArray(args)){ args = [args]; }; var fragment = document.createDocumentFragment(); qx.bom.Html.clean(args, 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 args {String[]|Element[]} HTML string(s) or DOM element(s) * @return {qxWeb} The collection for chaining */ after : function(args){ if(!qx.lang.Type.isArray(args)){ args = [args]; }; var fragment = document.createDocumentFragment(); qx.bom.Html.clean(args, 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: 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 }) }, /** * 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"); // Fix "XHTML"-style tags in all browsers // Replaces tags which are not allowed to be directly closed like // <code>div</code> or <code>p</code>. They are patched to use an // open and close tag instead e.g. <p> => <p></p> html = html.replace(/(<(\w+)[^>]*?)\/>/g, this.__fixNonDirectlyClosableHelper); // 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: 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{ if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Xhr, "Open native request with method: " + method + ", url: " + url + ", async: " + async); }; 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); if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Xhr, "Retry open native request with method: " + method + ", url: " + url + ", async: " + async); }; 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{ if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Xhr, "Send native request"); }; 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. * * Cancels any network activity. * @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; if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Xhr, "Received native readyState: " + nxhr.readyState); }; // 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: * * * <code>method</code> The method of the request. Default: <pre>GET</pre> * * <code>async</code> flag to mark the request as asynchronous. Default: <pre>true</pre> * * <code>header</code> A map of request headers. * * @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, /** * {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 { if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Jsonp, "Callback " + this.__callbackName + " already exists"); }; }; }; if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Jsonp, "Expecting JavaScript response to call: " + callbackName); }; query[callbackParam] = callbackName; 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; }, 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 = (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 : { __animationHandles : null, /** * Internal initializer to make sure we always have a plain array * for storing animation handles. * @internal */ $init : function(){ this.__animationHandles = []; }, /** * 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(){ return this.__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){ if(this.__animationHandles.length > 0){ throw new Error("Only one animation at a time."); }; for(var i = 0;i < this.length;i++){ var handle = qx.bom.element.Animation.animate(this[i], 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(){ var handles = self.__animationHandles; handles.splice(self.indexOf(handle), 1); if(handles.length == 0){ self.emit("animationEnd"); }; }, handle); this.__animationHandles.push(handle); }; 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){ if(this.__animationHandles.length > 0){ throw new Error("Only one animation at a time."); }; for(var i = 0;i < this.length;i++){ var handle = qx.bom.element.Animation.animateReverse(this[i], desc, duration); var self = this; handle.on("end", function(){ var handles = self.__animationHandles; handles.splice(self.indexOf(handle), 1); if(handles.length == 0){ self.emit("animationEnd"); }; }, handle); this.__animationHandles.push(handle); }; return this; }, /** * 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.__animationHandles.length;i++){ this.__animationHandles[i].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.__animationHandles.length;i++){ this.__animationHandles[i].pause(); }; return this; }, /** * Stops a running animation. * @attach {qxWeb} * @return {qxWeb} The collection for chaining. */ stop : function(){ for(var i = 0;i < this.__animationHandles.length;i++){ this.__animationHandles[i].stop(); }; this.__animationHandles = []; 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.__animationHandles.length;i++){ if(this.__animationHandles[i].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.__animationHandles.length;i++){ if(!this.__animationHandles[i].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 }); qxWeb.$attachInit(statics.$init); } }); /* ************************************************************************ 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.lang.String.hyphenate(prefixes[i]) + "-keyframes"; // special treatment for IE10 if(key == "@ms-keyframes"){ key = "@-ms-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", "oRequestAnmiationFrame"]; 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.animationId){ 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; }; // in case the animation is based on JS if(qx.bom.element.AnimationJs){ 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(); 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; window.setTimeout(function(){ 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); }; // check if animation is already stopped if(el == undefined){ return handle; }; // if we should keep a frame var keep = desc.keep; if(keep != undefined){ 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 if(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) ************************************************************************ */ /** * 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 { return window.setTimeout(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, __onMove : 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); }, /** * 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._fireEvent(domEvent, type); this.__checkAndFireGesture(domEvent, type); }, /* --------------------------------------------------------------------------- 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 clazz = qx.event.handler.TouchCore; var eventType; if(this.__originalTarget == target && Math.abs(deltaCoordinates.x) <= clazz.TAP_MAX_DISTANCE && Math.abs(deltaCoordinates.y) <= clazz.TAP_MAX_DISTANCE){ 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 = 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 * @type {Array} */ TYPES : ["orientationchange"], /** * List of qx.module.event.Orientation methods to be attached to native * event objects * @type {Array} * @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 * @type {Array} */ TYPES : ["keydown", "keypress", "keyup"], /** * List qx.module.event.Keyboard methods to be attached to native mouse event * objects * @type {Array} * @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) {} })();
src/containers/NotFound/NotFound.js
cellva/alluminate-temp-setup
import React from 'react'; export default function NotFound() { return ( <div className="container"> <h1>Doh! 404!</h1> <p>These are <em>not</em> the droids you are looking for!</p> </div> ); }
ajax/libs/clappr/0.0.66/clappr.js
mathiasrw/cdnjs
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (global){ "use strict"; var Player = require('./components/player'); var IframePlayer = require('./components/iframe_player'); var Mediator = require('mediator'); var version = require('../package.json').version; global.DEBUG = false; window.Clappr = { Player: Player, Mediator: Mediator, IframePlayer: IframePlayer }; window.Clappr.version = version; module.exports = window.Clappr; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../package.json":6,"./components/iframe_player":18,"./components/player":22,"mediator":"mediator"}],2:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canMutationObserver = typeof window !== 'undefined' && window.MutationObserver; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } var queue = []; if (canMutationObserver) { var hiddenDiv = document.createElement("div"); var observer = new MutationObserver(function () { var queueList = queue.slice(); queue.length = 0; queueList.forEach(function (fn) { fn(); }); }); observer.observe(hiddenDiv, { attributes: true }); return function nextTick(fn) { if (!queue.length) { hiddenDiv.setAttribute('yes', 'no'); } queue.push(fn); }; } if (canPost) { window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],3:[function(require,module,exports){ (function (process,global){ (function(global) { 'use strict'; if (global.$traceurRuntime) { return; } var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $Object.defineProperties; var $defineProperty = $Object.defineProperty; var $freeze = $Object.freeze; var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor; var $getOwnPropertyNames = $Object.getOwnPropertyNames; var $keys = $Object.keys; var $hasOwnProperty = $Object.prototype.hasOwnProperty; var $toString = $Object.prototype.toString; var $preventExtensions = Object.preventExtensions; var $seal = Object.seal; var $isExtensible = Object.isExtensible; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var types = { void: function voidType() {}, any: function any() {}, string: function string() {}, number: function number() {}, boolean: function boolean() {} }; var method = nonEnum; var counter = 0; function newUniqueString() { return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__'; } var symbolInternalProperty = newUniqueString(); var symbolDescriptionProperty = newUniqueString(); var symbolDataProperty = newUniqueString(); var symbolValues = $create(null); var privateNames = $create(null); function createPrivateName() { var s = newUniqueString(); privateNames[s] = true; return s; } function isSymbol(symbol) { return typeof symbol === 'object' && symbol instanceof SymbolValue; } function typeOf(v) { if (isSymbol(v)) return 'symbol'; return typeof v; } function Symbol(description) { var value = new SymbolValue(description); if (!(this instanceof Symbol)) return value; throw new TypeError('Symbol cannot be new\'ed'); } $defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(Symbol.prototype, 'toString', method(function() { var symbolValue = this[symbolDataProperty]; if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); var desc = symbolValue[symbolDescriptionProperty]; if (desc === undefined) desc = ''; return 'Symbol(' + desc + ')'; })); $defineProperty(Symbol.prototype, 'valueOf', method(function() { var symbolValue = this[symbolDataProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; return symbolValue; })); function SymbolValue(description) { var key = newUniqueString(); $defineProperty(this, symbolDataProperty, {value: this}); $defineProperty(this, symbolInternalProperty, {value: key}); $defineProperty(this, symbolDescriptionProperty, {value: description}); freeze(this); symbolValues[key] = this; } $defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(SymbolValue.prototype, 'toString', { value: Symbol.prototype.toString, enumerable: false }); $defineProperty(SymbolValue.prototype, 'valueOf', { value: Symbol.prototype.valueOf, enumerable: false }); var hashProperty = createPrivateName(); var hashPropertyDescriptor = {value: undefined}; var hashObjectProperties = { hash: {value: undefined}, self: {value: undefined} }; var hashCounter = 0; function getOwnHashObject(object) { var hashObject = object[hashProperty]; if (hashObject && hashObject.self === object) return hashObject; if ($isExtensible(object)) { hashObjectProperties.hash.value = hashCounter++; hashObjectProperties.self.value = object; hashPropertyDescriptor.value = $create(null, hashObjectProperties); $defineProperty(object, hashProperty, hashPropertyDescriptor); return hashPropertyDescriptor.value; } return undefined; } function freeze(object) { getOwnHashObject(object); return $freeze.apply(this, arguments); } function preventExtensions(object) { getOwnHashObject(object); return $preventExtensions.apply(this, arguments); } function seal(object) { getOwnHashObject(object); return $seal.apply(this, arguments); } Symbol.iterator = Symbol(); freeze(SymbolValue.prototype); function toProperty(name) { if (isSymbol(name)) return name[symbolInternalProperty]; return name; } function getOwnPropertyNames(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; if (!symbolValues[name] && !privateNames[name]) rv.push(name); } return rv; } function getOwnPropertyDescriptor(object, name) { return $getOwnPropertyDescriptor(object, toProperty(name)); } function getOwnPropertySymbols(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var symbol = symbolValues[names[i]]; if (symbol) rv.push(symbol); } return rv; } function hasOwnProperty(name) { return $hasOwnProperty.call(this, toProperty(name)); } function getOption(name) { return global.traceur && global.traceur.options[name]; } function setProperty(object, name, value) { var sym, desc; if (isSymbol(name)) { sym = name; name = name[symbolInternalProperty]; } object[name] = value; if (sym && (desc = $getOwnPropertyDescriptor(object, name))) $defineProperty(object, name, {enumerable: false}); return value; } function defineProperty(object, name, descriptor) { if (isSymbol(name)) { if (descriptor.enumerable) { descriptor = $create(descriptor, {enumerable: {value: false}}); } name = name[symbolInternalProperty]; } $defineProperty(object, name, descriptor); return object; } function polyfillObject(Object) { $defineProperty(Object, 'defineProperty', {value: defineProperty}); $defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames}); $defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor}); $defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty}); $defineProperty(Object, 'freeze', {value: freeze}); $defineProperty(Object, 'preventExtensions', {value: preventExtensions}); $defineProperty(Object, 'seal', {value: seal}); Object.getOwnPropertySymbols = getOwnPropertySymbols; } function exportStar(object) { for (var i = 1; i < arguments.length; i++) { var names = $getOwnPropertyNames(arguments[i]); for (var j = 0; j < names.length; j++) { var name = names[j]; if (privateNames[name]) continue; (function(mod, name) { $defineProperty(object, name, { get: function() { return mod[name]; }, enumerable: true }); })(arguments[i], names[j]); } } return object; } function isObject(x) { return x != null && (typeof x === 'object' || typeof x === 'function'); } function toObject(x) { if (x == null) throw $TypeError(); return $Object(x); } function checkObjectCoercible(argument) { if (argument == null) { throw new TypeError('Value cannot be converted to an Object'); } return argument; } function setupGlobals(global) { global.Symbol = Symbol; global.Reflect = global.Reflect || {}; global.Reflect.global = global.Reflect.global || global; polyfillObject(global.Object); } setupGlobals(global); global.$traceurRuntime = { createPrivateName: createPrivateName, exportStar: exportStar, getOwnHashObject: getOwnHashObject, privateNames: privateNames, setProperty: setProperty, setupGlobals: setupGlobals, toObject: toObject, isObject: isObject, toProperty: toProperty, type: types, typeof: typeOf, checkObjectCoercible: checkObjectCoercible, hasOwnProperty: function(o, p) { return hasOwnProperty.call(o, p); }, defineProperties: $defineProperties, defineProperty: $defineProperty, getOwnPropertyDescriptor: $getOwnPropertyDescriptor, getOwnPropertyNames: $getOwnPropertyNames, keys: $keys }; })(typeof global !== 'undefined' ? global : this); (function() { 'use strict'; function spread() { var rv = [], j = 0, iterResult; for (var i = 0; i < arguments.length; i++) { var valueToSpread = $traceurRuntime.checkObjectCoercible(arguments[i]); if (typeof valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)] !== 'function') { throw new TypeError('Cannot spread non-iterable object.'); } var iter = valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)](); while (!(iterResult = iter.next()).done) { rv[j++] = iterResult.value; } } return rv; } $traceurRuntime.spread = spread; })(); (function() { 'use strict'; var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor; var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames; var $getPrototypeOf = Object.getPrototypeOf; function superDescriptor(homeObject, name) { var proto = $getPrototypeOf(homeObject); do { var result = $getOwnPropertyDescriptor(proto, name); if (result) return result; proto = $getPrototypeOf(proto); } while (proto); return undefined; } function superCall(self, homeObject, name, args) { return superGet(self, homeObject, name).apply(self, args); } function superGet(self, homeObject, name) { var descriptor = superDescriptor(homeObject, name); if (descriptor) { if (!descriptor.get) return descriptor.value; return descriptor.get.call(self); } return undefined; } function superSet(self, homeObject, name, value) { var descriptor = superDescriptor(homeObject, name); if (descriptor && descriptor.set) { descriptor.set.call(self, value); return value; } throw $TypeError("super has no setter '" + name + "'."); } function getDescriptors(object) { var descriptors = {}, name, names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; descriptors[name] = $getOwnPropertyDescriptor(object, name); } return descriptors; } function createClass(ctor, object, staticObject, superClass) { $defineProperty(object, 'constructor', { value: ctor, configurable: true, enumerable: false, writable: true }); if (arguments.length > 3) { if (typeof superClass === 'function') ctor.__proto__ = superClass; ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object)); } else { ctor.prototype = object; } $defineProperty(ctor, 'prototype', { configurable: false, writable: false }); return $defineProperties(ctor, getDescriptors(staticObject)); } function getProtoParent(superClass) { if (typeof superClass === 'function') { var prototype = superClass.prototype; if ($Object(prototype) === prototype || prototype === null) return superClass.prototype; throw new $TypeError('super prototype must be an Object or null'); } if (superClass === null) return null; throw new $TypeError(("Super expression must either be null or a function, not " + typeof superClass + ".")); } function defaultSuperCall(self, homeObject, args) { if ($getPrototypeOf(homeObject) !== null) superCall(self, homeObject, 'constructor', args); } $traceurRuntime.createClass = createClass; $traceurRuntime.defaultSuperCall = defaultSuperCall; $traceurRuntime.superCall = superCall; $traceurRuntime.superGet = superGet; $traceurRuntime.superSet = superSet; })(); (function() { 'use strict'; var createPrivateName = $traceurRuntime.createPrivateName; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $create = Object.create; var $TypeError = TypeError; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var ST_NEWBORN = 0; var ST_EXECUTING = 1; var ST_SUSPENDED = 2; var ST_CLOSED = 3; var END_STATE = -2; var RETHROW_STATE = -3; function getInternalError(state) { return new Error('Traceur compiler bug: invalid state in state machine: ' + state); } function GeneratorContext() { this.state = 0; this.GState = ST_NEWBORN; this.storedException = undefined; this.finallyFallThrough = undefined; this.sent_ = undefined; this.returnValue = undefined; this.tryStack_ = []; } GeneratorContext.prototype = { pushTry: function(catchState, finallyState) { if (finallyState !== null) { var finallyFallThrough = null; for (var i = this.tryStack_.length - 1; i >= 0; i--) { if (this.tryStack_[i].catch !== undefined) { finallyFallThrough = this.tryStack_[i].catch; break; } } if (finallyFallThrough === null) finallyFallThrough = RETHROW_STATE; this.tryStack_.push({ finally: finallyState, finallyFallThrough: finallyFallThrough }); } if (catchState !== null) { this.tryStack_.push({catch: catchState}); } }, popTry: function() { this.tryStack_.pop(); }, get sent() { this.maybeThrow(); return this.sent_; }, set sent(v) { this.sent_ = v; }, get sentIgnoreThrow() { return this.sent_; }, maybeThrow: function() { if (this.action === 'throw') { this.action = 'next'; throw this.sent_; } }, end: function() { switch (this.state) { case END_STATE: return this; case RETHROW_STATE: throw this.storedException; default: throw getInternalError(this.state); } }, handleException: function(ex) { this.GState = ST_CLOSED; this.state = END_STATE; throw ex; } }; function nextOrThrow(ctx, moveNext, action, x) { switch (ctx.GState) { case ST_EXECUTING: throw new Error(("\"" + action + "\" on executing generator")); case ST_CLOSED: if (action == 'next') { return { value: undefined, done: true }; } throw x; case ST_NEWBORN: if (action === 'throw') { ctx.GState = ST_CLOSED; throw x; } if (x !== undefined) throw $TypeError('Sent value to newborn generator'); case ST_SUSPENDED: ctx.GState = ST_EXECUTING; ctx.action = action; ctx.sent = x; var value = moveNext(ctx); var done = value === ctx; if (done) value = ctx.returnValue; ctx.GState = done ? ST_CLOSED : ST_SUSPENDED; return { value: value, done: done }; } } var ctxName = createPrivateName(); var moveNextName = createPrivateName(); function GeneratorFunction() {} function GeneratorFunctionPrototype() {} GeneratorFunction.prototype = GeneratorFunctionPrototype; $defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction)); GeneratorFunctionPrototype.prototype = { constructor: GeneratorFunctionPrototype, next: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'next', v); }, throw: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v); } }; $defineProperties(GeneratorFunctionPrototype.prototype, { constructor: {enumerable: false}, next: {enumerable: false}, throw: {enumerable: false} }); Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() { return this; })); function createGeneratorInstance(innerFunction, functionObject, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new GeneratorContext(); var object = $create(functionObject.prototype); object[ctxName] = ctx; object[moveNextName] = moveNext; return object; } function initGeneratorFunction(functionObject) { functionObject.prototype = $create(GeneratorFunctionPrototype.prototype); functionObject.__proto__ = GeneratorFunctionPrototype; return functionObject; } function AsyncFunctionContext() { GeneratorContext.call(this); this.err = undefined; var ctx = this; ctx.result = new Promise(function(resolve, reject) { ctx.resolve = resolve; ctx.reject = reject; }); } AsyncFunctionContext.prototype = $create(GeneratorContext.prototype); AsyncFunctionContext.prototype.end = function() { switch (this.state) { case END_STATE: this.resolve(this.returnValue); break; case RETHROW_STATE: this.reject(this.storedException); break; default: this.reject(getInternalError(this.state)); } }; AsyncFunctionContext.prototype.handleException = function() { this.state = RETHROW_STATE; }; function asyncWrap(innerFunction, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new AsyncFunctionContext(); ctx.createCallback = function(newState) { return function(value) { ctx.state = newState; ctx.value = value; moveNext(ctx); }; }; ctx.errback = function(err) { handleCatch(ctx, err); moveNext(ctx); }; moveNext(ctx); return ctx.result; } function getMoveNext(innerFunction, self) { return function(ctx) { while (true) { try { return innerFunction.call(self, ctx); } catch (ex) { handleCatch(ctx, ex); } } }; } function handleCatch(ctx, ex) { ctx.storedException = ex; var last = ctx.tryStack_[ctx.tryStack_.length - 1]; if (!last) { ctx.handleException(ex); return; } ctx.state = last.catch !== undefined ? last.catch : last.finally; if (last.finallyFallThrough !== undefined) ctx.finallyFallThrough = last.finallyFallThrough; } $traceurRuntime.asyncWrap = asyncWrap; $traceurRuntime.initGeneratorFunction = initGeneratorFunction; $traceurRuntime.createGeneratorInstance = createGeneratorInstance; })(); (function() { function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { var out = []; if (opt_scheme) { out.push(opt_scheme, ':'); } if (opt_domain) { out.push('//'); if (opt_userInfo) { out.push(opt_userInfo, '@'); } out.push(opt_domain); if (opt_port) { out.push(':', opt_port); } } if (opt_path) { out.push(opt_path); } if (opt_queryData) { out.push('?', opt_queryData); } if (opt_fragment) { out.push('#', opt_fragment); } return out.join(''); } ; var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$'); var ComponentIndex = { SCHEME: 1, USER_INFO: 2, DOMAIN: 3, PORT: 4, PATH: 5, QUERY_DATA: 6, FRAGMENT: 7 }; function split(uri) { return (uri.match(splitRe)); } function removeDotSegments(path) { if (path === '/') return '/'; var leadingSlash = path[0] === '/' ? '/' : ''; var trailingSlash = path.slice(-1) === '/' ? '/' : ''; var segments = path.split('/'); var out = []; var up = 0; for (var pos = 0; pos < segments.length; pos++) { var segment = segments[pos]; switch (segment) { case '': case '.': break; case '..': if (out.length) out.pop(); else up++; break; default: out.push(segment); } } if (!leadingSlash) { while (up-- > 0) { out.unshift('..'); } if (out.length === 0) out.push('.'); } return leadingSlash + out.join('/') + trailingSlash; } function joinAndCanonicalizePath(parts) { var path = parts[ComponentIndex.PATH] || ''; path = removeDotSegments(path); parts[ComponentIndex.PATH] = path; return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]); } function canonicalizeUrl(url) { var parts = split(url); return joinAndCanonicalizePath(parts); } function resolveUrl(base, url) { var parts = split(url); var baseParts = split(base); if (parts[ComponentIndex.SCHEME]) { return joinAndCanonicalizePath(parts); } else { parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME]; } for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) { if (!parts[i]) { parts[i] = baseParts[i]; } } if (parts[ComponentIndex.PATH][0] == '/') { return joinAndCanonicalizePath(parts); } var path = baseParts[ComponentIndex.PATH]; var index = path.lastIndexOf('/'); path = path.slice(0, index + 1) + parts[ComponentIndex.PATH]; parts[ComponentIndex.PATH] = path; return joinAndCanonicalizePath(parts); } function isAbsolute(name) { if (!name) return false; if (name[0] === '/') return true; var parts = split(name); if (parts[ComponentIndex.SCHEME]) return true; return false; } $traceurRuntime.canonicalizeUrl = canonicalizeUrl; $traceurRuntime.isAbsolute = isAbsolute; $traceurRuntime.removeDotSegments = removeDotSegments; $traceurRuntime.resolveUrl = resolveUrl; })(); (function(global) { 'use strict'; var $__2 = $traceurRuntime, canonicalizeUrl = $__2.canonicalizeUrl, resolveUrl = $__2.resolveUrl, isAbsolute = $__2.isAbsolute; var moduleInstantiators = Object.create(null); var baseURL; if (global.location && global.location.href) baseURL = resolveUrl(global.location.href, './'); else baseURL = ''; var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) { this.url = url; this.value_ = uncoatedModule; }; ($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {}); var ModuleEvaluationError = function ModuleEvaluationError(erroneousModuleName, cause) { this.message = this.constructor.name + ': ' + this.stripCause(cause) + ' in ' + erroneousModuleName; if (!(cause instanceof $ModuleEvaluationError) && cause.stack) this.stack = this.stripStack(cause.stack); else this.stack = ''; }; var $ModuleEvaluationError = ModuleEvaluationError; ($traceurRuntime.createClass)(ModuleEvaluationError, { stripError: function(message) { return message.replace(/.*Error:/, this.constructor.name + ':'); }, stripCause: function(cause) { if (!cause) return ''; if (!cause.message) return cause + ''; return this.stripError(cause.message); }, loadedBy: function(moduleName) { this.stack += '\n loaded by ' + moduleName; }, stripStack: function(causeStack) { var stack = []; causeStack.split('\n').some((function(frame) { if (/UncoatedModuleInstantiator/.test(frame)) return true; stack.push(frame); })); stack[0] = this.stripError(stack[0]); return stack.join('\n'); } }, {}, Error); var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) { $traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]); this.func = func; }; var $UncoatedModuleInstantiator = UncoatedModuleInstantiator; ($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() { if (this.value_) return this.value_; try { return this.value_ = this.func.call(global); } catch (ex) { if (ex instanceof ModuleEvaluationError) { ex.loadedBy(this.url); throw ex; } throw new ModuleEvaluationError(this.url, ex); } }}, {}, UncoatedModuleEntry); function getUncoatedModuleInstantiator(name) { if (!name) return; var url = ModuleStore.normalize(name); return moduleInstantiators[url]; } ; var moduleInstances = Object.create(null); var liveModuleSentinel = {}; function Module(uncoatedModule) { var isLive = arguments[1]; var coatedModule = Object.create(null); Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) { var getter, value; if (isLive === liveModuleSentinel) { var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name); if (descr.get) getter = descr.get; } if (!getter) { value = uncoatedModule[name]; getter = function() { return value; }; } Object.defineProperty(coatedModule, name, { get: getter, enumerable: true }); })); Object.preventExtensions(coatedModule); return coatedModule; } var ModuleStore = { normalize: function(name, refererName, refererAddress) { if (typeof name !== "string") throw new TypeError("module name must be a string, not " + typeof name); if (isAbsolute(name)) return canonicalizeUrl(name); if (/[^\.]\/\.\.\//.test(name)) { throw new Error('module name embeds /../: ' + name); } if (name[0] === '.' && refererName) return resolveUrl(refererName, name); return canonicalizeUrl(name); }, get: function(normalizedName) { var m = getUncoatedModuleInstantiator(normalizedName); if (!m) return undefined; var moduleInstance = moduleInstances[m.url]; if (moduleInstance) return moduleInstance; moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel); return moduleInstances[m.url] = moduleInstance; }, set: function(normalizedName, module) { normalizedName = String(normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() { return module; })); moduleInstances[normalizedName] = module; }, get baseURL() { return baseURL; }, set baseURL(v) { baseURL = String(v); }, registerModule: function(name, func) { var normalizedName = ModuleStore.normalize(name); if (moduleInstantiators[normalizedName]) throw new Error('duplicate module named ' + normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func); }, bundleStore: Object.create(null), register: function(name, deps, func) { if (!deps || !deps.length && !func.length) { this.registerModule(name, func); } else { this.bundleStore[name] = { deps: deps, execute: function() { var $__0 = arguments; var depMap = {}; deps.forEach((function(dep, index) { return depMap[dep] = $__0[index]; })); var registryEntry = func.call(this, depMap); registryEntry.execute.call(this); return registryEntry.exports; } }; } }, getAnonymousModule: function(func) { return new Module(func.call(global), liveModuleSentinel); }, getForTesting: function(name) { var $__0 = this; if (!this.testingPrefix_) { Object.keys(moduleInstances).some((function(key) { var m = /(traceur@[^\/]*\/)/.exec(key); if (m) { $__0.testingPrefix_ = m[1]; return true; } })); } return this.get(this.testingPrefix_ + name); } }; ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore})); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); }; $traceurRuntime.ModuleStore = ModuleStore; global.System = { register: ModuleStore.register.bind(ModuleStore), get: ModuleStore.get, set: ModuleStore.set, normalize: ModuleStore.normalize }; $traceurRuntime.getModuleImpl = function(name) { var instantiator = getUncoatedModuleInstantiator(name); return instantiator && instantiator.getUncoatedModule(); }; })(typeof global !== 'undefined' ? global : this); System.register("[email protected]/src/runtime/polyfills/utils", [], function() { "use strict"; var __moduleName = "[email protected]/src/runtime/polyfills/utils"; var $ceil = Math.ceil; var $floor = Math.floor; var $isFinite = isFinite; var $isNaN = isNaN; var $pow = Math.pow; var $min = Math.min; var toObject = $traceurRuntime.toObject; function toUint32(x) { return x >>> 0; } function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function isCallable(x) { return typeof x === 'function'; } function isNumber(x) { return typeof x === 'number'; } function toInteger(x) { x = +x; if ($isNaN(x)) return 0; if (x === 0 || !$isFinite(x)) return x; return x > 0 ? $floor(x) : $ceil(x); } var MAX_SAFE_LENGTH = $pow(2, 53) - 1; function toLength(x) { var len = toInteger(x); return len < 0 ? 0 : $min(len, MAX_SAFE_LENGTH); } function checkIterable(x) { return !isObject(x) ? undefined : x[Symbol.iterator]; } function isConstructor(x) { return isCallable(x); } function createIteratorResultObject(value, done) { return { value: value, done: done }; } function maybeDefine(object, name, descr) { if (!(name in object)) { Object.defineProperty(object, name, descr); } } function maybeDefineMethod(object, name, value) { maybeDefine(object, name, { value: value, configurable: true, enumerable: false, writable: true }); } function maybeDefineConst(object, name, value) { maybeDefine(object, name, { value: value, configurable: false, enumerable: false, writable: false }); } function maybeAddFunctions(object, functions) { for (var i = 0; i < functions.length; i += 2) { var name = functions[i]; var value = functions[i + 1]; maybeDefineMethod(object, name, value); } } function maybeAddConsts(object, consts) { for (var i = 0; i < consts.length; i += 2) { var name = consts[i]; var value = consts[i + 1]; maybeDefineConst(object, name, value); } } function maybeAddIterator(object, func, Symbol) { if (!Symbol || !Symbol.iterator || object[Symbol.iterator]) return; if (object['@@iterator']) func = object['@@iterator']; Object.defineProperty(object, Symbol.iterator, { value: func, configurable: true, enumerable: false, writable: true }); } var polyfills = []; function registerPolyfill(func) { polyfills.push(func); } function polyfillAll(global) { polyfills.forEach((function(f) { return f(global); })); } return { get toObject() { return toObject; }, get toUint32() { return toUint32; }, get isObject() { return isObject; }, get isCallable() { return isCallable; }, get isNumber() { return isNumber; }, get toInteger() { return toInteger; }, get toLength() { return toLength; }, get checkIterable() { return checkIterable; }, get isConstructor() { return isConstructor; }, get createIteratorResultObject() { return createIteratorResultObject; }, get maybeDefine() { return maybeDefine; }, get maybeDefineMethod() { return maybeDefineMethod; }, get maybeDefineConst() { return maybeDefineConst; }, get maybeAddFunctions() { return maybeAddFunctions; }, get maybeAddConsts() { return maybeAddConsts; }, get maybeAddIterator() { return maybeAddIterator; }, get registerPolyfill() { return registerPolyfill; }, get polyfillAll() { return polyfillAll; } }; }); System.register("[email protected]/src/runtime/polyfills/Map", [], function() { "use strict"; var __moduleName = "[email protected]/src/runtime/polyfills/Map"; var $__3 = System.get("[email protected]/src/runtime/polyfills/utils"), isObject = $__3.isObject, maybeAddIterator = $__3.maybeAddIterator, registerPolyfill = $__3.registerPolyfill; var getOwnHashObject = $traceurRuntime.getOwnHashObject; var $hasOwnProperty = Object.prototype.hasOwnProperty; var deletedSentinel = {}; function lookupIndex(map, key) { if (isObject(key)) { var hashObject = getOwnHashObject(key); return hashObject && map.objectIndex_[hashObject.hash]; } if (typeof key === 'string') return map.stringIndex_[key]; return map.primitiveIndex_[key]; } function initMap(map) { map.entries_ = []; map.objectIndex_ = Object.create(null); map.stringIndex_ = Object.create(null); map.primitiveIndex_ = Object.create(null); map.deletedCount_ = 0; } var Map = function Map() { var iterable = arguments[0]; if (!isObject(this)) throw new TypeError('Map called on incompatible type'); if ($hasOwnProperty.call(this, 'entries_')) { throw new TypeError('Map can not be reentrantly initialised'); } initMap(this); if (iterable !== null && iterable !== undefined) { for (var $__5 = iterable[Symbol.iterator](), $__6; !($__6 = $__5.next()).done; ) { var $__7 = $__6.value, key = $__7[0], value = $__7[1]; { this.set(key, value); } } } }; ($traceurRuntime.createClass)(Map, { get size() { return this.entries_.length / 2 - this.deletedCount_; }, get: function(key) { var index = lookupIndex(this, key); if (index !== undefined) return this.entries_[index + 1]; }, set: function(key, value) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index = lookupIndex(this, key); if (index !== undefined) { this.entries_[index + 1] = value; } else { index = this.entries_.length; this.entries_[index] = key; this.entries_[index + 1] = value; if (objectMode) { var hashObject = getOwnHashObject(key); var hash = hashObject.hash; this.objectIndex_[hash] = index; } else if (stringMode) { this.stringIndex_[key] = index; } else { this.primitiveIndex_[key] = index; } } return this; }, has: function(key) { return lookupIndex(this, key) !== undefined; }, delete: function(key) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index; var hash; if (objectMode) { var hashObject = getOwnHashObject(key); if (hashObject) { index = this.objectIndex_[hash = hashObject.hash]; delete this.objectIndex_[hash]; } } else if (stringMode) { index = this.stringIndex_[key]; delete this.stringIndex_[key]; } else { index = this.primitiveIndex_[key]; delete this.primitiveIndex_[key]; } if (index !== undefined) { this.entries_[index] = deletedSentinel; this.entries_[index + 1] = undefined; this.deletedCount_++; return true; } return false; }, clear: function() { initMap(this); }, forEach: function(callbackFn) { var thisArg = arguments[1]; for (var i = 0; i < this.entries_.length; i += 2) { var key = this.entries_[i]; var value = this.entries_[i + 1]; if (key === deletedSentinel) continue; callbackFn.call(thisArg, value, key, this); } }, entries: $traceurRuntime.initGeneratorFunction(function $__8() { var i, key, value; return $traceurRuntime.createGeneratorInstance(function($ctx) { while (true) switch ($ctx.state) { case 0: i = 0; $ctx.state = 12; break; case 12: $ctx.state = (i < this.entries_.length) ? 8 : -2; break; case 4: i += 2; $ctx.state = 12; break; case 8: key = this.entries_[i]; value = this.entries_[i + 1]; $ctx.state = 9; break; case 9: $ctx.state = (key === deletedSentinel) ? 4 : 6; break; case 6: $ctx.state = 2; return [key, value]; case 2: $ctx.maybeThrow(); $ctx.state = 4; break; default: return $ctx.end(); } }, $__8, this); }), keys: $traceurRuntime.initGeneratorFunction(function $__9() { var i, key, value; return $traceurRuntime.createGeneratorInstance(function($ctx) { while (true) switch ($ctx.state) { case 0: i = 0; $ctx.state = 12; break; case 12: $ctx.state = (i < this.entries_.length) ? 8 : -2; break; case 4: i += 2; $ctx.state = 12; break; case 8: key = this.entries_[i]; value = this.entries_[i + 1]; $ctx.state = 9; break; case 9: $ctx.state = (key === deletedSentinel) ? 4 : 6; break; case 6: $ctx.state = 2; return key; case 2: $ctx.maybeThrow(); $ctx.state = 4; break; default: return $ctx.end(); } }, $__9, this); }), values: $traceurRuntime.initGeneratorFunction(function $__10() { var i, key, value; return $traceurRuntime.createGeneratorInstance(function($ctx) { while (true) switch ($ctx.state) { case 0: i = 0; $ctx.state = 12; break; case 12: $ctx.state = (i < this.entries_.length) ? 8 : -2; break; case 4: i += 2; $ctx.state = 12; break; case 8: key = this.entries_[i]; value = this.entries_[i + 1]; $ctx.state = 9; break; case 9: $ctx.state = (key === deletedSentinel) ? 4 : 6; break; case 6: $ctx.state = 2; return value; case 2: $ctx.maybeThrow(); $ctx.state = 4; break; default: return $ctx.end(); } }, $__10, this); }) }, {}); Object.defineProperty(Map.prototype, Symbol.iterator, { configurable: true, writable: true, value: Map.prototype.entries }); function polyfillMap(global) { var $__7 = global, Object = $__7.Object, Symbol = $__7.Symbol; if (!global.Map) global.Map = Map; var mapPrototype = global.Map.prototype; if (mapPrototype.entries) { maybeAddIterator(mapPrototype, mapPrototype.entries, Symbol); maybeAddIterator(Object.getPrototypeOf(new global.Map().entries()), function() { return this; }, Symbol); } } registerPolyfill(polyfillMap); return { get Map() { return Map; }, get polyfillMap() { return polyfillMap; } }; }); System.get("[email protected]/src/runtime/polyfills/Map" + ''); System.register("[email protected]/src/runtime/polyfills/Set", [], function() { "use strict"; var __moduleName = "[email protected]/src/runtime/polyfills/Set"; var $__11 = System.get("[email protected]/src/runtime/polyfills/utils"), isObject = $__11.isObject, maybeAddIterator = $__11.maybeAddIterator, registerPolyfill = $__11.registerPolyfill; var Map = System.get("[email protected]/src/runtime/polyfills/Map").Map; var getOwnHashObject = $traceurRuntime.getOwnHashObject; var $hasOwnProperty = Object.prototype.hasOwnProperty; function initSet(set) { set.map_ = new Map(); } var Set = function Set() { var iterable = arguments[0]; if (!isObject(this)) throw new TypeError('Set called on incompatible type'); if ($hasOwnProperty.call(this, 'map_')) { throw new TypeError('Set can not be reentrantly initialised'); } initSet(this); if (iterable !== null && iterable !== undefined) { for (var $__15 = iterable[Symbol.iterator](), $__16; !($__16 = $__15.next()).done; ) { var item = $__16.value; { this.add(item); } } } }; ($traceurRuntime.createClass)(Set, { get size() { return this.map_.size; }, has: function(key) { return this.map_.has(key); }, add: function(key) { this.map_.set(key, key); return this; }, delete: function(key) { return this.map_.delete(key); }, clear: function() { return this.map_.clear(); }, forEach: function(callbackFn) { var thisArg = arguments[1]; var $__13 = this; return this.map_.forEach((function(value, key) { callbackFn.call(thisArg, key, key, $__13); })); }, values: $traceurRuntime.initGeneratorFunction(function $__18() { var $__19, $__20; return $traceurRuntime.createGeneratorInstance(function($ctx) { while (true) switch ($ctx.state) { case 0: $__19 = this.map_.keys()[Symbol.iterator](); $ctx.sent = void 0; $ctx.action = 'next'; $ctx.state = 12; break; case 12: $__20 = $__19[$ctx.action]($ctx.sentIgnoreThrow); $ctx.state = 9; break; case 9: $ctx.state = ($__20.done) ? 3 : 2; break; case 3: $ctx.sent = $__20.value; $ctx.state = -2; break; case 2: $ctx.state = 12; return $__20.value; default: return $ctx.end(); } }, $__18, this); }), entries: $traceurRuntime.initGeneratorFunction(function $__21() { var $__22, $__23; return $traceurRuntime.createGeneratorInstance(function($ctx) { while (true) switch ($ctx.state) { case 0: $__22 = this.map_.entries()[Symbol.iterator](); $ctx.sent = void 0; $ctx.action = 'next'; $ctx.state = 12; break; case 12: $__23 = $__22[$ctx.action]($ctx.sentIgnoreThrow); $ctx.state = 9; break; case 9: $ctx.state = ($__23.done) ? 3 : 2; break; case 3: $ctx.sent = $__23.value; $ctx.state = -2; break; case 2: $ctx.state = 12; return $__23.value; default: return $ctx.end(); } }, $__21, this); }) }, {}); Object.defineProperty(Set.prototype, Symbol.iterator, { configurable: true, writable: true, value: Set.prototype.values }); Object.defineProperty(Set.prototype, 'keys', { configurable: true, writable: true, value: Set.prototype.values }); function polyfillSet(global) { var $__17 = global, Object = $__17.Object, Symbol = $__17.Symbol; if (!global.Set) global.Set = Set; var setPrototype = global.Set.prototype; if (setPrototype.values) { maybeAddIterator(setPrototype, setPrototype.values, Symbol); maybeAddIterator(Object.getPrototypeOf(new global.Set().values()), function() { return this; }, Symbol); } } registerPolyfill(polyfillSet); return { get Set() { return Set; }, get polyfillSet() { return polyfillSet; } }; }); System.get("[email protected]/src/runtime/polyfills/Set" + ''); System.register("[email protected]/node_modules/rsvp/lib/rsvp/asap", [], function() { "use strict"; var __moduleName = "[email protected]/node_modules/rsvp/lib/rsvp/asap"; var len = 0; function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { scheduleFlush(); } } var $__default = asap; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; function useNextTick() { return function() { process.nextTick(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, {characterData: true}); return function() { node.data = (iterations = ++iterations % 2); }; } function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function() { channel.port2.postMessage(0); }; } function useSetTimeout() { return function() { setTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } var scheduleFlush; if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else { scheduleFlush = useSetTimeout(); } return {get default() { return $__default; }}; }); System.register("[email protected]/src/runtime/polyfills/Promise", [], function() { "use strict"; var __moduleName = "[email protected]/src/runtime/polyfills/Promise"; var async = System.get("[email protected]/node_modules/rsvp/lib/rsvp/asap").default; var registerPolyfill = System.get("[email protected]/src/runtime/polyfills/utils").registerPolyfill; var promiseRaw = {}; function isPromise(x) { return x && typeof x === 'object' && x.status_ !== undefined; } function idResolveHandler(x) { return x; } function idRejectHandler(x) { throw x; } function chain(promise) { var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler; var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler; var deferred = getDeferred(promise.constructor); switch (promise.status_) { case undefined: throw TypeError; case 0: promise.onResolve_.push(onResolve, deferred); promise.onReject_.push(onReject, deferred); break; case +1: promiseEnqueue(promise.value_, [onResolve, deferred]); break; case -1: promiseEnqueue(promise.value_, [onReject, deferred]); break; } return deferred.promise; } function getDeferred(C) { if (this === $Promise) { var promise = promiseInit(new $Promise(promiseRaw)); return { promise: promise, resolve: (function(x) { promiseResolve(promise, x); }), reject: (function(r) { promiseReject(promise, r); }) }; } else { var result = {}; result.promise = new C((function(resolve, reject) { result.resolve = resolve; result.reject = reject; })); return result; } } function promiseSet(promise, status, value, onResolve, onReject) { promise.status_ = status; promise.value_ = value; promise.onResolve_ = onResolve; promise.onReject_ = onReject; return promise; } function promiseInit(promise) { return promiseSet(promise, 0, undefined, [], []); } var Promise = function Promise(resolver) { if (resolver === promiseRaw) return; if (typeof resolver !== 'function') throw new TypeError; var promise = promiseInit(this); try { resolver((function(x) { promiseResolve(promise, x); }), (function(r) { promiseReject(promise, r); })); } catch (e) { promiseReject(promise, e); } }; ($traceurRuntime.createClass)(Promise, { catch: function(onReject) { return this.then(undefined, onReject); }, then: function(onResolve, onReject) { if (typeof onResolve !== 'function') onResolve = idResolveHandler; if (typeof onReject !== 'function') onReject = idRejectHandler; var that = this; var constructor = this.constructor; return chain(this, function(x) { x = promiseCoerce(constructor, x); return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x); }, onReject); } }, { resolve: function(x) { if (this === $Promise) { if (isPromise(x)) { return x; } return promiseSet(new $Promise(promiseRaw), +1, x); } else { return new this(function(resolve, reject) { resolve(x); }); } }, reject: function(r) { if (this === $Promise) { return promiseSet(new $Promise(promiseRaw), -1, r); } else { return new this((function(resolve, reject) { reject(r); })); } }, all: function(values) { var deferred = getDeferred(this); var resolutions = []; try { var count = values.length; if (count === 0) { deferred.resolve(resolutions); } else { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then(function(i, x) { resolutions[i] = x; if (--count === 0) deferred.resolve(resolutions); }.bind(undefined, i), (function(r) { deferred.reject(r); })); } } } catch (e) { deferred.reject(e); } return deferred.promise; }, race: function(values) { var deferred = getDeferred(this); try { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then((function(x) { deferred.resolve(x); }), (function(r) { deferred.reject(r); })); } } catch (e) { deferred.reject(e); } return deferred.promise; } }); var $Promise = Promise; var $PromiseReject = $Promise.reject; function promiseResolve(promise, x) { promiseDone(promise, +1, x, promise.onResolve_); } function promiseReject(promise, r) { promiseDone(promise, -1, r, promise.onReject_); } function promiseDone(promise, status, value, reactions) { if (promise.status_ !== 0) return; promiseEnqueue(value, reactions); promiseSet(promise, status, value); } function promiseEnqueue(value, tasks) { async((function() { for (var i = 0; i < tasks.length; i += 2) { promiseHandle(value, tasks[i], tasks[i + 1]); } })); } function promiseHandle(value, handler, deferred) { try { var result = handler(value); if (result === deferred.promise) throw new TypeError; else if (isPromise(result)) chain(result, deferred.resolve, deferred.reject); else deferred.resolve(result); } catch (e) { try { deferred.reject(e); } catch (e) {} } } var thenableSymbol = '@@thenable'; function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function promiseCoerce(constructor, x) { if (!isPromise(x) && isObject(x)) { var then; try { then = x.then; } catch (r) { var promise = $PromiseReject.call(constructor, r); x[thenableSymbol] = promise; return promise; } if (typeof then === 'function') { var p = x[thenableSymbol]; if (p) { return p; } else { var deferred = getDeferred(constructor); x[thenableSymbol] = deferred.promise; try { then.call(x, deferred.resolve, deferred.reject); } catch (r) { deferred.reject(r); } return deferred.promise; } } } return x; } function polyfillPromise(global) { if (!global.Promise) global.Promise = Promise; } registerPolyfill(polyfillPromise); return { get Promise() { return Promise; }, get polyfillPromise() { return polyfillPromise; } }; }); System.get("[email protected]/src/runtime/polyfills/Promise" + ''); System.register("[email protected]/src/runtime/polyfills/StringIterator", [], function() { "use strict"; var $__29; var __moduleName = "[email protected]/src/runtime/polyfills/StringIterator"; var $__27 = System.get("[email protected]/src/runtime/polyfills/utils"), createIteratorResultObject = $__27.createIteratorResultObject, isObject = $__27.isObject; var $__30 = $traceurRuntime, hasOwnProperty = $__30.hasOwnProperty, toProperty = $__30.toProperty; var iteratedString = Symbol('iteratedString'); var stringIteratorNextIndex = Symbol('stringIteratorNextIndex'); var StringIterator = function StringIterator() {}; ($traceurRuntime.createClass)(StringIterator, ($__29 = {}, Object.defineProperty($__29, "next", { value: function() { var o = this; if (!isObject(o) || !hasOwnProperty(o, iteratedString)) { throw new TypeError('this must be a StringIterator object'); } var s = o[toProperty(iteratedString)]; if (s === undefined) { return createIteratorResultObject(undefined, true); } var position = o[toProperty(stringIteratorNextIndex)]; var len = s.length; if (position >= len) { o[toProperty(iteratedString)] = undefined; return createIteratorResultObject(undefined, true); } var first = s.charCodeAt(position); var resultString; if (first < 0xD800 || first > 0xDBFF || position + 1 === len) { resultString = String.fromCharCode(first); } else { var second = s.charCodeAt(position + 1); if (second < 0xDC00 || second > 0xDFFF) { resultString = String.fromCharCode(first); } else { resultString = String.fromCharCode(first) + String.fromCharCode(second); } } o[toProperty(stringIteratorNextIndex)] = position + resultString.length; return createIteratorResultObject(resultString, false); }, configurable: true, enumerable: true, writable: true }), Object.defineProperty($__29, Symbol.iterator, { value: function() { return this; }, configurable: true, enumerable: true, writable: true }), $__29), {}); function createStringIterator(string) { var s = String(string); var iterator = Object.create(StringIterator.prototype); iterator[toProperty(iteratedString)] = s; iterator[toProperty(stringIteratorNextIndex)] = 0; return iterator; } return {get createStringIterator() { return createStringIterator; }}; }); System.register("[email protected]/src/runtime/polyfills/String", [], function() { "use strict"; var __moduleName = "[email protected]/src/runtime/polyfills/String"; var createStringIterator = System.get("[email protected]/src/runtime/polyfills/StringIterator").createStringIterator; var $__32 = System.get("[email protected]/src/runtime/polyfills/utils"), maybeAddFunctions = $__32.maybeAddFunctions, maybeAddIterator = $__32.maybeAddIterator, registerPolyfill = $__32.registerPolyfill; var $toString = Object.prototype.toString; var $indexOf = String.prototype.indexOf; var $lastIndexOf = String.prototype.lastIndexOf; function startsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) == start; } function endsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var pos = stringLength; if (arguments.length > 1) { var position = arguments[1]; if (position !== undefined) { pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } } } var end = Math.min(Math.max(pos, 0), stringLength); var start = end - searchLength; if (start < 0) { return false; } return $lastIndexOf.call(string, searchString, start) == start; } function contains(search) { if (this == null) { throw TypeError(); } var string = String(this); var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) != -1; } function repeat(count) { if (this == null) { throw TypeError(); } var string = String(this); var n = count ? Number(count) : 0; if (isNaN(n)) { n = 0; } if (n < 0 || n == Infinity) { throw RangeError(); } if (n == 0) { return ''; } var result = ''; while (n--) { result += string; } return result; } function codePointAt(position) { if (this == null) { throw TypeError(); } var string = String(this); var size = string.length; var index = position ? Number(position) : 0; if (isNaN(index)) { index = 0; } if (index < 0 || index >= size) { return undefined; } var first = string.charCodeAt(index); var second; if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) { second = string.charCodeAt(index + 1); if (second >= 0xDC00 && second <= 0xDFFF) { return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return first; } function raw(callsite) { var raw = callsite.raw; var len = raw.length >>> 0; if (len === 0) return ''; var s = ''; var i = 0; while (true) { s += raw[i]; if (i + 1 === len) return s; s += arguments[++i]; } } function fromCodePoint() { var codeUnits = []; var floor = Math.floor; var highSurrogate; var lowSurrogate; var index = -1; var length = arguments.length; if (!length) { return ''; } while (++index < length) { var codePoint = Number(arguments[index]); if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { codeUnits.push(codePoint); } else { codePoint -= 0x10000; highSurrogate = (codePoint >> 10) + 0xD800; lowSurrogate = (codePoint % 0x400) + 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } } return String.fromCharCode.apply(null, codeUnits); } function stringPrototypeIterator() { var o = $traceurRuntime.checkObjectCoercible(this); var s = String(o); return createStringIterator(s); } function polyfillString(global) { var String = global.String; maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]); maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]); maybeAddIterator(String.prototype, stringPrototypeIterator, Symbol); } registerPolyfill(polyfillString); return { get startsWith() { return startsWith; }, get endsWith() { return endsWith; }, get contains() { return contains; }, get repeat() { return repeat; }, get codePointAt() { return codePointAt; }, get raw() { return raw; }, get fromCodePoint() { return fromCodePoint; }, get stringPrototypeIterator() { return stringPrototypeIterator; }, get polyfillString() { return polyfillString; } }; }); System.get("[email protected]/src/runtime/polyfills/String" + ''); System.register("[email protected]/src/runtime/polyfills/ArrayIterator", [], function() { "use strict"; var $__36; var __moduleName = "[email protected]/src/runtime/polyfills/ArrayIterator"; var $__34 = System.get("[email protected]/src/runtime/polyfills/utils"), toObject = $__34.toObject, toUint32 = $__34.toUint32, createIteratorResultObject = $__34.createIteratorResultObject; var ARRAY_ITERATOR_KIND_KEYS = 1; var ARRAY_ITERATOR_KIND_VALUES = 2; var ARRAY_ITERATOR_KIND_ENTRIES = 3; var ArrayIterator = function ArrayIterator() {}; ($traceurRuntime.createClass)(ArrayIterator, ($__36 = {}, Object.defineProperty($__36, "next", { value: function() { var iterator = toObject(this); var array = iterator.iteratorObject_; if (!array) { throw new TypeError('Object is not an ArrayIterator'); } var index = iterator.arrayIteratorNextIndex_; var itemKind = iterator.arrayIterationKind_; var length = toUint32(array.length); if (index >= length) { iterator.arrayIteratorNextIndex_ = Infinity; return createIteratorResultObject(undefined, true); } iterator.arrayIteratorNextIndex_ = index + 1; if (itemKind == ARRAY_ITERATOR_KIND_VALUES) return createIteratorResultObject(array[index], false); if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES) return createIteratorResultObject([index, array[index]], false); return createIteratorResultObject(index, false); }, configurable: true, enumerable: true, writable: true }), Object.defineProperty($__36, Symbol.iterator, { value: function() { return this; }, configurable: true, enumerable: true, writable: true }), $__36), {}); function createArrayIterator(array, kind) { var object = toObject(array); var iterator = new ArrayIterator; iterator.iteratorObject_ = object; iterator.arrayIteratorNextIndex_ = 0; iterator.arrayIterationKind_ = kind; return iterator; } function entries() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES); } function keys() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS); } function values() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES); } return { get entries() { return entries; }, get keys() { return keys; }, get values() { return values; } }; }); System.register("[email protected]/src/runtime/polyfills/Array", [], function() { "use strict"; var __moduleName = "[email protected]/src/runtime/polyfills/Array"; var $__37 = System.get("[email protected]/src/runtime/polyfills/ArrayIterator"), entries = $__37.entries, keys = $__37.keys, values = $__37.values; var $__38 = System.get("[email protected]/src/runtime/polyfills/utils"), checkIterable = $__38.checkIterable, isCallable = $__38.isCallable, isConstructor = $__38.isConstructor, maybeAddFunctions = $__38.maybeAddFunctions, maybeAddIterator = $__38.maybeAddIterator, registerPolyfill = $__38.registerPolyfill, toInteger = $__38.toInteger, toLength = $__38.toLength, toObject = $__38.toObject; function from(arrLike) { var mapFn = arguments[1]; var thisArg = arguments[2]; var C = this; var items = toObject(arrLike); var mapping = mapFn !== undefined; var k = 0; var arr, len; if (mapping && !isCallable(mapFn)) { throw TypeError(); } if (checkIterable(items)) { arr = isConstructor(C) ? new C() : []; for (var $__39 = items[Symbol.iterator](), $__40; !($__40 = $__39.next()).done; ) { var item = $__40.value; { if (mapping) { arr[k] = mapFn.call(thisArg, item, k); } else { arr[k] = item; } k++; } } arr.length = k; return arr; } len = toLength(items.length); arr = isConstructor(C) ? new C(len) : new Array(len); for (; k < len; k++) { if (mapping) { arr[k] = typeof thisArg === 'undefined' ? mapFn(items[k], k) : mapFn.call(thisArg, items[k], k); } else { arr[k] = items[k]; } } arr.length = len; return arr; } function of() { for (var items = [], $__41 = 0; $__41 < arguments.length; $__41++) items[$__41] = arguments[$__41]; var C = this; var len = items.length; var arr = isConstructor(C) ? new C(len) : new Array(len); for (var k = 0; k < len; k++) { arr[k] = items[k]; } arr.length = len; return arr; } function fill(value) { var start = arguments[1] !== (void 0) ? arguments[1] : 0; var end = arguments[2]; var object = toObject(this); var len = toLength(object.length); var fillStart = toInteger(start); var fillEnd = end !== undefined ? toInteger(end) : len; fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len); fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len); while (fillStart < fillEnd) { object[fillStart] = value; fillStart++; } return object; } function find(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg); } function findIndex(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg, true); } function findHelper(self, predicate) { var thisArg = arguments[2]; var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false; var object = toObject(self); var len = toLength(object.length); if (!isCallable(predicate)) { throw TypeError(); } for (var i = 0; i < len; i++) { if (i in object) { var value = object[i]; if (predicate.call(thisArg, value, i, object)) { return returnIndex ? i : value; } } } return returnIndex ? -1 : undefined; } function polyfillArray(global) { var $__42 = global, Array = $__42.Array, Object = $__42.Object, Symbol = $__42.Symbol; maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]); maybeAddFunctions(Array, ['from', from, 'of', of]); maybeAddIterator(Array.prototype, values, Symbol); maybeAddIterator(Object.getPrototypeOf([].values()), function() { return this; }, Symbol); } registerPolyfill(polyfillArray); return { get from() { return from; }, get of() { return of; }, get fill() { return fill; }, get find() { return find; }, get findIndex() { return findIndex; }, get polyfillArray() { return polyfillArray; } }; }); System.get("[email protected]/src/runtime/polyfills/Array" + ''); System.register("[email protected]/src/runtime/polyfills/Object", [], function() { "use strict"; var __moduleName = "[email protected]/src/runtime/polyfills/Object"; var $__43 = System.get("[email protected]/src/runtime/polyfills/utils"), maybeAddFunctions = $__43.maybeAddFunctions, registerPolyfill = $__43.registerPolyfill; var $__44 = $traceurRuntime, defineProperty = $__44.defineProperty, getOwnPropertyDescriptor = $__44.getOwnPropertyDescriptor, getOwnPropertyNames = $__44.getOwnPropertyNames, keys = $__44.keys, privateNames = $__44.privateNames; function is(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; return left !== left && right !== right; } function assign(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; var props = keys(source); var p, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; target[name] = source[name]; } } return target; } function mixin(target, source) { var props = getOwnPropertyNames(source); var p, descriptor, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; descriptor = getOwnPropertyDescriptor(source, props[p]); defineProperty(target, props[p], descriptor); } return target; } function polyfillObject(global) { var Object = global.Object; maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]); } registerPolyfill(polyfillObject); return { get is() { return is; }, get assign() { return assign; }, get mixin() { return mixin; }, get polyfillObject() { return polyfillObject; } }; }); System.get("[email protected]/src/runtime/polyfills/Object" + ''); System.register("[email protected]/src/runtime/polyfills/Number", [], function() { "use strict"; var __moduleName = "[email protected]/src/runtime/polyfills/Number"; var $__46 = System.get("[email protected]/src/runtime/polyfills/utils"), isNumber = $__46.isNumber, maybeAddConsts = $__46.maybeAddConsts, maybeAddFunctions = $__46.maybeAddFunctions, registerPolyfill = $__46.registerPolyfill, toInteger = $__46.toInteger; var $abs = Math.abs; var $isFinite = isFinite; var $isNaN = isNaN; var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; var MIN_SAFE_INTEGER = -Math.pow(2, 53) + 1; var EPSILON = Math.pow(2, -52); function NumberIsFinite(number) { return isNumber(number) && $isFinite(number); } ; function isInteger(number) { return NumberIsFinite(number) && toInteger(number) === number; } function NumberIsNaN(number) { return isNumber(number) && $isNaN(number); } ; function isSafeInteger(number) { if (NumberIsFinite(number)) { var integral = toInteger(number); if (integral === number) return $abs(integral) <= MAX_SAFE_INTEGER; } return false; } function polyfillNumber(global) { var Number = global.Number; maybeAddConsts(Number, ['MAX_SAFE_INTEGER', MAX_SAFE_INTEGER, 'MIN_SAFE_INTEGER', MIN_SAFE_INTEGER, 'EPSILON', EPSILON]); maybeAddFunctions(Number, ['isFinite', NumberIsFinite, 'isInteger', isInteger, 'isNaN', NumberIsNaN, 'isSafeInteger', isSafeInteger]); } registerPolyfill(polyfillNumber); return { get MAX_SAFE_INTEGER() { return MAX_SAFE_INTEGER; }, get MIN_SAFE_INTEGER() { return MIN_SAFE_INTEGER; }, get EPSILON() { return EPSILON; }, get isFinite() { return NumberIsFinite; }, get isInteger() { return isInteger; }, get isNaN() { return NumberIsNaN; }, get isSafeInteger() { return isSafeInteger; }, get polyfillNumber() { return polyfillNumber; } }; }); System.get("[email protected]/src/runtime/polyfills/Number" + ''); System.register("[email protected]/src/runtime/polyfills/polyfills", [], function() { "use strict"; var __moduleName = "[email protected]/src/runtime/polyfills/polyfills"; var polyfillAll = System.get("[email protected]/src/runtime/polyfills/utils").polyfillAll; polyfillAll(this); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); polyfillAll(global); }; return {}; }); System.get("[email protected]/src/runtime/polyfills/polyfills" + ''); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":2}],4:[function(require,module,exports){ /** * Copyright 2012 Craig Campbell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.1.2 * @url craig.is/killing/mice */ /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }, /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }, /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }, /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc' }, /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ _REVERSE_MAP, /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ _callbacks = {}, /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ _direct_map = {}, /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ _sequence_levels = {}, /** * variable to store the setTimeout call * * @type {null|number} */ _reset_timer, /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ _ignore_next_keyup = false, /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ _inside_sequence = false; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { _MAP[i + 96] = i; } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { return object.addEventListener(type, callback, false); } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { // for keypress events we should return the character as is if (e.type == 'keypress') { return String.fromCharCode(e.which); } // for non keypress events the special maps are needed if (_MAP[e.which]) { return _MAP[e.which]; } if (_KEYCODE_MAP[e.which]) { return _KEYCODE_MAP[e.which]; } // if it is not in the special map return String.fromCharCode(e.which).toLowerCase(); } /** * should we stop this event before firing off callbacks * * @param {Event} e * @return {boolean} */ function _stop(e) { var element = e.target || e.srcElement, tag_name = element.tagName; // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true'); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * resets all sequence counters except for the ones passed in * * @param {Object} do_not_reset * @returns void */ function _resetSequences(do_not_reset) { do_not_reset = do_not_reset || {}; var active_sequences = false, key; for (key in _sequence_levels) { if (do_not_reset[key]) { active_sequences = true; continue; } _sequence_levels[key] = 0; } if (!active_sequences) { _inside_sequence = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {string} action * @param {boolean=} remove - should we remove any matches * @param {string=} combination * @returns {Array} */ function _getMatches(character, modifiers, action, remove, combination) { var i, callback, matches = []; // if there are no events related to this keycode if (!_callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < _callbacks[character].length; ++i) { callback = _callbacks[character][i]; // if this is a sequence but it is not at the right level // then move onto the next match if (callback.seq && _sequence_levels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event that means that we need to only // look at the character, otherwise check the modifiers as // well if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) { // remove is used so if you change your mind and call bind a // second time with a new function the first one is overwritten if (remove && callback.combo == combination) { _callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e) { if (callback(e) === false) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.returnValue = false; e.cancelBubble = true; } } /** * handles a character key event * * @param {string} character * @param {Event} e * @returns void */ function _handleCharacter(character, e) { // if this event should not happen stop here if (_stop(e)) { return; } var callbacks = _getMatches(character, _eventModifiers(e), e.type), i, do_not_reset = {}, processed_sequence_callback = false; // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { processed_sequence_callback = true; // keep a list of which sequences were matches for later do_not_reset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processed_sequence_callback && !_inside_sequence) { _fireCallback(callbacks[i].callback, e); } } // if you are inside of a sequence and the key you are pressing // is not a modifier key then we should reset all sequences // that were not matched by this key event if (e.type == _inside_sequence && !_isModifier(character)) { _resetSequences(do_not_reset); } } /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKey(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion e.which = typeof e.which == "number" ? e.which : e.keyCode; var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } if (e.type == 'keyup' && _ignore_next_keyup == character) { _ignore_next_keyup = false; return; } _handleCharacter(character, e); } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_reset_timer); _reset_timer = setTimeout(_resetSequences, 1000); } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequence_levels[combo] = 0; // if there is no action pick the best one for the first key // in the sequence if (!action) { action = _pickBestAction(keys[0], []); } /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {Event} e * @returns void */ var _increaseSequence = function(e) { _inside_sequence = action; ++_sequence_levels[combo]; _resetSequenceTimer(); }, /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ _callbackAndReset = function(e) { _fireCallback(callback, e); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignore_next_keyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); }, i; // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences for (i = 0; i < keys.length; ++i) { _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i); } } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequence_name - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequence_name, level) { // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '), i, key, keys, modifiers = []; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { return _bindSequence(combination, sequence, callback, action); } // take the keys from this pattern and figure out what the actual // pattern is all about keys = combination === '+' ? ['+'] : combination.split('+'); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); // make sure to initialize array if this is the first time // a callback is added for this key if (!_callbacks[key]) { _callbacks[key] = []; } // remove an existing match if there is one _getMatches(key, modifiers, action, !sequence_name, combination); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first _callbacks[key][sequence_name ? 'unshift' : 'push']({ callback: callback, modifiers: modifiers, action: action, seq: sequence_name, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ function _bindMultiple(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } } // start! _addEvent(document, 'keypress', _handleKey); _addEvent(document, 'keydown', _handleKey); _addEvent(document, 'keyup', _handleKey); var mousetrap = { /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * a comma separated list of keys, an array of keys, or * a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ bind: function(keys, callback, action) { _bindMultiple(keys instanceof Array ? keys : [keys], callback, action); _direct_map[keys + ':' + action] = callback; return this; }, /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _direct_map dict. * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * @param {string|Array} keys * @param {string} action * @returns void */ unbind: function(keys, action) { if (_direct_map[keys + ':' + action]) { delete _direct_map[keys + ':' + action]; this.bind(keys, function() {}, action); } return this; }, /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ trigger: function(keys, action) { _direct_map[keys + ':' + action](); return this; }, /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ reset: function() { _callbacks = {}; _direct_map = {}; return this; } }; module.exports = mousetrap; },{}],5:[function(require,module,exports){ (function( factory ) { if (typeof define !== 'undefined' && define.amd) { define([], factory); } else if (typeof module !== 'undefined' && module.exports) { module.exports = factory(); } else { window.scrollMonitor = factory(); } })(function() { var scrollTop = function() { return window.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop; }; var exports = {}; var watchers = []; var VISIBILITYCHANGE = 'visibilityChange'; var ENTERVIEWPORT = 'enterViewport'; var FULLYENTERVIEWPORT = 'fullyEnterViewport'; var EXITVIEWPORT = 'exitViewport'; var PARTIALLYEXITVIEWPORT = 'partiallyExitViewport'; var LOCATIONCHANGE = 'locationChange'; var STATECHANGE = 'stateChange'; var eventTypes = [ VISIBILITYCHANGE, ENTERVIEWPORT, FULLYENTERVIEWPORT, EXITVIEWPORT, PARTIALLYEXITVIEWPORT, LOCATIONCHANGE, STATECHANGE ]; var defaultOffsets = {top: 0, bottom: 0}; var getViewportHeight = function() { return window.innerHeight || document.documentElement.clientHeight; }; var getDocumentHeight = function() { // jQuery approach // whichever is greatest return Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight ); }; exports.viewportTop = null; exports.viewportBottom = null; exports.documentHeight = null; exports.viewportHeight = getViewportHeight(); var previousDocumentHeight; var latestEvent; var calculateViewportI; function calculateViewport() { exports.viewportTop = scrollTop(); exports.viewportBottom = exports.viewportTop + exports.viewportHeight; exports.documentHeight = getDocumentHeight(); if (exports.documentHeight !== previousDocumentHeight) { calculateViewportI = watchers.length; while( calculateViewportI-- ) { watchers[calculateViewportI].recalculateLocation(); } previousDocumentHeight = exports.documentHeight; } } function recalculateWatchLocationsAndTrigger() { exports.viewportHeight = getViewportHeight(); calculateViewport(); updateAndTriggerWatchers(); } var recalculateAndTriggerTimer; function debouncedRecalcuateAndTrigger() { clearTimeout(recalculateAndTriggerTimer); recalculateAndTriggerTimer = setTimeout( recalculateWatchLocationsAndTrigger, 100 ); } var updateAndTriggerWatchersI; function updateAndTriggerWatchers() { // update all watchers then trigger the events so one can rely on another being up to date. updateAndTriggerWatchersI = watchers.length; while( updateAndTriggerWatchersI-- ) { watchers[updateAndTriggerWatchersI].update(); } updateAndTriggerWatchersI = watchers.length; while( updateAndTriggerWatchersI-- ) { watchers[updateAndTriggerWatchersI].triggerCallbacks(); } } function ElementWatcher( watchItem, offsets ) { var self = this; this.watchItem = watchItem; if (!offsets) { this.offsets = defaultOffsets; } else if (offsets === +offsets) { this.offsets = {top: offsets, bottom: offsets}; } else { this.offsets = { top: offsets.top || defaultOffsets.top, bottom: offsets.bottom || defaultOffsets.bottom }; } this.callbacks = {}; // {callback: function, isOne: true } for (var i = 0, j = eventTypes.length; i < j; i++) { self.callbacks[eventTypes[i]] = []; } this.locked = false; var wasInViewport; var wasFullyInViewport; var wasAboveViewport; var wasBelowViewport; var listenerToTriggerListI; var listener; function triggerCallbackArray( listeners ) { if (listeners.length === 0) { return; } listenerToTriggerListI = listeners.length; while( listenerToTriggerListI-- ) { listener = listeners[listenerToTriggerListI]; listener.callback.call( self, latestEvent ); if (listener.isOne) { listeners.splice(listenerToTriggerListI, 1); } } } this.triggerCallbacks = function triggerCallbacks() { if (this.isInViewport && !wasInViewport) { triggerCallbackArray( this.callbacks[ENTERVIEWPORT] ); } if (this.isFullyInViewport && !wasFullyInViewport) { triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] ); } if (this.isAboveViewport !== wasAboveViewport && this.isBelowViewport !== wasBelowViewport) { triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] ); // if you skip completely past this element if (!wasFullyInViewport && !this.isFullyInViewport) { triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] ); triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] ); } if (!wasInViewport && !this.isInViewport) { triggerCallbackArray( this.callbacks[ENTERVIEWPORT] ); triggerCallbackArray( this.callbacks[EXITVIEWPORT] ); } } if (!this.isFullyInViewport && wasFullyInViewport) { triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] ); } if (!this.isInViewport && wasInViewport) { triggerCallbackArray( this.callbacks[EXITVIEWPORT] ); } if (this.isInViewport !== wasInViewport) { triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] ); } switch( true ) { case wasInViewport !== this.isInViewport: case wasFullyInViewport !== this.isFullyInViewport: case wasAboveViewport !== this.isAboveViewport: case wasBelowViewport !== this.isBelowViewport: triggerCallbackArray( this.callbacks[STATECHANGE] ); } wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; }; this.recalculateLocation = function() { if (this.locked) { return; } var previousTop = this.top; var previousBottom = this.bottom; if (this.watchItem.nodeName) { // a dom element var cachedDisplay = this.watchItem.style.display; if (cachedDisplay === 'none') { this.watchItem.style.display = ''; } var boundingRect = this.watchItem.getBoundingClientRect(); this.top = boundingRect.top + exports.viewportTop; this.bottom = boundingRect.bottom + exports.viewportTop; if (cachedDisplay === 'none') { this.watchItem.style.display = cachedDisplay; } } else if (this.watchItem === +this.watchItem) { // number if (this.watchItem > 0) { this.top = this.bottom = this.watchItem; } else { this.top = this.bottom = exports.documentHeight - this.watchItem; } } else { // an object with a top and bottom property this.top = this.watchItem.top; this.bottom = this.watchItem.bottom; } this.top -= this.offsets.top; this.bottom += this.offsets.bottom; this.height = this.bottom - this.top; if ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) { triggerCallbackArray( this.callbacks[LOCATIONCHANGE] ); } }; this.recalculateLocation(); this.update(); wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; } ElementWatcher.prototype = { on: function( event, callback, isOne ) { // trigger the event if it applies to the element right now. switch( true ) { case event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport: case event === ENTERVIEWPORT && this.isInViewport: case event === FULLYENTERVIEWPORT && this.isFullyInViewport: case event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport: case event === PARTIALLYEXITVIEWPORT && this.isAboveViewport: callback.call( this, latestEvent ); if (isOne) { return; } } if (this.callbacks[event]) { this.callbacks[event].push({callback: callback, isOne: isOne||false}); } else { throw new Error('Tried to add a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', ')); } }, off: function( event, callback ) { if (this.callbacks[event]) { for (var i = 0, item; item = this.callbacks[event][i]; i++) { if (item.callback === callback) { this.callbacks[event].splice(i, 1); break; } } } else { throw new Error('Tried to remove a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', ')); } }, one: function( event, callback ) { this.on( event, callback, true); }, recalculateSize: function() { this.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom; this.bottom = this.top + this.height; }, update: function() { this.isAboveViewport = this.top < exports.viewportTop; this.isBelowViewport = this.bottom > exports.viewportBottom; this.isInViewport = (this.top <= exports.viewportBottom && this.bottom >= exports.viewportTop); this.isFullyInViewport = (this.top >= exports.viewportTop && this.bottom <= exports.viewportBottom) || (this.isAboveViewport && this.isBelowViewport); }, destroy: function() { var index = watchers.indexOf(this), self = this; watchers.splice(index, 1); for (var i = 0, j = eventTypes.length; i < j; i++) { self.callbacks[eventTypes[i]].length = 0; } }, // prevent recalculating the element location lock: function() { this.locked = true; }, unlock: function() { this.locked = false; } }; var eventHandlerFactory = function (type) { return function( callback, isOne ) { this.on.call(this, type, callback, isOne); }; }; for (var i = 0, j = eventTypes.length; i < j; i++) { var type = eventTypes[i]; ElementWatcher.prototype[type] = eventHandlerFactory(type); } try { calculateViewport(); } catch (e) { try { window.$(calculateViewport); } catch (e) { throw new Error('If you must put scrollMonitor in the <head>, you must use jQuery.'); } } function scrollMonitorListener(event) { latestEvent = event; calculateViewport(); updateAndTriggerWatchers(); } if (window.addEventListener) { window.addEventListener('scroll', scrollMonitorListener); window.addEventListener('resize', debouncedRecalcuateAndTrigger); } else { // Old IE support window.attachEvent('onscroll', scrollMonitorListener); window.attachEvent('onresize', debouncedRecalcuateAndTrigger); } exports.beget = exports.create = function( element, offsets ) { if (typeof element === 'string') { element = document.querySelector(element); } else if (element && element.length > 0) { element = element[0]; } var watcher = new ElementWatcher( element, offsets ); watchers.push(watcher); watcher.update(); return watcher; }; exports.update = function() { latestEvent = null; calculateViewport(); updateAndTriggerWatchers(); }; exports.recalculateLocations = function() { exports.documentHeight = 0; exports.update(); }; return exports; }); },{}],6:[function(require,module,exports){ module.exports={ "name": "clappr", "version": "0.0.65", "description": "An extensible media player for the web", "main": "dist/clappr.min.js", "scripts": { "test": "./node_modules/.bin/gulp release && ./node_modules/.bin/karma start --single-run --browsers Firefox" }, "repository": { "type": "git", "url": "[email protected]:globocom/clappr.git" }, "author": "Globo.com", "license": "ISC", "bugs": { "url": "https://github.com/globocom/clappr/issues" }, "browser": { "zepto": "clappr-zepto" }, "homepage": "https://github.com/globocom/clappr", "devDependencies": { "browserify": "^6.3.2", "browserify-shim": "^3.8.0", "chai": "latest", "compass-mixins": "latest", "dotenv": "^0.4.0", "es6ify": "~1.4.0", "exorcist": "^0.1.6", "express": "^4.6.1", "express-alias": "latest", "glob": "^4.0.2", "gulp": "^3.8.1", "clappr-zepto": "latest", "gulp-compressor": "^0.1.0", "gulp-jshint": "latest", "gulp-livereload": "^2.1.0", "gulp-minify-css": "~0.3.5", "gulp-rename": "^1.2.0", "gulp-sass": "1.0.0", "gulp-streamify": "0.0.5", "gulp-uglify": "^1.0.1", "gulp-util": "latest", "karma": "^0.12.17", "karma-browserify": "^1.0.0", "karma-chai": "^0.1.0", "karma-chrome-launcher": "^0.1.4", "karma-cli": "0.0.4", "karma-firefox-launcher": "^0.1.3", "karma-jasmine": "^0.2.2", "karma-jquery": "^0.1.0", "karma-mocha": "^0.1.4", "karma-safari-launcher": "^0.1.1", "karma-sinon": "^1.0.3", "karma-sinon-chai": "^0.2.0", "mkdirp": "^0.5.0", "s3": "^4.1.1", "scp": "latest", "sinon": "^1.10.2", "traceur": "0.0.72", "vinyl-source-stream": "^1.0.0", "vinyl-transform": "0.0.1", "watchify": "^2.0.0", "yargs": "latest" }, "dependencies": { "underscore": "1.7.0", "mousetrap": "0.0.1", "scrollmonitor": "^1.0.8" } } },{}],7:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var Log = require('../plugins/log').getInstance(); var slice = Array.prototype.slice; var Events = function Events() {}; ($traceurRuntime.createClass)(Events, { on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({ callback: callback, context: context, ctx: context || this }); return this; }, once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = void 0; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; events = this._events[name]; if (events) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, trigger: function(name) { var klass = arguments[arguments.length - 1]; Log.info(klass, name); if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, stopListening: function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; if (!callback && typeof name === 'object') callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; obj.off(name, callback, this); if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; } }, {}); var eventSplitter = /\s+/; var eventsApi = function(obj, action, name, rest) { if (!name) return true; if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; var listenMethods = { listenTo: 'on', listenToOnce: 'once' }; _.each(listenMethods, function(implementation, method) { Events.prototype[method] = function(obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); var id = obj._listenId || (obj._listenId = _.uniqueId('l')); listeningTo[id] = obj; if (!callback && typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); Events.PLAYBACK_PROGRESS = 'playback:progress'; Events.PLAYBACK_TIMEUPDATE = 'playback:timeupdate'; Events.PLAYBACK_READY = 'playback:ready'; Events.PLAYBACK_BUFFERING = 'playback:buffering'; Events.PLAYBACK_BUFFERFULL = 'playback:bufferfull'; Events.PLAYBACK_SETTINGSUPDATE = 'playback:settingsupdate'; Events.PLAYBACK_LOADEDMETADATA = 'playback:loadedmetadata'; Events.PLAYBACK_HIGHDEFINITIONUPDATE = 'playback:highdefinitionupdate'; Events.PLAYBACK_BITRATE = 'playback:bitrate'; Events.PLAYBACK_PLAYBACKSTATE = 'playback:playbackstate'; Events.PLAYBACK_DVR = 'playback:dvr'; Events.PLAYBACK_MEDIACONTROL_DISABLE = 'playback:mediacontrol:disable'; Events.PLAYBACK_MEDIACONTROL_ENABLE = 'playback:mediacontrol:enable'; Events.PLAYBACK_ENDED = 'playback:ended'; Events.PLAYBACK_PLAY = 'playback:play'; Events.PLAYBACK_ERROR = 'playback:error'; Events.CONTAINER_PLAYBACKSTATE = 'container:playbackstate'; Events.CONTAINER_PLAYBACKDVRSTATECHANGED = 'container:dvr'; Events.CONTAINER_BITRATE = 'container:bitrate'; Events.CONTAINER_STATS_REPORT = 'container:stats:report'; Events.CONTAINER_DESTROYED = 'container:destroyed'; Events.CONTAINER_READY = 'container:ready'; Events.CONTAINER_ERROR = 'container:error'; Events.CONTAINER_LOADEDMETADATA = 'container:loadedmetadata'; Events.CONTAINER_TIMEUPDATE = 'container:timeupdate'; Events.CONTAINER_PROGRESS = 'container:progress'; Events.CONTAINER_PLAY = 'container:play'; Events.CONTAINER_STOP = 'container:stop'; Events.CONTAINER_PAUSE = 'container:pause'; Events.CONTAINER_ENDED = 'container:ended'; Events.CONTAINER_CLICK = 'container:click'; Events.CONTAINER_SEEK = 'container:seek'; Events.CONTAINER_VOLUME = 'container:volume'; Events.CONTAINER_FULLSCREEN = 'container:fullscreen'; Events.CONTAINER_STATE_BUFFERING = 'container:state:buffering'; Events.CONTAINER_STATE_BUFFERFULL = 'container:state:bufferfull'; Events.CONTAINER_SETTINGSUPDATE = 'container:settingsupdate'; Events.CONTAINER_HIGHDEFINITIONUPDATE = 'container:highdefinitionupdate'; Events.CONTAINER_MEDIACONTROL_DISABLE = 'container:mediacontrol:disable'; Events.CONTAINER_MEDIACONTROL_ENABLE = 'container:mediacontrol:enable'; module.exports = Events; },{"../plugins/log":39,"underscore":"underscore"}],8:[function(require,module,exports){ "use strict"; var _ = require('underscore'); module.exports = { 'media_control': _.template('<div class="media-control-background" data-background></div><div class="media-control-layer" data-controls><% var renderBar=function(name) { %><div class="bar-container" data-<%= name %>><div class="bar-background" data-<%= name %>><div class="bar-fill-1" data-<%= name %>></div><div class="bar-fill-2" data-<%= name %>></div><div class="bar-hover" data-<%= name %>></div></div><div class="bar-scrubber" data-<%= name %>><div class="bar-scrubber-icon" data-<%= name %>></div></div></div><% }; %><% var renderSegmentedBar=function(name, segments) { segments=segments || 10; %><div class="bar-container" data-<%= name %>><% for (var i = 0; i < segments; i++) { %><div class="segmented-bar-element" data-<%= name %>></div><% } %></div><% }; %><% var renderDrawer=function(name, renderContent) { %><div class="drawer-container" data-<%= name %>><div class="drawer-icon-container" data-<%= name %>><div class="drawer-icon media-control-icon" data-<%= name %>></div><span class="drawer-text" data-<%= name %>></span></div><% renderContent(name); %></div><% }; %><% var renderIndicator=function(name) { %><div class="media-control-indicator" data-<%= name %>></div><% }; %><% var renderButton=function(name) { %><button class="media-control-button media-control-icon" data-<%= name %>></button><% }; %><% var templates={ bar: renderBar, segmentedBar: renderSegmentedBar, }; var render=function(settingsList) { _.each(settingsList, function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, settings.volumeBarTemplate ? templates[settings.volumeBarTemplate] : function(name) { return renderSegmentedBar(name); }); } else if (setting === "duration" || setting=== "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %><% if (settings.default && settings.default.length) { %><div class="media-control-center-panel" data-media-control><% render(settings.default); %></div><% } %><% if (settings.left && settings.left.length) { %><div class="media-control-left-panel" data-media-control><% render(settings.left); %></div><% } %><% if (settings.right && settings.right.length) { %><div class="media-control-right-panel" data-media-control><% render(settings.right); %></div><% } %></div>'), 'seek_time': _.template('<span data-seek-time></span>'), 'flash': _.template('<param name="movie" value="<%= swfPath %>"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" disabled tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'), 'hls': _.template('<param name="movie" value="<%= swfPath %>?inline=1"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" tabindex="1" enablecontextmenu="false" allowScriptAccess="always" quality="autohigh" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'), 'html5_video': _.template('<source src="<%=src%>" type="<%=type%>">'), 'no_op': _.template('<p data-no-op-msg>Something went wrong :(</p>'), 'background_button': _.template('<div class="background-button-wrapper" data-background-button><button class="background-button-icon" data-background-button></button></div>'), 'dvr_controls': _.template('<div class="live-info">LIVE</div><button class="live-button">BACK TO LIVE</button>'), 'poster': _.template('<div class="play-wrapper" data-poster><span class="poster-icon play" data-poster/></div>'), 'spinner_three_bounce': _.template('<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>'), 'watermark': _.template('<div data-watermark data-watermark-<%=position %>><img src="<%= imageUrl %>"></div>'), CSS: { 'container': '.container[data-container]{position:absolute;background-color:#000;height:100%;width:100%}.container[data-container].pointer-enabled{cursor:pointer}', 'core': '[data-player]{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0);position:relative;margin:0;padding:0;border:0;height:594px;width:1055px;font-style:normal;font-weight:400;text-align:center;overflow:hidden;font-size:100%;font-family:"lucida grande",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] a,[data-player] abbr,[data-player] acronym,[data-player] address,[data-player] applet,[data-player] article,[data-player] aside,[data-player] audio,[data-player] b,[data-player] big,[data-player] blockquote,[data-player] canvas,[data-player] caption,[data-player] center,[data-player] cite,[data-player] code,[data-player] dd,[data-player] del,[data-player] details,[data-player] dfn,[data-player] div,[data-player] dl,[data-player] dt,[data-player] em,[data-player] embed,[data-player] fieldset,[data-player] figcaption,[data-player] figure,[data-player] footer,[data-player] form,[data-player] h1,[data-player] h2,[data-player] h3,[data-player] h4,[data-player] h5,[data-player] h6,[data-player] header,[data-player] hgroup,[data-player] i,[data-player] iframe,[data-player] img,[data-player] ins,[data-player] kbd,[data-player] label,[data-player] legend,[data-player] li,[data-player] mark,[data-player] menu,[data-player] nav,[data-player] object,[data-player] ol,[data-player] output,[data-player] p,[data-player] pre,[data-player] q,[data-player] ruby,[data-player] s,[data-player] samp,[data-player] section,[data-player] small,[data-player] span,[data-player] strike,[data-player] strong,[data-player] sub,[data-player] summary,[data-player] sup,[data-player] table,[data-player] tbody,[data-player] td,[data-player] tfoot,[data-player] th,[data-player] thead,[data-player] time,[data-player] tr,[data-player] tt,[data-player] u,[data-player] ul,[data-player] var,[data-player] video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] table{border-collapse:collapse;border-spacing:0}[data-player] caption,[data-player] td,[data-player] th{text-align:left;font-weight:400;vertical-align:middle}[data-player] blockquote,[data-player] q{quotes:none}[data-player] blockquote:after,[data-player] blockquote:before,[data-player] q:after,[data-player] q:before{content:"";content:none}[data-player] a img{border:none}[data-player] *{max-width:initial;box-sizing:inherit;float:initial}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}[data-player] .clappr-style{display:none!important}@media screen{[data-player]{opacity:.99}}', 'media_control': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.media-control-notransition{-webkit-transition:none!important;-webkit-transition-delay:0s;-moz-transition:none!important;-o-transition:none!important;transition:none!important}.media-control[data-media-control]{position:absolute;width:100%;height:100%;z-index:9999;pointer-events:none}.media-control[data-media-control].dragging{pointer-events:auto;cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control].dragging *{cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control] .media-control-background[data-background]{position:absolute;height:40%;width:100%;bottom:0;background-image:-owg(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-webkit(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-moz(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-o(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9));-webkit-transition:opacity .6s;-webkit-transition-delay:ease-out;-moz-transition:opacity .6s ease-out;-o-transition:opacity .6s ease-out;transition:opacity .6s ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;opacity:.5;vertical-align:middle;text-align:left;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.75;text-shadow:rgba(255,255,255,.8) 0 0 5px}.media-control[data-media-control].media-control-hide .media-control-background[data-background]{opacity:0}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls]{bottom:-50px}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:absolute;bottom:7px;width:100%;height:32px;vertical-align:middle;pointer-events:auto;-webkit-transition:bottom .4s;-webkit-transition-delay:ease-out;-moz-transition:bottom .4s ease-out;-o-transition:bottom .4s ease-out;transition:bottom .4s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 6px;padding:0;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:"\\e006"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen].shrink:before{content:"\\e007"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:"\\e008"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled:hover{opacity:1;text-shadow:none}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:10px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{margin-left:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]{color:rgba(255,255,255,.5);margin-right:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:"|";margin:0 3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:25px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:1px;position:relative;top:12px;background-color:#666}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#c2c2c2;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#005aff;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0;position:absolute;top:-3px;width:5px;height:7px;background-color:rgba(255,255,255,.5);-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled{cursor:default}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:2px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:6px;top:6px;width:8px;height:8px;border-radius:10px;box-shadow:0 0 0 6px rgba(255,255,255,.2);background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;height:32px;cursor:pointer;margin:0 6px;box-sizing:border-box}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{float:left;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;box-sizing:content-box;width:16px;height:32px;margin-right:6px;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:hover{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:"\\e004"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted{opacity:.5}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:hover{opacity:.7}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:"\\e005"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{float:left;position:relative;top:6px;width:42px;height:18px;padding:3px 0;overflow:hidden;-webkit-transition:width .2s;-webkit-transition-delay:ease-out;-moz-transition:width .2s ease-out;-o-transition:width .2s ease-out;transition:width .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]{float:left;width:4px;padding-left:2px;height:12px;opacity:.5;-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;-webkit-transition:-webkit-transform .2s;-webkit-transition-delay:ease-out;-moz-transition:-moz-transform .2s ease-out;-o-transition:-o-transform .2s ease-out;transition:transform .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume].fill{-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:nth-of-type(1){padding-left:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:hover{-webkit-transform:scaleY(1.5);-moz-transform:scaleY(1.5);-ms-transform:scaleY(1.5);-o-transform:scaleY(1.5);transform:scaleY(1.5)}.media-control[data-media-control].w320 .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{height:12px;top:9px;padding:0;width:0}', 'seek_time': '.seek-time[data-seek-time]{position:absolute;width:auto;height:20px;line-height:20px;bottom:55px;background-color:rgba(2,2,2,.5);z-index:9999;-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.seek-time[data-seek-time].hidden[data-seek-time]{opacity:0}.seek-time[data-seek-time] span[data-seek-time]{position:relative;color:#fff;font-size:10px;padding-left:7px;padding-right:7px}', 'flash': '[data-flash]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}', 'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none;top:0}', 'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}', 'no_op': '[data-no-op]{z-index:1000;position:absolute;background-color:#222;height:100%;width:100%}[data-no-op] p[data-no-op-msg]{position:relative;font-size:25px;top:50%;color:#fff}', 'background_button': '.background-button[data-background-button]{font-family:Player;position:absolute;height:100%;width:100%;background-color:rgba(0,0,0,.2);pointer-events:none;-webkit-transition:all .4s;-webkit-transition-delay:ease-out;-moz-transition:all .4s ease-out;-o-transition:all .4s ease-out;transition:all .4s ease-out}.background-button[data-background-button].hide{background-color:transparent}.background-button[data-background-button].hide .background-button-wrapper[data-background-button]{opacity:0}.background-button[data-background-button] .background-button-wrapper[data-background-button]{position:absolute;overflow:hidden;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]{cursor:pointer;pointer-events:auto;font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;border:0;outline:0;background-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playing:before{content:"\\e002"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].notplaying:before{content:"\\e001"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.playing:before{content:"\\e003"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.notplaying:before{content:"\\e001"}.media-control.media-control-hide[data-media-control] .background-button[data-background-button]{opacity:0}', 'dvr_controls': '@import url(http://fonts.googleapis.com/css?family=Roboto);.dvr-controls[data-dvr-controls]{display:inline-block;float:left;color:#fff;line-height:32px;font-size:10px;font-weight:700;margin-left:6px}.dvr-controls[data-dvr-controls] .live-info{cursor:default;font-family:Roboto,"Open Sans",Arial,sans-serif}.dvr-controls[data-dvr-controls] .live-info:before{content:"";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#ff0101}.dvr-controls[data-dvr-controls] .live-info.disabled{opacity:.3}.dvr-controls[data-dvr-controls] .live-info.disabled:before{background-color:#fff}.dvr-controls[data-dvr-controls] .live-button{cursor:pointer;outline:0;display:none;border:0;color:#fff;background-color:transparent;height:32px;padding:0;opacity:.7;font-family:Roboto,"Open Sans",Arial,sans-serif;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.dvr-controls[data-dvr-controls] .live-button:before{content:"";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#fff}.dvr-controls[data-dvr-controls] .live-button:hover{opacity:1;text-shadow:rgba(255,255,255,.75) 0 0 5px}.dvr .dvr-controls[data-dvr-controls] .live-info{display:none}.dvr .dvr-controls[data-dvr-controls] .live-button{display:block}.dvr.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#005aff}.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#ff0101}.seek-time[data-seek-time] span[data-duration]{position:relative;color:rgba(255,255,255,.5);font-size:10px;padding-right:7px}.seek-time[data-seek-time] span[data-duration]:before{content:"|";margin-right:7px}', 'poster': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:opacity text-shadow;-webkit-transition-delay:.1s;-moz-transition:opacity text-shadow .1s;-o-transition:opacity text-shadow .1s;transition:opacity text-shadow .1s ease}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:"\\e001"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}', 'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:999;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-ms-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1],.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.32s;-moz-animation-delay:-.32s;-ms-animation-delay:-.32s;-o-animation-delay:-.32s;animation-delay:-.32s}@-moz-keyframes bouncedelay{0%,100%,80%{-moz-transform:scale(0);transform:scale(0)}40%{-moz-transform:scale(1);transform:scale(1)}}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);transform:scale(1)}}@-o-keyframes bouncedelay{0%,100%,80%{-o-transform:scale(0);transform:scale(0)}40%{-o-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-ms-transform:scale(0);transform:scale(0)}40%{-ms-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0)}40%{transform:scale(1)}}', 'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}' } }; },{"underscore":"underscore"}],9:[function(require,module,exports){ "use strict"; var $ = require('zepto'); var _ = require('underscore'); var JST = require('./jst'); var Styler = {getStyleFor: function(name, options) { options = options || {}; return $('<style class="clappr-style"></style>').html(_.template(JST.CSS[name])(options))[0]; }}; module.exports = Styler; },{"./jst":8,"underscore":"underscore","zepto":"zepto"}],10:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var extend = function(protoProps, staticProps) { var parent = this; var child; if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function() { return parent.apply(this, arguments); }; } _.extend(child, parent, staticProps); var Surrogate = function() { this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate(); if (protoProps) _.extend(child.prototype, protoProps); child.__super__ = parent.prototype; child.super = function(name) { return parent.prototype[name]; }; child.prototype.getClass = function() { return child; }; return child; }; var formatTime = function(time) { time = time * 1000; time = parseInt(time / 1000); var seconds = time % 60; time = parseInt(time / 60); var minutes = time % 60; time = parseInt(time / 60); var hours = time % 24; var out = ""; if (hours && hours > 0) out += ("0" + hours).slice(-2) + ":"; out += ("0" + minutes).slice(-2) + ":"; out += ("0" + seconds).slice(-2); return out.trim(); }; var Fullscreen = { isFullscreen: function() { return document.webkitIsFullScreen || document.mozFullScreen || !!document.msFullscreenElement || window.iframeFullScreen; }, requestFullscreen: function(el) { if (el.requestFullscreen) { el.requestFullscreen(); } else if (el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); } else if (el.mozRequestFullScreen) { el.mozRequestFullScreen(); } else if (el.msRequestFullscreen) { el.msRequestFullscreen(); } }, cancelFullscreen: function() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } } }; var seekStringToSeconds = function(url) { var elements = _.rest(_.compact(url.match(/t=([0-9]*)h?([0-9]*)m?([0-9]*)s/))).reverse(); var seconds = 0; var factor = 1; _.each(elements, function(el) { seconds += (parseInt(el) * factor); factor = factor * 60; }, this); return seconds; }; module.exports = { extend: extend, formatTime: formatTime, Fullscreen: Fullscreen, seekStringToSeconds: seekStringToSeconds }; },{"underscore":"underscore"}],11:[function(require,module,exports){ "use strict"; var UIObject = require('ui_object'); var Styler = require('../../base/styler'); var _ = require('underscore'); var Events = require('../../base/events'); var Container = function Container(options) { $traceurRuntime.superCall(this, $Container.prototype, "constructor", [options]); this.playback = options.playback; this.settings = this.playback.settings; this.isReady = false; this.mediaControlDisabled = false; this.plugins = [this.playback]; this.bindEvents(); }; var $Container = Container; ($traceurRuntime.createClass)(Container, { get name() { return 'Container'; }, get attributes() { return { class: 'container', 'data-container': '' }; }, get events() { return {'click': 'clicked'}; }, bindEvents: function() { this.listenTo(this.playback, Events.PLAYBACK_PROGRESS, this.progress); this.listenTo(this.playback, Events.PLAYBACK_TIMEUPDATE, this.timeUpdated); this.listenTo(this.playback, Events.PLAYBACK_READY, this.ready); this.listenTo(this.playback, Events.PLAYBACK_BUFFERING, this.buffering); this.listenTo(this.playback, Events.PLAYBACK_BUFFERFULL, this.bufferfull); this.listenTo(this.playback, Events.PLAYBACK_SETTINGSUPDATE, this.settingsUpdate); this.listenTo(this.playback, Events.PLAYBACK_LOADEDMETADATA, this.loadedMetadata); this.listenTo(this.playback, Events.PLAYBACK_HIGHDEFINITIONUPDATE, this.highDefinitionUpdate); this.listenTo(this.playback, Events.PLAYBACK_BITRATE, this.updateBitrate); this.listenTo(this.playback, Events.PLAYBACK_PLAYBACKSTATE, this.playbackStateChanged); this.listenTo(this.playback, Events.PLAYBACK_DVR, this.playbackDvrStateChanged); this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_DISABLE, this.disableMediaControl); this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_ENABLE, this.enableMediaControl); this.listenTo(this.playback, Events.PLAYBACK_ENDED, this.ended); this.listenTo(this.playback, Events.PLAYBACK_PLAY, this.playing); this.listenTo(this.playback, Events.PLAYBACK_ERROR, this.error); }, with: function(klass) { _.extend(this, klass); return this; }, playbackStateChanged: function() { this.trigger(Events.CONTAINER_PLAYBACKSTATE); }, playbackDvrStateChanged: function(dvrInUse) { this.settings = this.playback.settings; this.dvrInUse = dvrInUse; this.trigger(Events.CONTAINER_PLAYBACKDVRSTATECHANGED, dvrInUse); }, updateBitrate: function(newBitrate) { this.trigger(Events.CONTAINER_BITRATE, newBitrate); }, statsReport: function(metrics) { this.trigger(Events.CONTAINER_STATS_REPORT, metrics); }, getPlaybackType: function() { return this.playback.getPlaybackType(); }, isDvrEnabled: function() { return !!this.playback.dvrEnabled; }, isDvrInUse: function() { return !!this.dvrInUse; }, destroy: function() { this.trigger(Events.CONTAINER_DESTROYED, this, this.name); this.playback.destroy(); _(this.plugins).each((function(plugin) { return plugin.destroy(); })); this.$el.remove(); }, setStyle: function(style) { this.$el.css(style); }, animate: function(style, duration) { return this.$el.animate(style, duration).promise(); }, ready: function() { this.isReady = true; this.trigger(Events.CONTAINER_READY, this.name); }, isPlaying: function() { return this.playback.isPlaying(); }, getDuration: function() { return this.playback.getDuration(); }, error: function(errorObj) { this.$el.append(errorObj.render().el); this.trigger(Events.CONTAINER_ERROR, { error: errorObj, container: this }, this.name); }, loadedMetadata: function(duration) { this.trigger(Events.CONTAINER_LOADEDMETADATA, duration); }, timeUpdated: function(position, duration) { this.trigger(Events.CONTAINER_TIMEUPDATE, position, duration, this.name); }, progress: function(startPosition, endPosition, duration) { this.trigger(Events.CONTAINER_PROGRESS, startPosition, endPosition, duration, this.name); }, playing: function() { this.trigger(Events.CONTAINER_PLAY, this.name); }, play: function() { this.playback.play(); }, stop: function() { this.trigger(Events.CONTAINER_STOP, this.name); this.playback.stop(); }, pause: function() { this.trigger(Events.CONTAINER_PAUSE, this.name); this.playback.pause(); }, ended: function() { this.trigger(Events.CONTAINER_ENDED, this, this.name); }, clicked: function() { this.trigger(Events.CONTAINER_CLICK, this, this.name); }, setCurrentTime: function(time) { this.trigger(Events.CONTAINER_SEEK, time, this.name); this.playback.seek(time); }, setVolume: function(value) { this.trigger(Events.CONTAINER_VOLUME, value, this.name); this.playback.volume(value); }, fullscreen: function() { this.trigger(Events.CONTAINER_FULLSCREEN, this.name); }, buffering: function() { this.trigger(Events.CONTAINER_STATE_BUFFERING, this.name); }, bufferfull: function() { this.trigger(Events.CONTAINER_STATE_BUFFERFULL, this.name); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find(function(plugin) { return plugin.name === name; }); }, settingsUpdate: function() { this.settings = this.playback.settings; this.trigger(Events.CONTAINER_SETTINGSUPDATE); }, highDefinitionUpdate: function() { this.trigger(Events.CONTAINER_HIGHDEFINITIONUPDATES); }, isHighDefinitionInUse: function() { return this.playback.isHighDefinitionInUse(); }, disableMediaControl: function() { this.mediaControlDisabled = true; this.trigger(Events.CONTAINER_MEDIACONTROL_DISABLE); }, enableMediaControl: function() { this.mediaControlDisabled = false; this.trigger(Events.CONTAINER_MEDIACONTROL_ENABLE); }, render: function() { var style = Styler.getStyleFor('container'); this.$el.append(style); this.$el.append(this.playback.render().el); return this; } }, {}, UIObject); module.exports = Container; },{"../../base/events":7,"../../base/styler":9,"ui_object":"ui_object","underscore":"underscore"}],12:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('base_object'); var Container = require('container'); var $ = require('zepto'); var ContainerFactory = function ContainerFactory(options, loader) { $traceurRuntime.superCall(this, $ContainerFactory.prototype, "constructor", [options]); this.options = options; this.loader = loader; }; var $ContainerFactory = ContainerFactory; ($traceurRuntime.createClass)(ContainerFactory, { createContainers: function() { var $__0 = this; return $.Deferred((function(promise) { promise.resolve(_.map($__0.options.sources, (function(source) { return $__0.createContainer(source); }), $__0)); })); }, findPlaybackPlugin: function(source) { return _.find(this.loader.playbackPlugins, (function(p) { return p.canPlay(source.toString()); }), this); }, createContainer: function(source) { var playbackPlugin = this.findPlaybackPlugin(source); var options = _.extend({}, this.options, { src: source, autoPlay: !!this.options.autoPlay }); var playback = new playbackPlugin(options); var container = new Container({playback: playback}); var defer = $.Deferred(); defer.promise(container); this.addContainerPlugins(container, source); this.listenToOnce(container, 'container:ready', (function() { return defer.resolve(container); })); return container; }, addContainerPlugins: function(container, source) { _.each(this.loader.containerPlugins, function(Plugin) { var options = _.extend(this.options, { container: container, src: source }); container.addPlugin(new Plugin(options)); }, this); } }, {}, BaseObject); module.exports = ContainerFactory; },{"base_object":"base_object","container":"container","underscore":"underscore","zepto":"zepto"}],13:[function(require,module,exports){ "use strict"; module.exports = require('./container_factory'); },{"./container_factory":12}],14:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('zepto'); var UIObject = require('ui_object'); var ContainerFactory = require('../container_factory'); var Fullscreen = require('../../base/utils').Fullscreen; var Styler = require('../../base/styler'); var MediaControl = require('media_control'); var PlayerInfo = require('player_info'); var Mediator = require('mediator'); var Core = function Core(options) { var $__0 = this; $traceurRuntime.superCall(this, $Core.prototype, "constructor", [options]); PlayerInfo.options = options; this.options = options; this.plugins = []; this.containers = []; this.createContainers(options); $(document).bind('fullscreenchange', (function() { return $__0.exit(); })); $(document).bind('MSFullscreenChange', (function() { return $__0.exit(); })); $(document).bind('mozfullscreenchange', (function() { return $__0.exit(); })); }; var $Core = Core; ($traceurRuntime.createClass)(Core, { get events() { return { 'webkitfullscreenchange': 'exit', 'mousemove': 'showMediaControl', 'mouseleave': 'hideMediaControl' }; }, get attributes() { return {'data-player': ''}; }, createContainers: function(options) { var $__0 = this; this.defer = $.Deferred(); this.defer.promise(this); this.containerFactory = new ContainerFactory(options, options.loader); this.containerFactory.createContainers().then((function(containers) { return $__0.setupContainers(containers); })).then((function(containers) { return $__0.resolveOnContainersReady(containers); })); }, updateSize: function() { if (Fullscreen.isFullscreen()) { this.setFullscreen(); } else { this.setPlayerSize(); } Mediator.trigger('player:resize'); }, setFullscreen: function() { this.$el.addClass('fullscreen'); this.$el.removeAttr('style'); PlayerInfo.previousSize = PlayerInfo.currentSize; PlayerInfo.currentSize = { width: $(window).width(), height: $(window).height() }; }, setPlayerSize: function() { this.$el.removeClass('fullscreen'); PlayerInfo.currentSize = PlayerInfo.previousSize; PlayerInfo.previousSize = { width: $(window).width(), height: $(window).height() }; this.resize(PlayerInfo.currentSize); }, resize: function(options) { var size = _.pick(options, 'width', 'height'); this.$el.css(size); PlayerInfo.previousSize = PlayerInfo.currentSize; PlayerInfo.currentSize = size; Mediator.trigger('player:resize'); }, resolveOnContainersReady: function(containers) { var $__0 = this; $.when.apply($, containers).done((function() { return $__0.defer.resolve($__0); })); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find((function(plugin) { return plugin.name === name; })); }, load: function(sources) { var $__0 = this; sources = _.isArray(sources) ? sources : [sources.toString()]; _(this.containers).each((function(container) { return container.destroy(); })); this.containerFactory.options = _(this.options).extend({sources: sources}); this.containerFactory.createContainers().then((function(containers) { $__0.setupContainers(containers); })); }, destroy: function() { _(this.containers).each((function(container) { return container.destroy(); })); _(this.plugins).each((function(plugin) { return plugin.destroy(); })); this.$el.remove(); this.mediaControl.destroy(); $(document).unbind('fullscreenchange'); $(document).unbind('MSFullscreenChange'); $(document).unbind('mozfullscreenchange'); }, exit: function() { this.updateSize(); this.mediaControl.show(); }, setMediaControlContainer: function(container) { this.mediaControl.setContainer(container); this.mediaControl.render(); }, disableMediaControl: function() { this.mediaControl.disable(); this.$el.removeClass('nocursor'); }, enableMediaControl: function() { this.mediaControl.enable(); }, removeContainer: function(container) { this.stopListening(container); this.containers = _.without(this.containers, container); }, appendContainer: function(container) { this.listenTo(container, 'container:destroyed', this.removeContainer); this.el.appendChild(container.render().el); this.containers.push(container); }, prependContainer: function(container) { this.listenTo(container, 'container:destroyed', this.removeContainer); this.$el.append(container.render().el); this.containers.unshift(container); }, setupContainers: function(containers) { _.map(containers, this.appendContainer, this); this.setupMediaControl(this.getCurrentContainer()); this.render(); this.$el.appendTo(this.options.parentElement); return containers; }, createContainer: function(source) { var container = this.containerFactory.createContainer(source); this.appendContainer(container); return container; }, setupMediaControl: function(container) { if (this.mediaControl) { this.mediaControl.setContainer(container); } else { this.mediaControl = this.createMediaControl(_.extend({container: container}, this.options)); this.listenTo(this.mediaControl, 'mediacontrol:fullscreen', this.toggleFullscreen); this.listenTo(this.mediaControl, 'mediacontrol:show', this.onMediaControlShow.bind(this, true)); this.listenTo(this.mediaControl, 'mediacontrol:hide', this.onMediaControlShow.bind(this, false)); } }, createMediaControl: function(options) { if (options.mediacontrol && options.mediacontrol.external) { return new options.mediacontrol.external(options); } else { return new MediaControl(options); } }, getCurrentContainer: function() { return this.containers[0]; }, toggleFullscreen: function() { if (!Fullscreen.isFullscreen()) { Fullscreen.requestFullscreen(this.el); this.$el.addClass('fullscreen'); } else { Fullscreen.cancelFullscreen(); this.$el.removeClass('fullscreen nocursor'); } this.mediaControl.show(); }, showMediaControl: function(event) { this.mediaControl.show(event); }, hideMediaControl: function(event) { this.mediaControl.hide(event); }, onMediaControlShow: function(showing) { if (showing) this.$el.removeClass('nocursor'); else if (Fullscreen.isFullscreen()) this.$el.addClass('nocursor'); }, render: function() { var style = Styler.getStyleFor('core'); this.$el.append(style); this.$el.append(this.mediaControl.render().el); this.options.width = this.options.width || this.$el.width(); this.options.height = this.options.height || this.$el.height(); PlayerInfo.previousSize = PlayerInfo.currentSize = _.pick(this.options, 'width', 'height'); this.updateSize(); return this; } }, {}, UIObject); module.exports = Core; },{"../../base/styler":9,"../../base/utils":10,"../container_factory":13,"media_control":"media_control","mediator":"mediator","player_info":"player_info","ui_object":"ui_object","underscore":"underscore","zepto":"zepto"}],15:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('base_object'); var Core = require('core'); var CoreFactory = function CoreFactory(player, loader) { this.player = player; this.options = player.options; this.loader = loader; this.options.loader = this.loader; }; ($traceurRuntime.createClass)(CoreFactory, { create: function() { this.core = new Core(this.options); this.core.then(this.addCorePlugins.bind(this)); return this.core; }, addCorePlugins: function() { _.each(this.loader.corePlugins, function(Plugin) { var plugin = new Plugin(this.core); this.core.addPlugin(plugin); this.setupExternalInterface(plugin); }, this); return this.core; }, setupExternalInterface: function(plugin) { _.each(plugin.getExternalInterface(), function(value, key) { this.player[key] = value.bind(plugin); }, this); } }, {}, BaseObject); module.exports = CoreFactory; },{"base_object":"base_object","core":"core","underscore":"underscore"}],16:[function(require,module,exports){ "use strict"; module.exports = require('./core_factory'); },{"./core_factory":15}],17:[function(require,module,exports){ "use strict"; var BaseObject = require('base_object'); var $ = require('zepto'); var Player = require('../player'); var IframePlayer = function IframePlayer(options) { $traceurRuntime.superCall(this, $IframePlayer.prototype, "constructor", [options]); this.options = options; this.createIframe(); }; var $IframePlayer = IframePlayer; ($traceurRuntime.createClass)(IframePlayer, { createIframe: function() { this.iframe = document.createElement("iframe"); this.iframe.setAttribute("frameborder", 0); this.iframe.setAttribute("id", this.uniqueId); this.iframe.setAttribute("allowfullscreen", true); this.iframe.setAttribute("scrolling", "no"); this.iframe.setAttribute("src", "http://cdn.clappr.io/latest/assets/iframe.htm" + this.buildQueryString()); this.iframe.setAttribute('width', this.options.width); this.iframe.setAttribute('height', this.options.height); }, attachTo: function(element) { element.appendChild(this.iframe); }, addEventListeners: function() { var $__0 = this; this.iframe.contentWindow.addEventListener("fullscreenchange", (function() { return $__0.updateSize(); })); this.iframe.contentWindow.addEventListener("webkitfullscreenchange", (function() { return $__0.updateSize(); })); this.iframe.contentWindow.addEventListener("mozfullscreenchange", (function() { return $__0.updateSize(); })); }, buildQueryString: function() { var result = ""; for (var param in this.options) { result += !!result ? "&" : "?"; result += encodeURIComponent(param) + "=" + encodeURIComponent(this.options[param]); } return result; } }, {}, BaseObject); module.exports = IframePlayer; },{"../player":22,"base_object":"base_object","zepto":"zepto"}],18:[function(require,module,exports){ "use strict"; module.exports = require('./iframe_player'); },{"./iframe_player":17}],19:[function(require,module,exports){ "use strict"; module.exports = require('./loader'); },{"./loader":20}],20:[function(require,module,exports){ "use strict"; var BaseObject = require('base_object'); var _ = require('underscore'); var PlayerInfo = require('player_info'); var HTML5VideoPlayback = require('html5_video'); var FlashVideoPlayback = require('flash'); var HTML5AudioPlayback = require('html5_audio'); var HLSVideoPlayback = require('hls'); var NoOp = require('../../playbacks/no_op'); var SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce'); var StatsPlugin = require('../../plugins/stats'); var WaterMarkPlugin = require('../../plugins/watermark'); var PosterPlugin = require('poster'); var GoogleAnalyticsPlugin = require('../../plugins/google_analytics'); var ClickToPausePlugin = require('../../plugins/click_to_pause'); var BackgroundButton = require('../../plugins/background_button'); var DVRControls = require('../../plugins/dvr_controls'); var Loader = function Loader(externalPlugins) { $traceurRuntime.superCall(this, $Loader.prototype, "constructor", []); this.playbackPlugins = [FlashVideoPlayback, HTML5VideoPlayback, HTML5AudioPlayback, HLSVideoPlayback, NoOp]; this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin, GoogleAnalyticsPlugin, ClickToPausePlugin]; this.corePlugins = [BackgroundButton, DVRControls]; if (externalPlugins) { this.addExternalPlugins(externalPlugins); } }; var $Loader = Loader; ($traceurRuntime.createClass)(Loader, { addExternalPlugins: function(plugins) { var pluginName = function(plugin) { return plugin.prototype.name; }; if (plugins.playback) { this.playbackPlugins = _.uniq(plugins.playback.concat(this.playbackPlugins), pluginName); } if (plugins.container) { this.containerPlugins = _.uniq(plugins.container.concat(this.containerPlugins), pluginName); } if (plugins.core) { this.corePlugins = _.uniq(plugins.core.concat(this.corePlugins), pluginName); } PlayerInfo.playbackPlugins = this.playbackPlugins; }, getPlugin: function(name) { var allPlugins = _.union(this.containerPlugins, this.playbackPlugins, this.corePlugins); return _.find(allPlugins, function(plugin) { return plugin.prototype.name === name; }); } }, {}, BaseObject); module.exports = Loader; },{"../../playbacks/no_op":29,"../../plugins/background_button":32,"../../plugins/click_to_pause":34,"../../plugins/dvr_controls":36,"../../plugins/google_analytics":38,"../../plugins/spinner_three_bounce":42,"../../plugins/stats":44,"../../plugins/watermark":46,"base_object":"base_object","flash":"flash","hls":"hls","html5_audio":"html5_audio","html5_video":"html5_video","player_info":"player_info","poster":"poster","underscore":"underscore"}],21:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('zepto'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var UIObject = require('ui_object'); var Utils = require('../../base/utils'); var Mousetrap = require('mousetrap'); var SeekTime = require('../seek_time'); var Mediator = require('mediator'); var PlayerInfo = require('player_info'); var MediaControl = function MediaControl(options) { var $__0 = this; $traceurRuntime.superCall(this, $MediaControl.prototype, "constructor", [options]); this.seekTime = new SeekTime(this); this.options = options; this.mute = this.options.mute; this.currentVolume = this.options.mute ? 0 : 100; this.container = options.container; this.container.setVolume(this.currentVolume); this.keepVisible = false; this.addEventListeners(); this.settings = { left: ['play', 'stop', 'pause'], right: ['volume'], default: ['position', 'seekbar', 'duration'] }; this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings; this.disabled = false; if (this.container.mediaControlDisabled || this.options.chromeless) { this.disable(); } $(document).bind('mouseup', (function(event) { return $__0.stopDrag(event); })); $(document).bind('mousemove', (function(event) { return $__0.updateDrag(event); })); Mediator.on('player:resize', (function() { return $__0.playerResize(); })); }; var $MediaControl = MediaControl; ($traceurRuntime.createClass)(MediaControl, { get name() { return 'MediaControl'; }, get attributes() { return { class: 'media-control', 'data-media-control': '' }; }, get events() { return { 'click [data-play]': 'play', 'click [data-pause]': 'pause', 'click [data-playpause]': 'togglePlayPause', 'click [data-stop]': 'stop', 'click [data-playstop]': 'togglePlayStop', 'click [data-fullscreen]': 'toggleFullscreen', 'click .bar-container[data-seekbar]': 'seek', 'click .bar-container[data-volume]': 'volume', 'click .drawer-icon[data-volume]': 'toggleMute', 'mouseenter .drawer-container[data-volume]': 'showVolumeBar', 'mouseleave .drawer-container[data-volume]': 'hideVolumeBar', 'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag', 'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag', 'mousemove .bar-container[data-seekbar]': 'mousemoveOnSeekBar', 'mouseleave .bar-container[data-seekbar]': 'mouseleaveOnSeekBar', 'mouseenter .media-control-layer[data-controls]': 'setKeepVisible', 'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible' }; }, get template() { return JST.media_control; }, addEventListeners: function() { this.listenTo(this.container, 'container:play', this.changeTogglePlay); this.listenTo(this.container, 'container:timeupdate', this.updateSeekBar); this.listenTo(this.container, 'container:progress', this.updateProgressBar); this.listenTo(this.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.container, 'container:dvr', this.settingsUpdate); this.listenTo(this.container, 'container:highdefinitionupdate', this.highDefinitionUpdate); this.listenTo(this.container, 'container:mediacontrol:disable', this.disable); this.listenTo(this.container, 'container:mediacontrol:enable', this.enable); this.listenTo(this.container, 'container:ended', this.ended); }, disable: function() { this.disabled = true; this.hide(); this.$el.hide(); }, enable: function() { if (this.options.chromeless) return; this.disabled = false; this.show(); }, play: function() { this.container.play(); }, pause: function() { this.container.pause(); }, stop: function() { this.container.stop(); }, changeTogglePlay: function() { if (this.container.isPlaying()) { this.$playPauseToggle.removeClass('paused').addClass('playing'); this.$playStopToggle.removeClass('stopped').addClass('playing'); this.trigger('mediacontrol:playing'); } else { this.$playPauseToggle.removeClass('playing').addClass('paused'); this.$playStopToggle.removeClass('playing').addClass('stopped'); this.trigger('mediacontrol:notplaying'); } }, mousemoveOnSeekBar: function(event) { if (this.container.settings.seekEnabled) { var offsetX = event.pageX - this.$seekBarContainer.offset().left - (this.$seekBarHover.width() / 2); this.$seekBarHover.css({left: offsetX}); } this.trigger('mediacontrol:mousemove:seekbar', event); }, mouseleaveOnSeekBar: function(event) { this.trigger('mediacontrol:mouseleave:seekbar', event); }, playerResize: function() { if (Utils.Fullscreen.isFullscreen()) { this.$fullscreenToggle.addClass('shrink'); } else { this.$fullscreenToggle.removeClass('shrink'); } this.$el.removeClass('w320'); if (PlayerInfo.currentSize.width <= 320) { this.$el.addClass('w320'); } }, togglePlayPause: function() { if (this.container.isPlaying()) { this.container.pause(); } else { this.container.play(); } this.changeTogglePlay(); }, togglePlayStop: function() { if (this.container.isPlaying()) { this.container.stop(); } else { this.container.play(); } this.changeTogglePlay(); }, startSeekDrag: function(event) { if (!this.container.settings.seekEnabled) return; this.draggingSeekBar = true; this.$el.addClass('dragging'); this.$seekBarLoaded.addClass('media-control-notransition'); this.$seekBarPosition.addClass('media-control-notransition'); this.$seekBarScrubber.addClass('media-control-notransition'); if (event) { event.preventDefault(); } }, startVolumeDrag: function(event) { this.draggingVolumeBar = true; this.$el.addClass('dragging'); if (event) { event.preventDefault(); } }, stopDrag: function(event) { if (this.draggingSeekBar) { this.seek(event); } this.$el.removeClass('dragging'); this.$seekBarLoaded.removeClass('media-control-notransition'); this.$seekBarPosition.removeClass('media-control-notransition'); this.$seekBarScrubber.removeClass('media-control-notransition dragging'); this.draggingSeekBar = false; this.draggingVolumeBar = false; }, updateDrag: function(event) { if (event) { event.preventDefault(); } if (this.draggingSeekBar) { var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.setSeekPercentage(pos); } else if (this.draggingVolumeBar) { this.volume(event); } }, volume: function(event) { var offsetY = event.pageX - this.$volumeBarContainer.offset().left; this.currentVolume = (offsetY / this.$volumeBarContainer.width()) * 100; this.currentVolume = Math.min(100, Math.max(this.currentVolume, 0)); this.container.setVolume(this.currentVolume); this.setVolumeLevel(this.currentVolume); }, toggleMute: function() { if (this.mute) { if (this.currentVolume <= 0) { this.currentVolume = 100; } this.setVolume(this.currentVolume); } else { this.setVolume(0); } }, setVolume: function(value) { this.container.setVolume(value); this.setVolumeLevel(value); if (value === 0) { this.mute = true; } else { this.mute = false; } }, toggleFullscreen: function() { this.trigger('mediacontrol:fullscreen', this.name); this.container.fullscreen(); this.resetKeepVisible(); }, setContainer: function(container) { this.stopListening(this.container); this.container = container; this.changeTogglePlay(); this.addEventListeners(); this.settingsUpdate(); this.container.trigger('container:dvr', this.container.isDvrInUse()); this.container.setVolume(this.currentVolume); if (this.container.mediaControlDisabled) { this.disable(); } this.trigger("mediacontrol:containerchanged"); }, showVolumeBar: function() { if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.$volumeBarContainer.removeClass('volume-bar-hide'); }, hideVolumeBar: function() { var $__0 = this; var timeout = 400; if (!this.$volumeBarContainer) return; if (this.draggingVolumeBar) { this.hideVolumeId = setTimeout((function() { return $__0.hideVolumeBar(); }), timeout); } else { if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.hideVolumeId = setTimeout((function() { return $__0.$volumeBarContainer.addClass('volume-bar-hide'); }), timeout); } }, ended: function() { this.changeTogglePlay(); }, updateProgressBar: function(startPosition, endPosition, duration) { var loadedStart = startPosition / duration * 100; var loadedEnd = endPosition / duration * 100; this.$seekBarLoaded.css({ left: loadedStart + '%', width: (loadedEnd - loadedStart) + '%' }); }, updateSeekBar: function(position, duration) { if (this.draggingSeekBar) return; if (position < 0) position = duration; this.$seekBarPosition.removeClass('media-control-notransition'); this.$seekBarScrubber.removeClass('media-control-notransition'); var seekbarValue = (100 / duration) * position; this.setSeekPercentage(seekbarValue); this.$('[data-position]').html(Utils.formatTime(position)); this.$('[data-duration]').html(Utils.formatTime(duration)); }, seek: function(event) { if (!this.container.settings.seekEnabled) return; var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.container.setCurrentTime(pos); this.setSeekPercentage(pos); return false; }, setKeepVisible: function() { this.keepVisible = true; }, resetKeepVisible: function() { this.keepVisible = false; }, isVisible: function() { return !this.$el.hasClass('media-control-hide'); }, show: function(event) { var $__0 = this; if (this.disabled || this.container.getPlaybackType() === null) return; var timeout = 2000; if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) { clearTimeout(this.hideId); this.$el.show(); this.trigger('mediacontrol:show', this.name); this.$el.removeClass('media-control-hide'); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (event) { this.lastMouseX = event.clientX; this.lastMouseY = event.clientY; } } }, hide: function() { var $__0 = this; var timeout = 2000; clearTimeout(this.hideId); if (!this.isVisible() || this.options.hideMediaControl === false) return; if (this.keepVisible || this.draggingSeekBar || this.draggingVolumeBar) { this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); } else { this.trigger('mediacontrol:hide', this.name); this.$el.addClass('media-control-hide'); this.hideVolumeBar(); } }, settingsUpdate: function() { if (this.container.getPlaybackType() !== null && !_.isEmpty(this.container.settings)) { this.settings = this.container.settings; this.render(); this.enable(); } else { this.disable(); } }, highDefinitionUpdate: function() { if (this.container.isHighDefinitionInUse()) { this.$el.find('button[data-hd-indicator]').addClass("enabled"); } else { this.$el.find('button[data-hd-indicator]').removeClass("enabled"); } }, createCachedElements: function() { this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]'); this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]'); this.$fullscreenToggle = this.$el.find('button.media-control-button[data-fullscreen]'); this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]'); this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]'); this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]'); this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]'); this.$seekBarHover = this.$el.find('.bar-hover[data-seekbar]'); this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]'); this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]'); }, setVolumeLevel: function(value) { var $__0 = this; if (!this.container.isReady) { this.listenToOnce(this.container, "container:ready", (function() { return $__0.setVolumeLevel(value); })); } else { this.$volumeBarContainer.find('.segmented-bar-element').removeClass('fill'); var item = Math.ceil(value / 10.0); this.$volumeBarContainer.find('.segmented-bar-element').slice(0, item).addClass('fill'); if (value > 0) { this.$volumeIcon.removeClass('muted'); } else { this.$volumeIcon.addClass('muted'); } } }, setSeekPercentage: function(value) { if (value > 100) return; var pos = this.$seekBarContainer.width() * value / 100.0 - (this.$seekBarScrubber.width() / 2.0); this.currentSeekPercentage = value; this.$seekBarPosition.css({width: value + '%'}); this.$seekBarScrubber.css({left: pos}); }, bindKeyEvents: function() { var $__0 = this; Mousetrap.bind(['space'], (function() { return $__0.togglePlayPause(); })); }, unbindKeyEvents: function() { Mousetrap.unbind('space'); }, parseColors: function() { if (this.options.mediacontrol) { var buttonsColor = this.options.mediacontrol.buttons; var seekbarColor = this.options.mediacontrol.seekbar; this.$el.find('.bar-fill-2[data-seekbar]').css('background-color', seekbarColor); this.$el.find('[data-media-control] > .media-control-icon, .drawer-icon').css('color', buttonsColor); this.$el.find('.segmented-bar-element[data-volume]').css('boxShadow', "inset 2px 0 0 " + buttonsColor); } }, render: function() { var $__0 = this; var timeout = 1000; var style = Styler.getStyleFor('media_control'); this.$el.html(this.template({settings: this.settings})); this.$el.append(style); this.createCachedElements(); this.$playPauseToggle.addClass('paused'); this.$playStopToggle.addClass('stopped'); this.changeTogglePlay(); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (this.disabled) { this.hide(); } this.$seekBarPosition.addClass('media-control-notransition'); this.$seekBarScrubber.addClass('media-control-notransition'); if (!this.currentSeekPercentage) { this.currentSeekPercentage = 0; } this.setSeekPercentage(this.currentSeekPercentage); this.$el.ready((function() { if (!$__0.container.settings.seekEnabled) { $__0.$seekBarContainer.addClass('seek-disabled'); } $__0.setVolumeLevel($__0.currentVolume); $__0.bindKeyEvents(); $__0.hideVolumeBar(); })); this.parseColors(); this.seekTime.render(); this.trigger('mediacontrol:rendered'); return this; }, destroy: function() { $(document).unbind('mouseup'); $(document).unbind('mousemove'); this.unbindKeyEvents(); } }, {}, UIObject); module.exports = MediaControl; },{"../../base/jst":8,"../../base/styler":9,"../../base/utils":10,"../seek_time":23,"mediator":"mediator","mousetrap":4,"player_info":"player_info","ui_object":"ui_object","underscore":"underscore","zepto":"zepto"}],22:[function(require,module,exports){ "use strict"; var BaseObject = require('base_object'); var CoreFactory = require('./core_factory'); var Loader = require('./loader'); var _ = require('underscore'); var ScrollMonitor = require('scrollmonitor'); var PlayerInfo = require('player_info'); var Player = function Player(options) { $traceurRuntime.superCall(this, $Player.prototype, "constructor", [options]); window.p = this; this.options = options; this.options.sources = this.normalizeSources(options); this.loader = new Loader(this.options.plugins || []); this.coreFactory = new CoreFactory(this, this.loader); options.height || (options.height = 360); options.width || (options.width = 640); PlayerInfo.currentSize = { width: options.width, height: options.height }; if (this.options.parentId) { var el = document.querySelector(this.options.parentId); if (el) { this.attachTo(el); } } }; var $Player = Player; ($traceurRuntime.createClass)(Player, { attachTo: function(element) { this.options.parentElement = element; this.core = this.coreFactory.create(); if (this.options.autoPlayVisible) { this.bindAutoPlayVisible(this.options.autoPlayVisible); } }, bindAutoPlayVisible: function(option) { var $__0 = this; this.elementWatcher = ScrollMonitor.create(this.core.$el); if (option === 'full') { this.elementWatcher.fullyEnterViewport((function() { return $__0.enterViewport(); })); } else if (option === 'partial') { this.elementWatcher.enterViewport((function() { return $__0.enterViewport(); })); } }, enterViewport: function() { if (this.elementWatcher.top !== 0 && !this.isPlaying()) { this.play(); } }, normalizeSources: function(options) { return _.compact(_.flatten([options.source, options.sources])); }, resize: function(size) { this.core.resize(size); }, load: function(sources) { this.core.load(sources); }, destroy: function() { this.core.destroy(); }, play: function() { this.core.mediaControl.container.play(); }, pause: function() { this.core.mediaControl.container.pause(); }, stop: function() { this.core.mediaControl.container.stop(); }, seek: function(time) { this.core.mediaControl.container.setCurrentTime(time); }, setVolume: function(volume) { this.core.mediaControl.container.setVolume(volume); }, mute: function() { this.core.mediaControl.container.setVolume(0); }, unmute: function() { this.core.mediaControl.container.setVolume(100); }, isPlaying: function() { return this.core.mediaControl.container.isPlaying(); } }, {}, BaseObject); module.exports = Player; },{"./core_factory":16,"./loader":19,"base_object":"base_object","player_info":"player_info","scrollmonitor":5,"underscore":"underscore"}],23:[function(require,module,exports){ "use strict"; module.exports = require('./seek_time'); },{"./seek_time":24}],24:[function(require,module,exports){ "use strict"; var UIObject = require('ui_object'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var formatTime = require('../../base/utils').formatTime; var SeekTime = function SeekTime(mediaControl) { $traceurRuntime.superCall(this, $SeekTime.prototype, "constructor", []); this.mediaControl = mediaControl; this.addEventListeners(); }; var $SeekTime = SeekTime; ($traceurRuntime.createClass)(SeekTime, { get name() { return 'seek_time'; }, get template() { return JST.seek_time; }, get attributes() { return { 'class': 'seek-time hidden', 'data-seek-time': '' }; }, addEventListeners: function() { this.listenTo(this.mediaControl, 'mediacontrol:mousemove:seekbar', this.showTime); this.listenTo(this.mediaControl, 'mediacontrol:mouseleave:seekbar', this.hideTime); }, showTime: function(event) { var offset = event.pageX - this.mediaControl.$seekBarContainer.offset().left; var timePosition = Math.min(100, Math.max((offset) / this.mediaControl.$seekBarContainer.width() * 100, 0)); var pointerPosition = event.pageX - this.mediaControl.$el.offset().left - (this.$el.width() / 2); pointerPosition = Math.min(Math.max(0, pointerPosition), this.mediaControl.$el.width() - this.$el.width()); var currentTime = timePosition * this.mediaControl.container.getDuration() / 100; var options = { timestamp: currentTime, formattedTime: formatTime(currentTime), pointerPosition: pointerPosition }; this.update(options); }, hideTime: function() { this.$el.addClass('hidden'); this.$el.css('left', '-100%'); }, update: function(options) { if (this.mediaControl.container.getPlaybackType() === 'vod' || this.mediaControl.container.isDvrInUse()) { this.$el.find('[data-seek-time]').text(options.formattedTime); this.$el.css('left', options.pointerPosition); this.$el.removeClass('hidden'); } }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.mediaControl.$el.append(this.el); } }, {}, UIObject); module.exports = SeekTime; },{"../../base/jst":8,"../../base/styler":9,"../../base/utils":10,"ui_object":"ui_object"}],25:[function(require,module,exports){ "use strict"; var Playback = require('playback'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Mediator = require('mediator'); var _ = require('underscore'); var $ = require('zepto'); var Browser = require('browser'); var Mousetrap = require('mousetrap'); var seekStringToSeconds = require('../../base/utils').seekStringToSeconds; var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-flash-vod=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>'; var Flash = function Flash(options) { $traceurRuntime.superCall(this, $Flash.prototype, "constructor", [options]); this.src = options.src; this.isRTMP = (this.src.indexOf("rtmp") > -1); this.defaultBaseSwfPath = "http://cdn.clappr.io/" + Clappr.version + "/assets/"; this.swfPath = (options.swfBasePath || this.defaultBaseSwfPath) + "Player.swf"; this.autoPlay = options.autoPlay; this.settings = {default: ['seekbar']}; if (this.isRTMP) { this.settings.left = ["playstop"]; this.settings.right = ["fullscreen", "volume"]; } else { this.settings.left = ["playpause", "position", "duration"]; this.settings.right = ["fullscreen", "volume"]; this.settings.seekEnabled = true; } this.isReady = false; this.addListeners(); }; var $Flash = Flash; ($traceurRuntime.createClass)(Flash, { get name() { return 'flash'; }, get tagName() { return 'object'; }, get template() { return JST.flash; }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.isReady = true; if (this.currentState === 'PLAYING') { this.firstPlay(); } else { this.currentState = "IDLE"; this.autoPlay && this.play(); } $('<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />').insertAfter(this.$el); this.trigger('playback:ready', this.name); }, getPlaybackType: function() { return this.isRTMP ? 'live' : 'vod'; }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-flash', ''); this.setElement($el[0]); }, isHighDefinitionInUse: function() { return false; }, updateTime: function() { this.trigger('playback:timeupdate', this.el.getPosition(), this.el.getDuration(), this.name); }, addListeners: function() { Mediator.on(this.uniqueId + ':progress', this.progress, this); Mediator.on(this.uniqueId + ':timeupdate', this.updateTime, this); Mediator.on(this.uniqueId + ':statechanged', this.checkState, this); Mediator.on(this.uniqueId + ':flashready', this.bootstrap, this); _.each(_.range(1, 10), function(i) { var $__0 = this; Mousetrap.bind([i.toString()], (function() { return $__0.seek(i * 10); })); }.bind(this)); }, stopListening: function() { $traceurRuntime.superCall(this, $Flash.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':progress'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':statechanged'); Mediator.off(this.uniqueId + ':flashready'); _.each(_.range(1, 10), function(i) { var $__0 = this; Mousetrap.unbind([i.toString()], (function() { return $__0.seek(i * 10); })); }.bind(this)); }, checkState: function() { if (this.currentState === "PAUSED") { return; } else if (this.currentState !== "PLAYING_BUFFERING" && this.el.getState() === "PLAYING_BUFFERING") { this.trigger('playback:buffering', this.name); this.currentState = "PLAYING_BUFFERING"; } else if (this.currentState === "PLAYING_BUFFERING" && this.el.getState() === "PLAYING") { this.trigger('playback:bufferfull', this.name); this.currentState = "PLAYING"; } else if (this.el.getState() === "IDLE") { this.currentState = "IDLE"; } else if (this.el.getState() === "ENDED") { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.getDuration(), this.name); this.currentState = "ENDED"; } }, progress: function() { if (this.currentState !== "IDLE" && this.currentState !== "ENDED") { this.trigger('playback:progress', 0, this.el.getBytesLoaded(), this.el.getBytesTotal(), this.name); } }, firstPlay: function() { var $__0 = this; this.currentState = "PLAYING"; if (_.isFunction(this.el.playerPlay)) { this.el.playerPlay(this.src); this.listenToOnce(this, 'playback:bufferfull', (function() { return $__0.checkInitialSeek(); })); } }, checkInitialSeek: function() { var seekTime = seekStringToSeconds(window.location.href); this.seekSeconds(seekTime); }, play: function() { if (this.el.getState() === 'PAUSED' || this.el.getState() === 'PLAYING_BUFFERING') { this.currentState = "PLAYING"; this.el.playerResume(); } else if (this.el.getState() !== 'PLAYING') { this.firstPlay(); } this.trigger('playback:play', this.name); }, volume: function(value) { var $__0 = this; if (this.isReady) { this.el.playerVolume(value); } else { this.listenToOnce(this, 'playback:bufferfull', (function() { return $__0.volume(value); })); } }, pause: function() { this.currentState = "PAUSED"; this.el.playerPause(); }, stop: function() { this.el.playerStop(); this.trigger('playback:timeupdate', 0, this.name); }, isPlaying: function() { return !!(this.isReady && this.currentState === "PLAYING"); }, getDuration: function() { return this.el.getDuration(); }, seek: function(seekBarValue) { var seekTo = this.el.getDuration() * (seekBarValue / 100); this.seekSeconds(seekTo); }, seekSeconds: function(seekTo) { this.el.playerSeek(seekTo); this.trigger('playback:timeupdate', seekTo, this.el.getDuration(), this.name); if (this.currentState === "PAUSED") { this.el.playerPause(); } }, destroy: function() { clearInterval(this.bootstrapId); this.stopListening(); this.$el.remove(); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId }))); }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isLegacyIE) { this.setupIE(); } this.$el.append(style); return this; } }, {}, Playback); Flash.canPlay = function(resource) { if (resource.indexOf('rtmp') > -1) { return true; } else if ((!Browser.isMobile && Browser.isFirefox) || Browser.isLegacyIE) { return _.isString(resource) && !!resource.match(/(.*)\.(mp4|mov|f4v|3gpp|3gp)/); } else { return _.isString(resource) && !!resource.match(/(.*)\.(mov|f4v|3gpp|3gp)/); } }; module.exports = Flash; },{"../../base/jst":8,"../../base/styler":9,"../../base/utils":10,"browser":"browser","mediator":"mediator","mousetrap":4,"playback":"playback","underscore":"underscore","zepto":"zepto"}],26:[function(require,module,exports){ "use strict"; var Playback = require('playback'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var _ = require("underscore"); var Mediator = require('mediator'); var Browser = require('browser'); var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" class="hls-playback" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls="" width="100%" height="100%"><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>'; var HLS = function HLS(options) { $traceurRuntime.superCall(this, $HLS.prototype, "constructor", [options]); this.src = options.src; this.defaultBaseSwfPath = "http://cdn.clappr.io/" + Clappr.version + "/assets/"; this.swfPath = (options.swfBasePath || this.defaultBaseSwfPath) + "HLSPlayer.swf"; this.flushLiveURLCache = (options.flushLiveURLCache === undefined) ? true : options.flushLiveURLCache; this.capLevelToStage = (options.capLevelToStage === undefined) ? false : options.capLevelToStage; this.highDefinition = false; this.autoPlay = options.autoPlay; this.defaultSettings = { left: ["playstop"], default: ['seekbar'], right: ["fullscreen", "volume", "hd-indicator"], seekEnabled: false }; this.settings = _.extend({}, this.defaultSettings); this.playbackType = 'live'; this.addListeners(); }; var $HLS = HLS; ($traceurRuntime.createClass)(HLS, { get name() { return 'hls'; }, get tagName() { return 'object'; }, get template() { return JST.hls; }, get attributes() { return { 'class': 'hls-playback', 'data-hls': '', 'type': 'application/x-shockwave-flash' }; }, addListeners: function() { var $__0 = this; Mediator.on(this.uniqueId + ':flashready', (function() { return $__0.bootstrap(); })); Mediator.on(this.uniqueId + ':timeupdate', (function() { return $__0.updateTime(); })); Mediator.on(this.uniqueId + ':playbackstate', (function(state) { return $__0.setPlaybackState(state); })); Mediator.on(this.uniqueId + ':highdefinition', (function(isHD) { return $__0.updateHighDefinition(isHD); })); Mediator.on(this.uniqueId + ':playbackerror', (function() { return $__0.flashPlaybackError(); })); }, stopListening: function() { $traceurRuntime.superCall(this, $HLS.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':flashready'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':playbackstate'); Mediator.off(this.uniqueId + ':highdefinition'); Mediator.off(this.uniqueId + ':playbackerror'); }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.isReady = true; this.trigger('playback:ready', this.name); this.currentState = "IDLE"; this.setFlashSettings(); this.autoPlay && this.play(); }, setFlashSettings: function() { this.el.globoPlayerSetflushLiveURLCache(this.flushLiveURLCache); this.el.globoPlayerCapLeveltoStage(this.capLevelToStage); this.el.globoPlayerSetmaxBufferLength(0); }, updateHighDefinition: function(isHD) { this.highDefinition = (isHD === "true"); this.trigger('playback:highdefinitionupdate'); this.trigger('playback:bitrate', {'bitrate': this.getCurrentBitrate()}); }, updateTime: function() { var duration = this.getDuration(); var position = Math.min(Math.max(this.el.globoGetPosition(), 0), duration); var previousDVRStatus = this.dvrEnabled; var livePlayback = (this.playbackType === 'live'); this.dvrEnabled = (livePlayback && duration > 240); if (duration === 100 || livePlayback === undefined) { return; } if (this.dvrEnabled !== previousDVRStatus) { this.updateSettings(); this.trigger('playback:settingsupdate', this.name); } if (livePlayback && (!this.dvrEnabled || !this.dvrInUse)) { position = duration; } this.trigger('playback:timeupdate', position, duration, this.name); }, play: function() { if (this.currentState === 'PAUSED') { this.el.globoPlayerResume(); } else if (this.currentState !== "PLAYING") { this.firstPlay(); } this.trigger('playback:play', this.name); }, getPlaybackType: function() { return this.playbackType ? this.playbackType : null; }, getCurrentBitrate: function() { var currentLevel = this.getLevels()[this.el.globoGetLevel()]; return currentLevel.bitrate; }, getLastProgramDate: function() { var programDate = this.el.globoGetLastProgramDate(); return programDate - 1.08e+7; }, isHighDefinitionInUse: function() { return this.highDefinition; }, getLevels: function() { if (!this.levels || this.levels.length === 0) { this.levels = this.el.globoGetLevels(); } return this.levels; }, setPlaybackState: function(state) { var bufferLength = this.el.globoGetbufferLength(); if (state === "PLAYING_BUFFERING" && bufferLength < 1) { this.trigger('playback:buffering', this.name); this.updateCurrentState(state); } else if (state === "PLAYING") { if (_.contains(["PLAYING_BUFFERING", "PAUSED", "IDLE"], this.currentState)) { this.trigger('playback:bufferfull', this.name); this.updateCurrentState(state); } } else if (state === "PAUSED") { this.updateCurrentState(state); } else if (state === "IDLE") { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.globoGetDuration(), this.name); this.updateCurrentState(state); } this.lastBufferLength = bufferLength; }, updateCurrentState: function(state) { this.currentState = state; this.updatePlaybackType(); }, updatePlaybackType: function() { this.playbackType = this.el.globoGetType(); if (this.playbackType) { this.playbackType = this.playbackType.toLowerCase(); if (this.playbackType === 'vod') { this.startReportingProgress(); } else { this.stopReportingProgress(); } } this.trigger('playback:playbackstate'); }, startReportingProgress: function() { if (!this.reportingProgress) { this.reportingProgress = true; Mediator.on(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded); } }, stopReportingProgress: function() { Mediator.off(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded, this); }, onFragmentLoaded: function() { var buffered = this.el.globoGetPosition() + this.el.globoGetbufferLength(); this.trigger('playback:progress', this.el.globoGetPosition(), buffered, this.getDuration(), this.name); }, firstPlay: function() { this.el.globoPlayerLoad(this.src); this.el.globoPlayerPlay(); }, volume: function(value) { var $__0 = this; if (this.isReady) { this.el.globoPlayerVolume(value); } else { this.listenToOnce(this, 'playback:bufferfull', (function() { return $__0.volume(value); })); } }, pause: function() { if (this.playbackType !== 'live' || this.dvrEnabled) { this.el.globoPlayerPause(); if (this.playbackType === 'live' && this.dvrEnabled) { this.updateDvr(true); } } }, stop: function() { this.el.globoPlayerStop(); this.trigger('playback:timeupdate', 0, this.name); }, isPlaying: function() { if (this.currentState) { return !!(this.currentState.match(/playing/i)); } return false; }, getDuration: function() { var duration = this.el.globoGetDuration(); if (this.playbackType === 'live') { duration = duration - 10; } return duration; }, seek: function(time) { var duration = this.getDuration(); if (time > 0) { time = duration * time / 100; } if (this.playbackType === 'live') { var dvrInUse = (time >= 0 && duration - time > 5); if (!dvrInUse) { time = -1; } this.updateDvr(dvrInUse); } this.el.globoPlayerSeek(time); this.trigger('playback:timeupdate', time, duration, this.name); }, updateDvr: function(dvrInUse) { var previousDvrInUse = !!this.dvrInUse; this.dvrInUse = dvrInUse; if (this.dvrInUse !== previousDvrInUse) { this.updateSettings(); this.trigger('playback:dvr', this.dvrInUse); this.trigger('playback:stats:add', {'dvr': this.dvrInUse}); } }, flashPlaybackError: function() { this.trigger('playback:stop'); }, timeUpdate: function(time, duration) { this.trigger('playback:timeupdate', time, duration, this.name); }, destroy: function() { this.stopListening(); this.$el.remove(); }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-hls', ''); this.setElement($el); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId }))); }, updateSettings: function() { this.settings = _.extend({}, this.defaultSettings); if (this.playbackType === "vod" || this.dvrInUse) { this.settings.left = ["playpause", "position", "duration"]; this.settings.seekEnabled = true; } else if (this.dvrEnabled) { this.settings.left = ["playpause"]; this.settings.seekEnabled = true; } else { this.settings.seekEnabled = false; } }, setElement: function(element) { this.$el = element; this.el = element[0]; }, render: function() { var style = Styler.getStyleFor(this.name); if (Browser.isLegacyIE) { this.setupIE(); } else { this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isIE) { this.$('embed').remove(); } } this.el.id = this.cid; this.$el.append(style); return this; } }, {}, Playback); HLS.canPlay = function(resource) { return !!resource.match(/^http(.*).m3u8?/); }; module.exports = HLS; },{"../../base/jst":8,"../../base/styler":9,"browser":"browser","mediator":"mediator","playback":"playback","underscore":"underscore"}],27:[function(require,module,exports){ "use strict"; var Playback = require('playback'); var HTML5Audio = function HTML5Audio(params) { $traceurRuntime.superCall(this, $HTML5Audio.prototype, "constructor", [params]); this.el.src = params.src; this.settings = { left: ['playpause', 'position', 'duration'], right: ['fullscreen', 'volume'], default: ['seekbar'] }; this.render(); params.autoPlay && this.play(); }; var $HTML5Audio = HTML5Audio; ($traceurRuntime.createClass)(HTML5Audio, { get name() { return 'html5_audio'; }, get tagName() { return 'audio'; }, get events() { return { 'timeupdate': 'timeUpdated', 'ended': 'ended' }; }, bindEvents: function() { this.listenTo(this.container, 'container:play', this.play); this.listenTo(this.container, 'container:pause', this.pause); this.listenTo(this.container, 'container:seek', this.seek); this.listenTo(this.container, 'container:volume', this.volume); this.listenTo(this.container, 'container:stop', this.stop); }, getPlaybackType: function() { return "aod"; }, play: function() { this.el.play(); this.trigger('playback:play'); }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); this.el.currentTime = 0; }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, ended: function() { this.trigger('container:timeupdate', 0); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.el.currentTime = time; }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, isPlaying: function() { return !this.el.paused && !this.el.ended; }, timeUpdated: function() { this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name); }, render: function() { return this; } }, {}, Playback); HTML5Audio.canPlay = function(resource) { return !!resource.match(/(.*).mp3/); }; module.exports = HTML5Audio; },{"playback":"playback"}],28:[function(require,module,exports){ (function (process){ "use strict"; var Playback = require('playback'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var Browser = require('browser'); var Mousetrap = require('mousetrap'); var seekStringToSeconds = require('../../base/utils').seekStringToSeconds; var _ = require('underscore'); var HTML5Video = function HTML5Video(options) { $traceurRuntime.superCall(this, $HTML5Video.prototype, "constructor", [options]); this.options = options; this.src = options.src; this.el.src = options.src; this.el.loop = options.loop; this.firstBuffer = true; this.isHLS = (this.src.indexOf('m3u8') > -1); this.settings = {default: ['seekbar']}; if (this.isHLS) { this.el.preload = options.preload ? options.preload : 'none'; this.settings.left = ["playstop"]; this.settings.right = ["fullscreen", "volume"]; } else { this.el.preload = options.preload ? options.preload : 'metadata'; this.settings.left = ["playpause", "position", "duration"]; this.settings.right = ["fullscreen", "volume"]; this.settings.seekEnabled = true; } this.bindEvents(); }; var $HTML5Video = HTML5Video; ($traceurRuntime.createClass)(HTML5Video, { get name() { return 'html5_video'; }, get tagName() { return 'video'; }, get template() { return JST.html5_video; }, get attributes() { return {'data-html5-video': ''}; }, get events() { return { 'timeupdate': 'timeUpdated', 'progress': 'progress', 'ended': 'ended', 'stalled': 'stalled', 'waiting': 'waiting', 'canplaythrough': 'bufferFull', 'loadedmetadata': 'loadedMetadata' }; }, bindEvents: function() { _.each(_.range(1, 10), function(i) { var $__0 = this; Mousetrap.bind([i.toString()], (function() { return $__0.seek(i * 10); })); }.bind(this)); }, loadedMetadata: function(e) { this.trigger('playback:loadedmetadata', e.target.duration); this.trigger('playback:settingsupdate'); this.checkInitialSeek(); }, getPlaybackType: function() { return this.isHLS && _.contains([0, undefined, Infinity], this.el.duration) ? 'live' : 'vod'; }, isHighDefinitionInUse: function() { return false; }, play: function() { this.el.play(); this.trigger('playback:play'); if (this.isHLS) { this.trigger('playback:timeupdate', 1, 1, this.name); } }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); if (this.el.readyState !== 0) { this.el.currentTime = 0; } }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, isPlaying: function() { return !this.el.paused && !this.el.ended; }, ended: function() { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.duration, this.name); }, stalled: function() { if (this.getPlaybackType() === 'vod' && this.el.readyState < this.el.HAVE_FUTURE_DATA) { this.trigger('playback:buffering', this.name); } }, waiting: function() { if (this.el.readyState < this.el.HAVE_FUTURE_DATA) { this.trigger('playback:buffering', this.name); } }, bufferFull: function() { if (this.options.poster && this.firstBuffer) { this.firstBuffer = false; this.el.poster = this.options.poster; } else { this.el.poster = ''; } this.trigger('playback:bufferfull', this.name); }, destroy: function() { this.stop(); this.el.src = ''; this.$el.remove(); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.seekSeconds(time); }, seekSeconds: function(time) { this.el.currentTime = time; }, checkInitialSeek: function() { var seekTime = seekStringToSeconds(window.location.href); this.seekSeconds(seekTime); }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, timeUpdated: function() { if (this.getPlaybackType() !== 'live') { this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name); } }, progress: function() { if (!this.el.buffered.length) return; var bufferedPos = 0; for (var i = 0; i < this.el.buffered.length; i++) { if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) { bufferedPos = i; break; } } this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name); }, typeFor: function(src) { return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4'; }, render: function() { var $__0 = this; var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ src: this.src, type: this.typeFor(this.src) })); this.$el.append(style); this.trigger('playback:ready', this.name); process.nextTick((function() { return $__0.options.autoPlay && $__0.play(); })); return this; } }, {}, Playback); HTML5Video.canPlay = function(resource) { if (isSupportedBrowser()) { return true; } else if (Browser.isChrome || Browser.isFirefox || Browser.isIE) { return (!!resource.match(/(.*).(mp4|webm)/)); } }; var isSupportedBrowser = (function() { return Browser.isSafari || Browser.isMobile || Browser.isWin8App || Browser.isLegacyIE || Browser.isWiiU || Browser.isPS4; }); module.exports = HTML5Video; }).call(this,require('_process')) },{"../../base/jst":8,"../../base/styler":9,"../../base/utils":10,"_process":2,"browser":"browser","mousetrap":4,"playback":"playback","underscore":"underscore"}],29:[function(require,module,exports){ "use strict"; module.exports = require('./no_op'); },{"./no_op":30}],30:[function(require,module,exports){ "use strict"; var Playback = require('playback'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var NoOp = function NoOp(options) { $traceurRuntime.superCall(this, $NoOp.prototype, "constructor", [options]); }; var $NoOp = NoOp; ($traceurRuntime.createClass)(NoOp, { get name() { return 'no_op'; }, get template() { return JST.no_op; }, get attributes() { return {'data-no-op': ''}; }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); return this; } }, {}, Playback); NoOp.canPlay = (function(source) { return true; }); module.exports = NoOp; },{"../../base/jst":8,"../../base/styler":9,"playback":"playback"}],31:[function(require,module,exports){ (function (process){ "use strict"; var UICorePlugin = require('ui_core_plugin'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var Browser = require('browser'); var Mediator = require('mediator'); var PlayerInfo = require('player_info'); var BackgroundButton = function BackgroundButton(core) { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "constructor", [core]); this.core = core; this.settingsUpdate(); }; var $BackgroundButton = BackgroundButton; ($traceurRuntime.createClass)(BackgroundButton, { get template() { return JST.background_button; }, get name() { return 'background_button'; }, get attributes() { return { 'class': 'background-button', 'data-background-button': '' }; }, get events() { return {'click .background-button-icon': 'click'}; }, bindEvents: function() { this.listenTo(this.core.mediaControl.container, 'container:state:buffering', this.hide); this.listenTo(this.core.mediaControl.container, 'container:state:bufferfull', this.show); this.listenTo(this.core.mediaControl, 'mediacontrol:rendered', this.settingsUpdate); this.listenTo(this.core.mediaControl, 'mediacontrol:show', this.updateSize); this.listenTo(this.core.mediaControl, 'mediacontrol:playing', this.playing); this.listenTo(this.core.mediaControl, 'mediacontrol:notplaying', this.notplaying); Mediator.on('player:resize', this.updateSize, this); }, stopListening: function() { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "stopListening", []); Mediator.off('player:resize', this.updateSize, this); }, settingsUpdate: function() { this.stopListening(); if (this.shouldRender()) { this.render(); this.bindEvents(); if (this.core.mediaControl.container.isPlaying()) { this.playing(); } else { this.notplaying(); } } else { this.$el.remove(); this.$playPauseButton.show(); this.$playStopButton.show(); this.listenTo(this.core.mediaControl.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.core.mediaControl.container, 'container:dvr', this.settingsUpdate); this.listenTo(this.core.mediaControl, 'mediacontrol:containerchanged', this.settingsUpdate); } }, shouldRender: function() { var useBackgroundButton = (this.core.options.useBackgroundButton === undefined && Browser.isMobile) || !!this.core.options.useBackgroundButton; return useBackgroundButton && (this.core.mediaControl.$el.find('[data-playstop]').length > 0 || this.core.mediaControl.$el.find('[data-playpause]').length > 0); }, click: function() { this.core.mediaControl.show(); if (this.shouldStop) { this.core.mediaControl.togglePlayStop(); } else { this.core.mediaControl.togglePlayPause(); } }, show: function() { this.$el.removeClass('hide'); }, hide: function() { this.$el.addClass('hide'); }, enable: function() { this.stopListening(); $traceurRuntime.superCall(this, $BackgroundButton.prototype, "enable", []); this.settingsUpdate(); }, disable: function() { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "disable", []); this.$playPauseButton.show(); this.$playStopButton.show(); }, playing: function() { this.$buttonIcon.removeClass('notplaying').addClass('playing'); }, notplaying: function() { this.$buttonIcon.removeClass('playing').addClass('notplaying'); }, getExternalInterface: function() {}, updateSize: function() { if (!this.$el) return; var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height(); this.$el.css({fontSize: height}); this.$buttonWrapper.css({marginTop: -(this.$buttonWrapper.height() / 2)}); }, render: function() { var $__0 = this; var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.$playPauseButton = this.core.mediaControl.$el.find('[data-playpause]'); this.$playStopButton = this.core.mediaControl.$el.find('[data-playstop]'); this.$buttonWrapper = this.$el.find('.background-button-wrapper[data-background-button]'); this.$buttonIcon = this.$el.find('.background-button-icon[data-background-button]'); this.shouldStop = this.$playStopButton.length > 0; this.$el.insertBefore(this.core.mediaControl.$el.find('.media-control-layer[data-controls]')); this.$el.click((function() { return $__0.click($__0.$el); })); process.nextTick((function() { return $__0.updateSize(); })); if (this.core.options.useBackgroundButton) { this.$playPauseButton.hide(); this.$playStopButton.hide(); } if (this.shouldStop) { this.$buttonIcon.addClass('playstop'); } if (this.core.mediaControl.isVisible()) { this.show(); } return this; } }, {}, UICorePlugin); module.exports = BackgroundButton; }).call(this,require('_process')) },{"../../base/jst":8,"../../base/styler":9,"_process":2,"browser":"browser","mediator":"mediator","player_info":"player_info","ui_core_plugin":"ui_core_plugin"}],32:[function(require,module,exports){ "use strict"; module.exports = require('./background_button'); },{"./background_button":31}],33:[function(require,module,exports){ "use strict"; var ContainerPlugin = require('container_plugin'); var ClickToPausePlugin = function ClickToPausePlugin() { $traceurRuntime.defaultSuperCall(this, $ClickToPausePlugin.prototype, arguments); }; var $ClickToPausePlugin = ClickToPausePlugin; ($traceurRuntime.createClass)(ClickToPausePlugin, { get name() { return 'click_to_pause'; }, bindEvents: function() { this.listenTo(this.container, 'container:click', this.click); this.listenTo(this.container, 'container:settingsupdate', this.settingsUpdate); }, click: function() { if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) { if (this.container.isPlaying()) { this.container.pause(); } else { this.container.play(); } } }, settingsUpdate: function() { this.container.$el.removeClass('pointer-enabled'); if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) { this.container.$el.addClass('pointer-enabled'); } } }, {}, ContainerPlugin); module.exports = ClickToPausePlugin; },{"container_plugin":"container_plugin"}],34:[function(require,module,exports){ "use strict"; module.exports = require('./click_to_pause'); },{"./click_to_pause":33}],35:[function(require,module,exports){ "use strict"; var UICorePlugin = require('ui_core_plugin'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var DVRControls = function DVRControls(core) { $traceurRuntime.superCall(this, $DVRControls.prototype, "constructor", [core]); this.core = core; this.settingsUpdate(); }; var $DVRControls = DVRControls; ($traceurRuntime.createClass)(DVRControls, { get template() { return JST.dvr_controls; }, get name() { return 'dvr_controls'; }, get events() { return {'click .live-button': 'click'}; }, get attributes() { return { 'class': 'dvr-controls', 'data-dvr-controls': '' }; }, bindEvents: function() { this.listenTo(this.core.mediaControl, 'mediacontrol:rendered', this.settingsUpdate); this.listenTo(this.core.mediaControl.container, 'container:dvr', this.dvrChanged); }, dvrChanged: function(dvrEnabled) { this.settingsUpdate(); this.core.mediaControl.$el.addClass('live'); if (dvrEnabled) { this.core.mediaControl.$el.addClass('dvr'); this.core.mediaControl.$el.find('.media-control-indicator[data-position], .media-control-indicator[data-duration]').hide(); } else { this.core.mediaControl.$el.removeClass('dvr'); } }, click: function() { if (!this.core.mediaControl.container.isPlaying()) { this.core.mediaControl.container.play(); } if (this.core.mediaControl.$el.hasClass('dvr')) { this.core.mediaControl.container.setCurrentTime(-1); } }, settingsUpdate: function() { var $__0 = this; this.stopListening(); if (this.shouldRender()) { this.render(); this.$el.click((function() { return $__0.click(); })); } this.bindEvents(); }, shouldRender: function() { var useDvrControls = this.core.options.useDvrControls === undefined || !!this.core.options.useDvrControls; return useDvrControls && this.core.mediaControl.container.getPlaybackType() === 'live'; }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); if (this.shouldRender()) { this.core.mediaControl.$el.addClass('live'); this.core.mediaControl.$('.media-control-left-panel[data-media-control]').append(this.$el); if (this.$duration) { this.$duration.remove(); } this.$duration = $('<span data-duration></span>'); this.core.mediaControl.seekTime.$el.append(this.$duration); } return this; } }, {}, UICorePlugin); module.exports = DVRControls; },{"../../base/jst":8,"../../base/styler":9,"ui_core_plugin":"ui_core_plugin"}],36:[function(require,module,exports){ "use strict"; module.exports = require('./dvr_controls'); },{"./dvr_controls":35}],37:[function(require,module,exports){ "use strict"; var ContainerPlugin = require('container_plugin'); var GoogleAnalytics = function GoogleAnalytics(options) { $traceurRuntime.superCall(this, $GoogleAnalytics.prototype, "constructor", [options]); if (options.gaAccount) { this.embedScript(); this.account = options.gaAccount; this.trackerName = options.gaTrackerName + "." || 'Clappr.'; this.currentHDState = undefined; } }; var $GoogleAnalytics = GoogleAnalytics; ($traceurRuntime.createClass)(GoogleAnalytics, { get name() { return 'google_analytics'; }, embedScript: function() { var $__0 = this; if (!window._gat) { var script = document.createElement('script'); script.setAttribute("type", "text/javascript"); script.setAttribute("async", "async"); script.setAttribute("src", "http://www.google-analytics.com/ga.js"); script.onload = (function() { return $__0.addEventListeners(); }); document.body.appendChild(script); } else { this.addEventListeners(); } }, addEventListeners: function() { var $__0 = this; this.listenTo(this.container, 'container:play', this.onPlay); this.listenTo(this.container, 'container:pause', this.onPause); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:ended', this.onEnded); this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:error', this.onError); this.listenTo(this.container, 'container:playbackstate', this.onPlaybackChanged); this.listenTo(this.container, 'container:volume', (function(event) { return $__0.onVolumeChanged(event); })); this.listenTo(this.container, 'container:seek', (function(event) { return $__0.onSeek(event); })); this.listenTo(this.container, 'container:fullscreen', this.onFullscreen); this.listenTo(this.container, 'container:highdefinitionupdate', this.onHD); this.listenTo(this.container.playback, 'playback:dvr', this.onDVR); _gaq.push([this.trackerName + '_setAccount', this.account]); }, onPlay: function() { this.push(["Video", "Play", this.container.playback.src]); }, onStop: function() { this.push(["Video", "Stop", this.container.playback.src]); }, onEnded: function() { this.push(["Video", "Ended", this.container.playback.src]); }, onBuffering: function() { this.push(["Video", "Buffering", this.container.playback.src]); }, onBufferFull: function() { this.push(["Video", "Bufferfull", this.container.playback.src]); }, onError: function() { this.push(["Video", "Error", this.container.playback.src]); }, onHD: function() { var status = this.container.isHighDefinitionInUse() ? "ON" : "OFF"; if (status !== this.currentHDState) { this.currentHDState = status; this.push(["Video", "HD - " + status, this.container.playback.src]); } }, onPlaybackChanged: function() { var type = this.container.getPlaybackType(); if (type !== null) { this.push(["Video", "Playback Type - " + type, this.container.playback.src]); } }, onDVR: function() { var status = this.container.isHighDefinitionInUse(); this.push(["Interaction", "DVR - " + status, this.container.playback.src]); }, onPause: function() { this.push(["Video", "Pause", this.container.playback.src]); }, onSeek: function() { this.push(["Video", "Seek", this.container.playback.src]); }, onVolumeChanged: function() { this.push(["Interaction", "Volume", this.container.playback.src]); }, onFullscreen: function() { this.push(["Interaction", "Fullscreen", this.container.playback.src]); }, push: function(array) { var res = [this.trackerName + "_trackEvent"].concat(array); _gaq.push(res); } }, {}, ContainerPlugin); module.exports = GoogleAnalytics; },{"container_plugin":"container_plugin"}],38:[function(require,module,exports){ "use strict"; module.exports = require('./google_analytics'); },{"./google_analytics":37}],39:[function(require,module,exports){ "use strict"; module.exports = require('./log'); },{"./log":40}],40:[function(require,module,exports){ "use strict"; var Mousetrap = require('mousetrap'); var _ = require('underscore'); var Log = function Log() { var $__0 = this; Mousetrap.bind(['ctrl+shift+d'], (function() { return $__0.onOff(); })); this.BLACKLIST = ['playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress']; }; ($traceurRuntime.createClass)(Log, { info: function(klass, message) { this.log(klass, 'info', message); }, warn: function(klass, message) { this.log(klass, 'warn', message); }, debug: function(klass, message) { this.log(klass, 'debug', message); }, onOff: function() { window.DEBUG = !window.DEBUG; if (window.DEBUG) { console.log('log enabled'); } else { console.log('log disabled'); } }, log: function(klass, level, message) { if (!window.DEBUG || _.contains(this.BLACKLIST, message)) return; var color; if (level === 'warn') { color = '#FF8000'; } else if (level === 'info') { color = '#006600'; } else if (level === 'error') { color = '#FF0000'; } console.log("%c [" + klass + "] [" + level + "] " + message, 'color: ' + color); } }, {}); Log.getInstance = function() { if (this._instance === undefined) { this._instance = new this(); } return this._instance; }; module.exports = Log; },{"mousetrap":4,"underscore":"underscore"}],41:[function(require,module,exports){ (function (process){ "use strict"; var UIContainerPlugin = require('ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Mediator = require('mediator'); var PlayerInfo = require('player_info'); var $ = require('zepto'); var _ = require('underscore'); var PosterPlugin = function PosterPlugin(options) { $traceurRuntime.superCall(this, $PosterPlugin.prototype, "constructor", [options]); this.options = options; _.defaults(this.options, {disableControlsOnPoster: true}); if (this.options.disableControlsOnPoster) { this.container.disableMediaControl(); } this.render(); }; var $PosterPlugin = PosterPlugin; ($traceurRuntime.createClass)(PosterPlugin, { get name() { return 'poster'; }, get template() { return JST.poster; }, get attributes() { return { 'class': 'player-poster', 'data-poster': '' }; }, get events() { return {'click': 'clicked'}; }, bindEvents: function() { this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferfull); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:ended', this.onStop); Mediator.on('player:resize', this.updateSize, this); }, stopListening: function() { $traceurRuntime.superCall(this, $PosterPlugin.prototype, "stopListening", []); Mediator.off('player:resize', this.updateSize, this); }, onBuffering: function() { this.hidePlayButton(); }, onBufferfull: function() { this.$el.hide(); if (this.options.disableControlsOnPoster) { this.container.enableMediaControl(); } }, onStop: function() { this.$el.show(); if (this.options.disableControlsOnPoster) { this.container.disableMediaControl(); } if (!this.options.hidePlayButton) { this.showPlayButton(); } }, hidePlayButton: function() { this.$playButton.hide(); }, showPlayButton: function() { this.$playButton.show(); this.updateSize(); }, clicked: function() { this.container.play(); return false; }, updateSize: function() { if (!this.$el) return; var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height(); this.$el.css({fontSize: height}); if (this.$playWrapper.is(':visible')) { this.$playWrapper.css({marginTop: -(this.$playWrapper.height() / 2)}); if (!this.options.hidePlayButton) { this.$playButton.show(); } } else { this.$playButton.hide(); } }, render: function() { var $__0 = this; var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.$playButton = this.$el.find('.poster-icon'); this.$playWrapper = this.$el.find('.play-wrapper'); if (this.options.poster !== undefined) { var imgEl = $('<img data-poster class="poster-background"></img>'); imgEl.attr('src', this.options.poster); this.$el.prepend(imgEl); } this.container.$el.append(this.el); if (!!this.options.hidePlayButton) { this.hidePlayButton(); } process.nextTick((function() { return $__0.updateSize(); })); return this; } }, {}, UIContainerPlugin); module.exports = PosterPlugin; }).call(this,require('_process')) },{"../../base/jst":8,"../../base/styler":9,"_process":2,"mediator":"mediator","player_info":"player_info","ui_container_plugin":"ui_container_plugin","underscore":"underscore","zepto":"zepto"}],42:[function(require,module,exports){ "use strict"; module.exports = require('./spinner_three_bounce'); },{"./spinner_three_bounce":43}],43:[function(require,module,exports){ "use strict"; var UIContainerPlugin = require('ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) { $traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, "constructor", [options]); this.template = JST.spinner_three_bounce; this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:stop', this.onStop); this.render(); }; var $SpinnerThreeBouncePlugin = SpinnerThreeBouncePlugin; ($traceurRuntime.createClass)(SpinnerThreeBouncePlugin, { get name() { return 'spinner'; }, get attributes() { return { 'data-spinner': '', 'class': 'spinner-three-bounce' }; }, onBuffering: function() { this.$el.show(); }, onBufferFull: function() { this.$el.hide(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.html(this.template()); var style = Styler.getStyleFor('spinner_three_bounce'); this.container.$el.append(style); this.container.$el.append(this.$el); this.$el.hide(); return this; } }, {}, UIContainerPlugin); module.exports = SpinnerThreeBouncePlugin; },{"../../base/jst":8,"../../base/styler":9,"ui_container_plugin":"ui_container_plugin"}],44:[function(require,module,exports){ "use strict"; module.exports = require('./stats'); },{"./stats":45}],45:[function(require,module,exports){ "use strict"; var ContainerPlugin = require('container_plugin'); var $ = require("zepto"); var StatsPlugin = function StatsPlugin(options) { $traceurRuntime.superCall(this, $StatsPlugin.prototype, "constructor", [options]); this.setInitialAttrs(); this.reportInterval = options.reportInterval || 5000; this.state = "IDLE"; }; var $StatsPlugin = StatsPlugin; ($traceurRuntime.createClass)(StatsPlugin, { get name() { return 'stats'; }, bindEvents: function() { this.listenTo(this.container.playback, 'playback:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:destroyed', this.onStop); this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:stats:add', this.onStatsAdd); this.listenTo(this.container, 'container:bitrate', this.onStatsAdd); this.listenTo(this.container.playback, 'playback:stats:add', this.onStatsAdd); }, setInitialAttrs: function() { this.firstPlay = true; this.startupTime = 0; this.rebufferingTime = 0; this.watchingTime = 0; this.rebuffers = 0; this.externalMetrics = {}; }, onPlay: function() { this.state = "PLAYING"; this.watchingTimeInit = Date.now(); if (!this.intervalId) { this.intervalId = setInterval(this.report.bind(this), this.reportInterval); } }, onStop: function() { clearInterval(this.intervalId); this.intervalId = undefined; this.state = "STOPPED"; }, onBuffering: function() { if (this.firstPlay) { this.startupTimeInit = Date.now(); } else { this.rebufferingTimeInit = Date.now(); } this.state = "BUFFERING"; this.rebuffers++; }, onBufferFull: function() { if (this.firstPlay && !!this.startupTimeInit) { this.firstPlay = false; this.startupTime = Date.now() - this.startupTimeInit; this.watchingTimeInit = Date.now(); } else if (!!this.rebufferingTimeInit) { this.rebufferingTime += this.getRebufferingTime(); } this.rebufferingTimeInit = undefined; this.state = "PLAYING"; }, getRebufferingTime: function() { return Date.now() - this.rebufferingTimeInit; }, getWatchingTime: function() { var totalTime = (Date.now() - this.watchingTimeInit); return totalTime - this.rebufferingTime; }, isRebuffering: function() { return !!this.rebufferingTimeInit; }, onStatsAdd: function(metric) { $.extend(this.externalMetrics, metric); }, getStats: function() { var metrics = { startupTime: this.startupTime, rebuffers: this.rebuffers, rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime, watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime() }; $.extend(metrics, this.externalMetrics); return metrics; }, report: function() { this.container.statsReport(this.getStats()); } }, {}, ContainerPlugin); module.exports = StatsPlugin; },{"container_plugin":"container_plugin","zepto":"zepto"}],46:[function(require,module,exports){ "use strict"; module.exports = require('./watermark'); },{"./watermark":47}],47:[function(require,module,exports){ "use strict"; var UIContainerPlugin = require('ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var WaterMarkPlugin = function WaterMarkPlugin(options) { $traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, "constructor", [options]); this.template = JST[this.name]; this.position = options.position || "bottom-right"; if (options.watermark) { this.imageUrl = options.watermark; this.render(); } else { this.$el.remove(); } }; var $WaterMarkPlugin = WaterMarkPlugin; ($traceurRuntime.createClass)(WaterMarkPlugin, { get name() { return 'watermark'; }, bindEvents: function() { this.listenTo(this.container, 'container:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); }, onPlay: function() { if (!this.hidden) this.$el.show(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.hide(); var templateOptions = { position: this.position, imageUrl: this.imageUrl }; this.$el.html(this.template(templateOptions)); var style = Styler.getStyleFor(this.name); this.container.$el.append(style); this.container.$el.append(this.$el); return this; } }, {}, UIContainerPlugin); module.exports = WaterMarkPlugin; },{"../../base/jst":8,"../../base/styler":9,"ui_container_plugin":"ui_container_plugin"}],"base_object":[function(require,module,exports){ "use strict"; var _ = require('underscore'); var extend = require('./utils').extend; var Events = require('./events'); var pluginOptions = ['container']; var BaseObject = function BaseObject(options) { this.uniqueId = _.uniqueId('o'); options || (options = {}); _.extend(this, _.pick(options, pluginOptions)); }; ($traceurRuntime.createClass)(BaseObject, {}, {}, Events); BaseObject.extend = extend; module.exports = BaseObject; },{"./events":7,"./utils":10,"underscore":"underscore"}],"browser":[function(require,module,exports){ "use strict"; var Browser = function Browser() {}; ($traceurRuntime.createClass)(Browser, {}, {}); Browser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1); Browser.isChrome = !!(navigator.userAgent.match(/chrome/i)); Browser.isFirefox = !!(navigator.userAgent.match(/firefox/i)); Browser.isLegacyIE = !!(window.ActiveXObject); Browser.isIE = Browser.isLegacyIE || !!(navigator.userAgent.match(/trident.*rv:1\d/i)); Browser.isIE11 = !!(navigator.userAgent.match(/trident.*rv:11/i)); Browser.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Opera Mini/i.test(navigator.userAgent)); Browser.isWin8App = !!(/MSAppHost/i.test(navigator.userAgent)); Browser.isWiiU = !!(/WiiU/i.test(navigator.userAgent)); Browser.isPS4 = !!(/PlayStation 4/i.test(navigator.userAgent)); module.exports = Browser; },{}],"container_plugin":[function(require,module,exports){ "use strict"; var BaseObject = require('base_object'); var ContainerPlugin = function ContainerPlugin(options) { $traceurRuntime.superCall(this, $ContainerPlugin.prototype, "constructor", [options]); this.bindEvents(); }; var $ContainerPlugin = ContainerPlugin; ($traceurRuntime.createClass)(ContainerPlugin, { enable: function() { this.bindEvents(); }, disable: function() { this.stopListening(); }, bindEvents: function() {}, destroy: function() { this.stopListening(); } }, {}, BaseObject); module.exports = ContainerPlugin; },{"base_object":"base_object"}],"container":[function(require,module,exports){ "use strict"; module.exports = require('./container'); },{"./container":11}],"core_plugin":[function(require,module,exports){ "use strict"; var BaseObject = require('base_object'); var CorePlugin = function CorePlugin(core) { $traceurRuntime.superCall(this, $CorePlugin.prototype, "constructor", [core]); this.core = core; }; var $CorePlugin = CorePlugin; ($traceurRuntime.createClass)(CorePlugin, { getExternalInterface: function() { return {}; }, destroy: function() {} }, {}, BaseObject); module.exports = CorePlugin; },{"base_object":"base_object"}],"core":[function(require,module,exports){ "use strict"; module.exports = require('./core'); },{"./core":14}],"flash":[function(require,module,exports){ "use strict"; module.exports = require('./flash'); },{"./flash":25}],"hls":[function(require,module,exports){ "use strict"; module.exports = require('./hls'); },{"./hls":26}],"html5_audio":[function(require,module,exports){ "use strict"; module.exports = require('./html5_audio'); },{"./html5_audio":27}],"html5_video":[function(require,module,exports){ "use strict"; module.exports = require('./html5_video'); },{"./html5_video":28}],"media_control":[function(require,module,exports){ "use strict"; module.exports = require('./media_control'); },{"./media_control":21}],"mediator":[function(require,module,exports){ "use strict"; var Events = require('../base/events'); var events = new Events(); var Mediator = function Mediator() {}; ($traceurRuntime.createClass)(Mediator, {}, {}); Mediator.on = function(name, callback, context) { events.on(name, callback, context); return; }; Mediator.once = function(name, callback, context) { events.once(name, callback, context); return; }; Mediator.off = function(name, callback, context) { events.off(name, callback, context); return; }; Mediator.trigger = function(name, opts) { events.trigger(name, opts); return; }; Mediator.stopListening = function(obj, name, callback) { events.stopListening(obj, name, callback); return; }; module.exports = Mediator; },{"../base/events":7}],"playback":[function(require,module,exports){ "use strict"; var UIObject = require('ui_object'); var Playback = function Playback(options) { $traceurRuntime.superCall(this, $Playback.prototype, "constructor", [options]); this.settings = {}; }; var $Playback = Playback; ($traceurRuntime.createClass)(Playback, { play: function() {}, pause: function() {}, stop: function() {}, seek: function(time) {}, getDuration: function() { return 0; }, isPlaying: function() { return false; }, getPlaybackType: function() { return 'no_op'; }, isHighDefinitionInUse: function() { return false; }, volume: function(value) {}, destroy: function() { this.$el.remove(); } }, {}, UIObject); Playback.canPlay = (function(source) { return false; }); module.exports = Playback; },{"ui_object":"ui_object"}],"player_info":[function(require,module,exports){ "use strict"; var PlayerInfo = { options: {}, playbackPlugins: [], currentSize: { width: 0, height: 0 } }; module.exports = PlayerInfo; },{}],"poster":[function(require,module,exports){ "use strict"; module.exports = require('./poster'); },{"./poster":41}],"ui_container_plugin":[function(require,module,exports){ "use strict"; var UIObject = require('ui_object'); var UIContainerPlugin = function UIContainerPlugin(options) { $traceurRuntime.superCall(this, $UIContainerPlugin.prototype, "constructor", [options]); this.enabled = true; this.bindEvents(); }; var $UIContainerPlugin = UIContainerPlugin; ($traceurRuntime.createClass)(UIContainerPlugin, { enable: function() { this.bindEvents(); this.$el.show(); this.enabled = true; }, disable: function() { this.stopListening(); this.$el.hide(); this.enabled = false; }, bindEvents: function() {}, destroy: function() { this.remove(); } }, {}, UIObject); module.exports = UIContainerPlugin; },{"ui_object":"ui_object"}],"ui_core_plugin":[function(require,module,exports){ "use strict"; var UIObject = require('ui_object'); var UICorePlugin = function UICorePlugin(core) { $traceurRuntime.superCall(this, $UICorePlugin.prototype, "constructor", [core]); this.core = core; this.enabled = true; this.bindEvents(); this.render(); }; var $UICorePlugin = UICorePlugin; ($traceurRuntime.createClass)(UICorePlugin, { bindEvents: function() {}, getExternalInterface: function() { return {}; }, enable: function() { this.bindEvents(); this.$el.show(); this.enabled = true; }, disable: function() { this.stopListening(); this.$el.hide(); this.enabled = false; }, destroy: function() { this.remove(); }, render: function() { this.$el.html(this.template()); this.$el.append(this.styler.getStyleFor(this.name)); this.core.$el.append(this.el); return this; } }, {}, UIObject); module.exports = UICorePlugin; },{"ui_object":"ui_object"}],"ui_object":[function(require,module,exports){ "use strict"; var $ = require('zepto'); var _ = require('underscore'); var extend = require('./utils').extend; var BaseObject = require('base_object'); var delegateEventSplitter = /^(\S+)\s*(.*)$/; var UIObject = function UIObject(options) { $traceurRuntime.superCall(this, $UIObject.prototype, "constructor", [options]); this.cid = _.uniqueId('c'); this._ensureElement(); this.delegateEvents(); }; var $UIObject = UIObject; ($traceurRuntime.createClass)(UIObject, { get tagName() { return 'div'; }, $: function(selector) { return this.$el.find(selector); }, render: function() { return this; }, remove: function() { this.$el.remove(); this.stopListening(); return this; }, setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof $ ? element : $(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }, {}, BaseObject); UIObject.extend = extend; module.exports = UIObject; },{"./utils":10,"base_object":"base_object","underscore":"underscore","zepto":"zepto"}],"underscore":[function(require,module,exports){ // Underscore.js 1.7.0 // http://underscorejs.org // (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.7.0'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. var createCallback = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; case 2: return function(value, other) { return func.call(context, value, other); }; case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; // A mostly-internal function to generate callbacks that can be applied // to each element in a collection, returning the desired result — either // identity, an arbitrary callback, a property matcher, or a property accessor. _.iteratee = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return createCallback(value, context, argCount); if (_.isObject(value)) return _.matches(value); return _.property(value); }; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. _.each = _.forEach = function(obj, iteratee, context) { if (obj == null) return obj; iteratee = createCallback(iteratee, context); var i, length = obj.length; if (length === +length) { for (i = 0; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { if (obj == null) return []; iteratee = _.iteratee(iteratee, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, results = Array(length), currentKey; for (var index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index = 0, currentKey; if (arguments.length < 3) { if (!length) throw new TypeError(reduceError); memo = obj[keys ? keys[index++] : index++]; } for (; index < length; index++) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== + obj.length && _.keys(obj), index = (keys || obj).length, currentKey; if (arguments.length < 3) { if (!index) throw new TypeError(reduceError); memo = obj[keys ? keys[--index] : --index]; } while (index--) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var result; predicate = _.iteratee(predicate, context); _.some(obj, function(value, index, list) { if (predicate(value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; if (obj == null) return results; predicate = _.iteratee(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(_.iteratee(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { if (obj == null) return true; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { if (obj == null) return false; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (obj.length !== +obj.length) obj = _.values(obj); return _.indexOf(obj, target) >= 0; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matches(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matches(attrs)); }; // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value < result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Shuffle a collection, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var set = obj && obj.length === +obj.length ? obj : _.values(obj); var length = set.length; var shuffled = Array(length); for (var index = 0, rand; index < length; index++) { rand = _.random(0, index); if (rand !== index) shuffled[index] = shuffled[rand]; shuffled[rand] = set[index]; } return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (obj.length !== +obj.length) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { iteratee = _.iteratee(iteratee, context); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iteratee(value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iteratee, context) { var result = {}; iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { iteratee = _.iteratee(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = array.length; while (low < high) { var mid = low + high >>> 1; if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return obj.length === +obj.length ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(obj, predicate, context) { predicate = _.iteratee(predicate, context); var pass = [], fail = []; _.each(obj, function(value, key, obj) { (predicate(value, key, obj) ? pass : fail).push(value); }); return [pass, fail]; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; if (n < 0) return []; return slice.call(array, 0, n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return slice.call(array, Math.max(array.length - n, 0)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, output) { if (shallow && _.every(input, _.isArray)) { return concat.apply(output, input); } for (var i = 0, length = input.length; i < length; i++) { var value = input[i]; if (!_.isArray(value) && !_.isArguments(value)) { if (!strict) output.push(value); } else if (shallow) { push.apply(output, value); } else { flatten(value, shallow, strict, output); } } return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (array == null) return []; if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = _.iteratee(iteratee, context); var result = []; var seen = []; for (var i = 0, length = array.length; i < length; i++) { var value = array[i]; if (isSorted) { if (!i || seen !== value) result.push(value); seen = value; } else if (iteratee) { var computed = iteratee(value, i, array); if (_.indexOf(seen, computed) < 0) { seen.push(computed); result.push(value); } } else if (_.indexOf(result, value) < 0) { result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(flatten(arguments, true, true, [])); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { if (array == null) return []; var result = []; var argsLength = arguments.length; for (var i = 0, length = array.length; i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; for (var j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = flatten(slice.call(arguments, 1), true, true, []); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function(array) { if (array == null) return []; var length = _.max(arguments, 'length').length; var results = Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(arguments, i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, length = list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted; } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } for (; i < length; i++) if (array[i] === item) return i; return -1; }; _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var idx = array.length; if (typeof from == 'number') { idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1); } while (--idx >= 0) if (array[idx] === item) return idx; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = step || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var Ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { var args, bound; if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); args = slice.call(arguments, 2); bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); Ctor.prototype = func.prototype; var self = new Ctor; Ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (_.isObject(result)) return result; return self; }; return bound; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. _.partial = function(func) { var boundArgs = slice.call(arguments, 1); return function() { var position = 0; var args = boundArgs.slice(); for (var i = 0, length = args.length; i < length; i++) { if (args[i] === _) args[i] = arguments[position++]; } while (position < arguments.length) args.push(arguments[position++]); return func.apply(this, args); }; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = function(obj) { var i, length = arguments.length, key; if (length <= 1) throw new Error('bindAll must be passed function names'); for (i = 1; i < length; i++) { key = arguments[i]; obj[key] = _.bind(obj[key], obj); } return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = hasher ? hasher.apply(this, arguments) : key; if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait && last > 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed before being called N times. _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } else { func = null; } return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { if (!_.isObject(obj)) return obj; var source, prop; for (var i = 1, length = arguments.length; i < length; i++) { source = arguments[i]; for (prop in source) { if (hasOwnProperty.call(source, prop)) { obj[prop] = source[prop]; } } } return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj, iteratee, context) { var result = {}, key; if (obj == null) return result; if (_.isFunction(iteratee)) { iteratee = createCallback(iteratee, context); for (key in obj) { var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } } else { var keys = concat.apply([], slice.call(arguments, 1)); obj = new Object(obj); for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (key in obj) result[key] = obj[key]; } } return result; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj, iteratee, context) { if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); } else { var keys = _.map(concat.apply([], slice.call(arguments, 1)), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }; // Fill in a given object with default properties. _.defaults = function(obj) { if (!_.isObject(obj)) return obj; for (var i = 1, length = arguments.length; i < length; i++) { var source = arguments[i]; for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if ( aCtor !== bCtor && // Handle Object.create(x) cases 'constructor' in a && 'constructor' in b && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) ) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size, result; // Recursively compare objects and arrays. if (className === '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size === b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Deep compare objects. var keys = _.keys(a), key; size = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. result = _.keys(b).length === size; if (result) { while (size--) { // Deep compare each member key = keys[size]; if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around an IE 11 bug. if (typeof /./ !== 'function') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = function(key) { return function(obj) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of `key:value` pairs. _.matches = function(attrs) { var pairs = _.pairs(attrs), length = pairs.length; return function(obj) { if (obj == null) return !length; obj = new Object(obj); for (var i = 0; i < length; i++) { var pair = pairs[i], key = pair[0]; if (pair[1] !== obj[key] || !(key in obj)) return false; } return true; }; }; // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = createCallback(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property) { if (object == null) return void 0; var value = object[property]; return _.isFunction(value) ? object[property]() : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escaper, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offest. return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; try { var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }.call(this)); },{}],"zepto":[function(require,module,exports){ /* Zepto v1.1.4-67-g76e4233 - zepto deferred detect ajax touch selector event callbacks - zeptojs.com/license */ var Zepto=function(){function k(t){return null==t?String(t):S[j.call(t)]||"object"}function D(t){return"function"==k(t)}function L(t){return null!=t&&t==t.window}function Z(t){return null!=t&&t.nodeType==t.DOCUMENT_NODE}function F(t){return"object"==k(t)}function $(t){return F(t)&&!L(t)&&Object.getPrototypeOf(t)==Object.prototype}function R(t){return"number"==typeof t.length}function _(t){return s.call(t,function(t){return null!=t})}function q(t){return t.length>0?n.fn.concat.apply([],t):t}function W(t){return t.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function B(t){return t in c?c[t]:c[t]=new RegExp("(^|\\s)"+t+"(\\s|$)")}function I(t,e){return"number"!=typeof e||l[W(t)]?e:e+"px"}function z(t){var e,n;return f[t]||(e=u.createElement(t),u.body.appendChild(e),n=getComputedStyle(e,"").getPropertyValue("display"),e.parentNode.removeChild(e),"none"==n&&(n="block"),f[t]=n),f[t]}function H(t){return"children"in t?a.call(t.children):n.map(t.childNodes,function(t){return 1==t.nodeType?t:void 0})}function V(t,e){var n,i=t?t.length:0;for(n=0;i>n;n++)this[n]=t[n];this.length=i,this.selector=e||""}function U(n,i,r){for(e in i)r&&($(i[e])||A(i[e]))?($(i[e])&&!$(n[e])&&(n[e]={}),A(i[e])&&!A(n[e])&&(n[e]=[]),U(n[e],i[e],r)):i[e]!==t&&(n[e]=i[e])}function X(t,e){return null==e?n(t):n(t).filter(e)}function Y(t,e,n,i){return D(e)?e.call(t,n,i):e}function J(t,e,n){null==n?t.removeAttribute(e):t.setAttribute(e,n)}function G(e,n){var i=e.className||"",r=i&&i.baseVal!==t;return n===t?r?i.baseVal:i:void(r?i.baseVal=n:e.className=n)}function K(t){try{return t?"true"==t||("false"==t?!1:"null"==t?null:+t+""==t?+t:/^[\[\{]/.test(t)?n.parseJSON(t):t):t}catch(e){return t}}function Q(t,e){e(t);for(var n=0,i=t.childNodes.length;i>n;n++)Q(t.childNodes[n],e)}var t,e,n,i,P,N,r=[],o=r.concat,s=r.filter,a=r.slice,u=window.document,f={},c={},l={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},h=/^\s*<(\w+|!)[^>]*>/,p=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,d=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,m=/^(?:body|html)$/i,g=/([A-Z])/g,v=["val","css","html","text","data","width","height","offset"],y=["after","prepend","before","append"],w=u.createElement("table"),b=u.createElement("tr"),x={tr:u.createElement("tbody"),tbody:w,thead:w,tfoot:w,td:b,th:b,"*":u.createElement("div")},T=/complete|loaded|interactive/,E=/^[\w-]*$/,S={},j=S.toString,C={},O=u.createElement("div"),M={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},A=Array.isArray||function(t){return t instanceof Array};return C.matches=function(t,e){if(!e||!t||1!==t.nodeType)return!1;var n=t.webkitMatchesSelector||t.mozMatchesSelector||t.oMatchesSelector||t.matchesSelector;if(n)return n.call(t,e);var i,r=t.parentNode,o=!r;return o&&(r=O).appendChild(t),i=~C.qsa(r,e).indexOf(t),o&&O.removeChild(t),i},P=function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})},N=function(t){return s.call(t,function(e,n){return t.indexOf(e)==n})},C.fragment=function(e,i,r){var o,s,f;return p.test(e)&&(o=n(u.createElement(RegExp.$1))),o||(e.replace&&(e=e.replace(d,"<$1></$2>")),i===t&&(i=h.test(e)&&RegExp.$1),i in x||(i="*"),f=x[i],f.innerHTML=""+e,o=n.each(a.call(f.childNodes),function(){f.removeChild(this)})),$(r)&&(s=n(o),n.each(r,function(t,e){v.indexOf(t)>-1?s[t](e):s.attr(t,e)})),o},C.Z=function(t,e){return new V(t,e)},C.isZ=function(t){return t instanceof C.Z},C.init=function(e,i){var r;if(!e)return C.Z();if("string"==typeof e)if(e=e.trim(),"<"==e[0]&&h.test(e))r=C.fragment(e,RegExp.$1,i),e=null;else{if(i!==t)return n(i).find(e);r=C.qsa(u,e)}else{if(D(e))return n(u).ready(e);if(C.isZ(e))return e;if(A(e))r=_(e);else if(F(e))r=[e],e=null;else if(h.test(e))r=C.fragment(e.trim(),RegExp.$1,i),e=null;else{if(i!==t)return n(i).find(e);r=C.qsa(u,e)}}return C.Z(r,e)},n=function(t,e){return C.init(t,e)},n.extend=function(t){var e,n=a.call(arguments,1);return"boolean"==typeof t&&(e=t,t=n.shift()),n.forEach(function(n){U(t,n,e)}),t},C.qsa=function(t,e){var n,i="#"==e[0],r=!i&&"."==e[0],o=i||r?e.slice(1):e,s=E.test(o);return t.getElementById&&s&&i?(n=t.getElementById(o))?[n]:[]:1!==t.nodeType&&9!==t.nodeType&&11!==t.nodeType?[]:a.call(s&&!i&&t.getElementsByClassName?r?t.getElementsByClassName(o):t.getElementsByTagName(e):t.querySelectorAll(e))},n.contains=u.documentElement.contains?function(t,e){return t!==e&&t.contains(e)}:function(t,e){for(;e&&(e=e.parentNode);)if(e===t)return!0;return!1},n.type=k,n.isFunction=D,n.isWindow=L,n.isArray=A,n.isPlainObject=$,n.isEmptyObject=function(t){var e;for(e in t)return!1;return!0},n.inArray=function(t,e,n){return r.indexOf.call(e,t,n)},n.camelCase=P,n.trim=function(t){return null==t?"":String.prototype.trim.call(t)},n.uuid=0,n.support={},n.expr={},n.noop=function(){},n.map=function(t,e){var n,r,o,i=[];if(R(t))for(r=0;r<t.length;r++)n=e(t[r],r),null!=n&&i.push(n);else for(o in t)n=e(t[o],o),null!=n&&i.push(n);return q(i)},n.each=function(t,e){var n,i;if(R(t)){for(n=0;n<t.length;n++)if(e.call(t[n],n,t[n])===!1)return t}else for(i in t)if(e.call(t[i],i,t[i])===!1)return t;return t},n.grep=function(t,e){return s.call(t,e)},window.JSON&&(n.parseJSON=JSON.parse),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(t,e){S["[object "+e+"]"]=e.toLowerCase()}),n.fn={constructor:C.Z,length:0,forEach:r.forEach,reduce:r.reduce,push:r.push,sort:r.sort,splice:r.splice,indexOf:r.indexOf,concat:function(){var t,e,n=[];for(t=0;t<arguments.length;t++)e=arguments[t],n[t]=C.isZ(e)?e.toArray():e;return o.apply(C.isZ(this)?this.toArray():this,n)},map:function(t){return n(n.map(this,function(e,n){return t.call(e,n,e)}))},slice:function(){return n(a.apply(this,arguments))},ready:function(t){return T.test(u.readyState)&&u.body?t(n):u.addEventListener("DOMContentLoaded",function(){t(n)},!1),this},get:function(e){return e===t?a.call(this):this[e>=0?e:e+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){null!=this.parentNode&&this.parentNode.removeChild(this)})},each:function(t){return r.every.call(this,function(e,n){return t.call(e,n,e)!==!1}),this},filter:function(t){return D(t)?this.not(this.not(t)):n(s.call(this,function(e){return C.matches(e,t)}))},add:function(t,e){return n(N(this.concat(n(t,e))))},is:function(t){return this.length>0&&C.matches(this[0],t)},not:function(e){var i=[];if(D(e)&&e.call!==t)this.each(function(t){e.call(this,t)||i.push(this)});else{var r="string"==typeof e?this.filter(e):R(e)&&D(e.item)?a.call(e):n(e);this.forEach(function(t){r.indexOf(t)<0&&i.push(t)})}return n(i)},has:function(t){return this.filter(function(){return F(t)?n.contains(this,t):n(this).find(t).size()})},eq:function(t){return-1===t?this.slice(t):this.slice(t,+t+1)},first:function(){var t=this[0];return t&&!F(t)?t:n(t)},last:function(){var t=this[this.length-1];return t&&!F(t)?t:n(t)},find:function(t){var e,i=this;return e=t?"object"==typeof t?n(t).filter(function(){var t=this;return r.some.call(i,function(e){return n.contains(e,t)})}):1==this.length?n(C.qsa(this[0],t)):this.map(function(){return C.qsa(this,t)}):n()},closest:function(t,e){var i=this[0],r=!1;for("object"==typeof t&&(r=n(t));i&&!(r?r.indexOf(i)>=0:C.matches(i,t));)i=i!==e&&!Z(i)&&i.parentNode;return n(i)},parents:function(t){for(var e=[],i=this;i.length>0;)i=n.map(i,function(t){return(t=t.parentNode)&&!Z(t)&&e.indexOf(t)<0?(e.push(t),t):void 0});return X(e,t)},parent:function(t){return X(N(this.pluck("parentNode")),t)},children:function(t){return X(this.map(function(){return H(this)}),t)},contents:function(){return this.map(function(){return a.call(this.childNodes)})},siblings:function(t){return X(this.map(function(t,e){return s.call(H(e.parentNode),function(t){return t!==e})}),t)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(t){return n.map(this,function(e){return e[t]})},show:function(){return this.each(function(){"none"==this.style.display&&(this.style.display=""),"none"==getComputedStyle(this,"").getPropertyValue("display")&&(this.style.display=z(this.nodeName))})},replaceWith:function(t){return this.before(t).remove()},wrap:function(t){var e=D(t);if(this[0]&&!e)var i=n(t).get(0),r=i.parentNode||this.length>1;return this.each(function(o){n(this).wrapAll(e?t.call(this,o):r?i.cloneNode(!0):i)})},wrapAll:function(t){if(this[0]){n(this[0]).before(t=n(t));for(var e;(e=t.children()).length;)t=e.first();n(t).append(this)}return this},wrapInner:function(t){var e=D(t);return this.each(function(i){var r=n(this),o=r.contents(),s=e?t.call(this,i):t;o.length?o.wrapAll(s):r.append(s)})},unwrap:function(){return this.parent().each(function(){n(this).replaceWith(n(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(e){return this.each(function(){var i=n(this);(e===t?"none"==i.css("display"):e)?i.show():i.hide()})},prev:function(t){return n(this.pluck("previousElementSibling")).filter(t||"*")},next:function(t){return n(this.pluck("nextElementSibling")).filter(t||"*")},html:function(t){return 0 in arguments?this.each(function(e){var i=this.innerHTML;n(this).empty().append(Y(this,t,e,i))}):0 in this?this[0].innerHTML:null},text:function(t){return 0 in arguments?this.each(function(e){var n=Y(this,t,e,this.textContent);this.textContent=null==n?"":""+n}):0 in this?this[0].textContent:null},attr:function(n,i){var r;return"string"!=typeof n||1 in arguments?this.each(function(t){if(1===this.nodeType)if(F(n))for(e in n)J(this,e,n[e]);else J(this,n,Y(this,i,t,this.getAttribute(n)))}):this.length&&1===this[0].nodeType?!(r=this[0].getAttribute(n))&&n in this[0]?this[0][n]:r:t},removeAttr:function(t){return this.each(function(){1===this.nodeType&&t.split(" ").forEach(function(t){J(this,t)},this)})},prop:function(t,e){return t=M[t]||t,1 in arguments?this.each(function(n){this[t]=Y(this,e,n,this[t])}):this[0]&&this[0][t]},data:function(e,n){var i="data-"+e.replace(g,"-$1").toLowerCase(),r=1 in arguments?this.attr(i,n):this.attr(i);return null!==r?K(r):t},val:function(t){return 0 in arguments?this.each(function(e){this.value=Y(this,t,e,this.value)}):this[0]&&(this[0].multiple?n(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value)},offset:function(t){if(t)return this.each(function(e){var i=n(this),r=Y(this,t,e,i.offset()),o=i.offsetParent().offset(),s={top:r.top-o.top,left:r.left-o.left};"static"==i.css("position")&&(s.position="relative"),i.css(s)});if(!this.length)return null;var e=this[0].getBoundingClientRect();return{left:e.left+window.pageXOffset,top:e.top+window.pageYOffset,width:Math.round(e.width),height:Math.round(e.height)}},css:function(t,i){if(arguments.length<2){var r,o=this[0];if(!o)return;if(r=getComputedStyle(o,""),"string"==typeof t)return o.style[P(t)]||r.getPropertyValue(t);if(A(t)){var s={};return n.each(t,function(t,e){s[e]=o.style[P(e)]||r.getPropertyValue(e)}),s}}var a="";if("string"==k(t))i||0===i?a=W(t)+":"+I(t,i):this.each(function(){this.style.removeProperty(W(t))});else for(e in t)t[e]||0===t[e]?a+=W(e)+":"+I(e,t[e])+";":this.each(function(){this.style.removeProperty(W(e))});return this.each(function(){this.style.cssText+=";"+a})},index:function(t){return t?this.indexOf(n(t)[0]):this.parent().children().indexOf(this[0])},hasClass:function(t){return t?r.some.call(this,function(t){return this.test(G(t))},B(t)):!1},addClass:function(t){return t?this.each(function(e){if("className"in this){i=[];var r=G(this),o=Y(this,t,e,r);o.split(/\s+/g).forEach(function(t){n(this).hasClass(t)||i.push(t)},this),i.length&&G(this,r+(r?" ":"")+i.join(" "))}}):this},removeClass:function(e){return this.each(function(n){if("className"in this){if(e===t)return G(this,"");i=G(this),Y(this,e,n,i).split(/\s+/g).forEach(function(t){i=i.replace(B(t)," ")}),G(this,i.trim())}})},toggleClass:function(e,i){return e?this.each(function(r){var o=n(this),s=Y(this,e,r,G(this));s.split(/\s+/g).forEach(function(e){(i===t?!o.hasClass(e):i)?o.addClass(e):o.removeClass(e)})}):this},scrollTop:function(e){if(this.length){var n="scrollTop"in this[0];return e===t?n?this[0].scrollTop:this[0].pageYOffset:this.each(n?function(){this.scrollTop=e}:function(){this.scrollTo(this.scrollX,e)})}},scrollLeft:function(e){if(this.length){var n="scrollLeft"in this[0];return e===t?n?this[0].scrollLeft:this[0].pageXOffset:this.each(n?function(){this.scrollLeft=e}:function(){this.scrollTo(e,this.scrollY)})}},position:function(){if(this.length){var t=this[0],e=this.offsetParent(),i=this.offset(),r=m.test(e[0].nodeName)?{top:0,left:0}:e.offset();return i.top-=parseFloat(n(t).css("margin-top"))||0,i.left-=parseFloat(n(t).css("margin-left"))||0,r.top+=parseFloat(n(e[0]).css("border-top-width"))||0,r.left+=parseFloat(n(e[0]).css("border-left-width"))||0,{top:i.top-r.top,left:i.left-r.left}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||u.body;t&&!m.test(t.nodeName)&&"static"==n(t).css("position");)t=t.offsetParent;return t})}},n.fn.detach=n.fn.remove,["width","height"].forEach(function(e){var i=e.replace(/./,function(t){return t[0].toUpperCase()});n.fn[e]=function(r){var o,s=this[0];return r===t?L(s)?s["inner"+i]:Z(s)?s.documentElement["scroll"+i]:(o=this.offset())&&o[e]:this.each(function(t){s=n(this),s.css(e,Y(this,r,t,s[e]()))})}}),y.forEach(function(t,e){var i=e%2;n.fn[t]=function(){var t,o,r=n.map(arguments,function(e){return t=k(e),"object"==t||"array"==t||null==e?e:C.fragment(e)}),s=this.length>1;return r.length<1?this:this.each(function(t,a){o=i?a:a.parentNode,a=0==e?a.nextSibling:1==e?a.firstChild:2==e?a:null;var f=n.contains(u.documentElement,o);r.forEach(function(t){if(s)t=t.cloneNode(!0);else if(!o)return n(t).remove();o.insertBefore(t,a),f&&Q(t,function(t){null==t.nodeName||"SCRIPT"!==t.nodeName.toUpperCase()||t.type&&"text/javascript"!==t.type||t.src||window.eval.call(window,t.innerHTML)})})})},n.fn[i?t+"To":"insert"+(e?"Before":"After")]=function(e){return n(e)[t](this),this}}),C.Z.prototype=V.prototype=n.fn,C.uniq=N,C.deserializeValue=K,n.zepto=C,n}();window.Zepto=Zepto,void 0===window.$&&(window.$=Zepto),function(t){function n(e){var i=[["resolve","done",t.Callbacks({once:1,memory:1}),"resolved"],["reject","fail",t.Callbacks({once:1,memory:1}),"rejected"],["notify","progress",t.Callbacks({memory:1})]],r="pending",o={state:function(){return r},always:function(){return s.done(arguments).fail(arguments),this},then:function(){var e=arguments;return n(function(n){t.each(i,function(i,r){var a=t.isFunction(e[i])&&e[i];s[r[1]](function(){var e=a&&a.apply(this,arguments);if(e&&t.isFunction(e.promise))e.promise().done(n.resolve).fail(n.reject).progress(n.notify);else{var i=this===o?n.promise():this,s=a?[e]:arguments;n[r[0]+"With"](i,s)}})}),e=null}).promise()},promise:function(e){return null!=e?t.extend(e,o):o}},s={};return t.each(i,function(t,e){var n=e[2],a=e[3];o[e[1]]=n.add,a&&n.add(function(){r=a},i[1^t][2].disable,i[2][2].lock),s[e[0]]=function(){return s[e[0]+"With"](this===s?o:this,arguments),this},s[e[0]+"With"]=n.fireWith}),o.promise(s),e&&e.call(s,s),s}var e=Array.prototype.slice;t.when=function(i){var f,c,l,r=e.call(arguments),o=r.length,s=0,a=1!==o||i&&t.isFunction(i.promise)?o:0,u=1===a?i:n(),h=function(t,n,i){return function(r){n[t]=this,i[t]=arguments.length>1?e.call(arguments):r,i===f?u.notifyWith(n,i):--a||u.resolveWith(n,i)}};if(o>1)for(f=new Array(o),c=new Array(o),l=new Array(o);o>s;++s)r[s]&&t.isFunction(r[s].promise)?r[s].promise().done(h(s,l,r)).fail(u.reject).progress(h(s,c,f)):--a;return a||u.resolveWith(l,r),u.promise()},t.Deferred=n}(Zepto),function(t){function e(t,e){var n=this.os={},i=this.browser={},r=t.match(/Web[kK]it[\/]{0,1}([\d.]+)/),o=t.match(/(Android);?[\s\/]+([\d.]+)?/),s=!!t.match(/\(Macintosh\; Intel /),a=t.match(/(iPad).*OS\s([\d_]+)/),u=t.match(/(iPod)(.*OS\s([\d_]+))?/),f=!a&&t.match(/(iPhone\sOS)\s([\d_]+)/),c=t.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),l=/Win\d{2}|Windows/.test(e),h=t.match(/Windows Phone ([\d.]+)/),p=c&&t.match(/TouchPad/),d=t.match(/Kindle\/([\d.]+)/),m=t.match(/Silk\/([\d._]+)/),g=t.match(/(BlackBerry).*Version\/([\d.]+)/),v=t.match(/(BB10).*Version\/([\d.]+)/),y=t.match(/(RIM\sTablet\sOS)\s([\d.]+)/),w=t.match(/PlayBook/),b=t.match(/Chrome\/([\d.]+)/)||t.match(/CriOS\/([\d.]+)/),x=t.match(/Firefox\/([\d.]+)/),T=t.match(/\((?:Mobile|Tablet); rv:([\d.]+)\).*Firefox\/[\d.]+/),E=t.match(/MSIE\s([\d.]+)/)||t.match(/Trident\/[\d](?=[^\?]+).*rv:([0-9.].)/),S=!b&&t.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/),j=S||t.match(/Version\/([\d.]+)([^S](Safari)|[^M]*(Mobile)[^S]*(Safari))/);(i.webkit=!!r)&&(i.version=r[1]),o&&(n.android=!0,n.version=o[2]),f&&!u&&(n.ios=n.iphone=!0,n.version=f[2].replace(/_/g,".")),a&&(n.ios=n.ipad=!0,n.version=a[2].replace(/_/g,".")),u&&(n.ios=n.ipod=!0,n.version=u[3]?u[3].replace(/_/g,"."):null),h&&(n.wp=!0,n.version=h[1]),c&&(n.webos=!0,n.version=c[2]),p&&(n.touchpad=!0),g&&(n.blackberry=!0,n.version=g[2]),v&&(n.bb10=!0,n.version=v[2]),y&&(n.rimtabletos=!0,n.version=y[2]),w&&(i.playbook=!0),d&&(n.kindle=!0,n.version=d[1]),m&&(i.silk=!0,i.version=m[1]),!m&&n.android&&t.match(/Kindle Fire/)&&(i.silk=!0),b&&(i.chrome=!0,i.version=b[1]),x&&(i.firefox=!0,i.version=x[1]),T&&(n.firefoxos=!0,n.version=T[1]),E&&(i.ie=!0,i.version=E[1]),j&&(s||n.ios||l)&&(i.safari=!0,n.ios||(i.version=j[1])),S&&(i.webview=!0),n.tablet=!!(a||w||o&&!t.match(/Mobile/)||x&&t.match(/Tablet/)||E&&!t.match(/Phone/)&&t.match(/Touch/)),n.phone=!(n.tablet||n.ipod||!(o||f||c||g||v||b&&t.match(/Android/)||b&&t.match(/CriOS\/([\d.]+)/)||x&&t.match(/Mobile/)||E&&t.match(/Touch/)))}e.call(t,navigator.userAgent,navigator.platform),t.__detect=e}(Zepto),function(t){function h(e,n,i){var r=t.Event(n);return t(e).trigger(r,i),!r.isDefaultPrevented()}function p(t,e,i,r){return t.global?h(e||n,i,r):void 0}function d(e){e.global&&0===t.active++&&p(e,null,"ajaxStart")}function m(e){e.global&&!--t.active&&p(e,null,"ajaxStop")}function g(t,e){var n=e.context;return e.beforeSend.call(n,t,e)===!1||p(e,n,"ajaxBeforeSend",[t,e])===!1?!1:void p(e,n,"ajaxSend",[t,e])}function v(t,e,n,i){var r=n.context,o="success";n.success.call(r,t,o,e),i&&i.resolveWith(r,[t,o,e]),p(n,r,"ajaxSuccess",[e,n,t]),w(o,e,n)}function y(t,e,n,i,r){var o=i.context;i.error.call(o,n,e,t),r&&r.rejectWith(o,[n,e,t]),p(i,o,"ajaxError",[n,i,t||e]),w(e,n,i)}function w(t,e,n){var i=n.context;n.complete.call(i,e,t),p(n,i,"ajaxComplete",[e,n]),m(n)}function b(){}function x(t){return t&&(t=t.split(";",2)[0]),t&&(t==f?"html":t==u?"json":s.test(t)?"script":a.test(t)&&"xml")||"text"}function T(t,e){return""==e?t:(t+"&"+e).replace(/[&?]{1,2}/,"?")}function E(e){e.processData&&e.data&&"string"!=t.type(e.data)&&(e.data=t.param(e.data,e.traditional)),!e.data||e.type&&"GET"!=e.type.toUpperCase()||(e.url=T(e.url,e.data),e.data=void 0)}function S(e,n,i,r){return t.isFunction(n)&&(r=i,i=n,n=void 0),t.isFunction(i)||(r=i,i=void 0),{url:e,data:n,success:i,dataType:r}}function C(e,n,i,r){var o,s=t.isArray(n),a=t.isPlainObject(n);t.each(n,function(n,u){o=t.type(u),r&&(n=i?r:r+"["+(a||"object"==o||"array"==o?n:"")+"]"),!r&&s?e.add(u.name,u.value):"array"==o||!i&&"object"==o?C(e,u,i,n):e.add(n,u)})}var i,r,e=0,n=window.document,o=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,s=/^(?:text|application)\/javascript/i,a=/^(?:text|application)\/xml/i,u="application/json",f="text/html",c=/^\s*$/,l=n.createElement("a");l.href=window.location.href,t.active=0,t.ajaxJSONP=function(i,r){if(!("type"in i))return t.ajax(i);var f,h,o=i.jsonpCallback,s=(t.isFunction(o)?o():o)||"jsonp"+ ++e,a=n.createElement("script"),u=window[s],c=function(e){t(a).triggerHandler("error",e||"abort")},l={abort:c};return r&&r.promise(l),t(a).on("load error",function(e,n){clearTimeout(h),t(a).off().remove(),"error"!=e.type&&f?v(f[0],l,i,r):y(null,n||"error",l,i,r),window[s]=u,f&&t.isFunction(u)&&u(f[0]),u=f=void 0}),g(l,i)===!1?(c("abort"),l):(window[s]=function(){f=arguments},a.src=i.url.replace(/\?(.+)=\?/,"?$1="+s),n.head.appendChild(a),i.timeout>0&&(h=setTimeout(function(){c("timeout")},i.timeout)),l)},t.ajaxSettings={type:"GET",beforeSend:b,success:b,error:b,complete:b,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:u,xml:"application/xml, text/xml",html:f,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},t.ajax=function(e){var a,o=t.extend({},e||{}),s=t.Deferred&&t.Deferred();for(i in t.ajaxSettings)void 0===o[i]&&(o[i]=t.ajaxSettings[i]);d(o),o.crossDomain||(a=n.createElement("a"),a.href=o.url,a.href=a.href,o.crossDomain=l.protocol+"//"+l.host!=a.protocol+"//"+a.host),o.url||(o.url=window.location.toString()),E(o);var u=o.dataType,f=/\?.+=\?/.test(o.url);if(f&&(u="jsonp"),o.cache!==!1&&(e&&e.cache===!0||"script"!=u&&"jsonp"!=u)||(o.url=T(o.url,"_="+Date.now())),"jsonp"==u)return f||(o.url=T(o.url,o.jsonp?o.jsonp+"=?":o.jsonp===!1?"":"callback=?")),t.ajaxJSONP(o,s);var C,h=o.accepts[u],p={},m=function(t,e){p[t.toLowerCase()]=[t,e]},w=/^([\w-]+:)\/\//.test(o.url)?RegExp.$1:window.location.protocol,S=o.xhr(),j=S.setRequestHeader;if(s&&s.promise(S),o.crossDomain||m("X-Requested-With","XMLHttpRequest"),m("Accept",h||"*/*"),(h=o.mimeType||h)&&(h.indexOf(",")>-1&&(h=h.split(",",2)[0]),S.overrideMimeType&&S.overrideMimeType(h)),(o.contentType||o.contentType!==!1&&o.data&&"GET"!=o.type.toUpperCase())&&m("Content-Type",o.contentType||"application/x-www-form-urlencoded"),o.headers)for(r in o.headers)m(r,o.headers[r]);if(S.setRequestHeader=m,S.onreadystatechange=function(){if(4==S.readyState){S.onreadystatechange=b,clearTimeout(C);var e,n=!1;if(S.status>=200&&S.status<300||304==S.status||0==S.status&&"file:"==w){u=u||x(o.mimeType||S.getResponseHeader("content-type")),e=S.responseText;try{"script"==u?(1,eval)(e):"xml"==u?e=S.responseXML:"json"==u&&(e=c.test(e)?null:t.parseJSON(e))}catch(i){n=i}n?y(n,"parsererror",S,o,s):v(e,S,o,s)}else y(S.statusText||null,S.status?"error":"abort",S,o,s)}},g(S,o)===!1)return S.abort(),y(null,"abort",S,o,s),S;if(o.xhrFields)for(r in o.xhrFields)S[r]=o.xhrFields[r];var P="async"in o?o.async:!0;S.open(o.type,o.url,P,o.username,o.password);for(r in p)j.apply(S,p[r]);return o.timeout>0&&(C=setTimeout(function(){S.onreadystatechange=b,S.abort(),y(null,"timeout",S,o,s)},o.timeout)),S.send(o.data?o.data:null),S},t.get=function(){return t.ajax(S.apply(null,arguments))},t.post=function(){var e=S.apply(null,arguments);return e.type="POST",t.ajax(e)},t.getJSON=function(){var e=S.apply(null,arguments);return e.dataType="json",t.ajax(e)},t.fn.load=function(e,n,i){if(!this.length)return this;var a,r=this,s=e.split(/\s/),u=S(e,n,i),f=u.success;return s.length>1&&(u.url=s[0],a=s[1]),u.success=function(e){r.html(a?t("<div>").html(e.replace(o,"")).find(a):e),f&&f.apply(r,arguments)},t.ajax(u),this};var j=encodeURIComponent;t.param=function(e,n){var i=[];return i.add=function(e,n){t.isFunction(n)&&(n=n()),null==n&&(n=""),this.push(j(e)+"="+j(n))},C(i,e,n),i.join("&").replace(/%20/g,"+")}}(Zepto),function(t){function u(t,e,n,i){return Math.abs(t-e)>=Math.abs(n-i)?t-e>0?"Left":"Right":n-i>0?"Up":"Down"}function f(){o=null,e.last&&(e.el.trigger("longTap"),e={})}function c(){o&&clearTimeout(o),o=null}function l(){n&&clearTimeout(n),i&&clearTimeout(i),r&&clearTimeout(r),o&&clearTimeout(o),n=i=r=o=null,e={}}function h(t){return("touch"==t.pointerType||t.pointerType==t.MSPOINTER_TYPE_TOUCH)&&t.isPrimary}function p(t,e){return t.type=="pointer"+e||t.type.toLowerCase()=="mspointer"+e}var n,i,r,o,a,e={},s=750;t(document).ready(function(){var d,m,y,w,g=0,v=0;"MSGesture"in window&&(a=new MSGesture,a.target=document.body),t(document).bind("MSGestureEnd",function(t){var n=t.velocityX>1?"Right":t.velocityX<-1?"Left":t.velocityY>1?"Down":t.velocityY<-1?"Up":null;n&&(e.el.trigger("swipe"),e.el.trigger("swipe"+n))}).on("touchstart MSPointerDown pointerdown",function(i){(!(w=p(i,"down"))||h(i))&&(y=w?i:i.touches[0],i.touches&&1===i.touches.length&&e.x2&&(e.x2=void 0,e.y2=void 0),d=Date.now(),m=d-(e.last||d),e.el=t("tagName"in y.target?y.target:y.target.parentNode),n&&clearTimeout(n),e.x1=y.pageX,e.y1=y.pageY,m>0&&250>=m&&(e.isDoubleTap=!0),e.last=d,o=setTimeout(f,s),a&&w&&a.addPointer(i.pointerId))}).on("touchmove MSPointerMove pointermove",function(t){(!(w=p(t,"move"))||h(t))&&(y=w?t:t.touches[0],c(),e.x2=y.pageX,e.y2=y.pageY,g+=Math.abs(e.x1-e.x2),v+=Math.abs(e.y1-e.y2))}).on("touchend MSPointerUp pointerup",function(o){(!(w=p(o,"up"))||h(o))&&(c(),e.x2&&Math.abs(e.x1-e.x2)>30||e.y2&&Math.abs(e.y1-e.y2)>30?r=setTimeout(function(){e.el.trigger("swipe"),e.el.trigger("swipe"+u(e.x1,e.x2,e.y1,e.y2)),e={}},0):"last"in e&&(30>g&&30>v?i=setTimeout(function(){var i=t.Event("tap");i.cancelTouch=l,e.el.trigger(i),e.isDoubleTap?(e.el&&e.el.trigger("doubleTap"),e={}):n=setTimeout(function(){n=null,e.el&&e.el.trigger("singleTap"),e={}},250)},0):e={}),g=v=0)}).on("touchcancel MSPointerCancel pointercancel",l),t(window).on("scroll",l)}),["swipe","swipeLeft","swipeRight","swipeUp","swipeDown","doubleTap","tap","singleTap","longTap"].forEach(function(e){t.fn[e]=function(t){return this.on(e,t)}})}(Zepto),function(t){function r(e){return e=t(e),!(!e.width()&&!e.height())&&"none"!==e.css("display")}function f(t,e){t=t.replace(/=#\]/g,'="#"]');var n,i,r=s.exec(t);if(r&&r[2]in o&&(n=o[r[2]],i=r[3],t=r[1],i)){var a=Number(i);i=isNaN(a)?i.replace(/^["']|["']$/g,""):a}return e(t,n,i)}var e=t.zepto,n=e.qsa,i=e.matches,o=t.expr[":"]={visible:function(){return r(this)?this:void 0},hidden:function(){return r(this)?void 0:this},selected:function(){return this.selected?this:void 0},checked:function(){return this.checked?this:void 0},parent:function(){return this.parentNode},first:function(t){return 0===t?this:void 0},last:function(t,e){return t===e.length-1?this:void 0},eq:function(t,e,n){return t===n?this:void 0},contains:function(e,n,i){return t(this).text().indexOf(i)>-1?this:void 0},has:function(t,n,i){return e.qsa(this,i).length?this:void 0}},s=new RegExp("(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*"),a=/^\s*>/,u="Zepto"+ +new Date;e.qsa=function(i,r){return f(r,function(o,s,f){try{var c;!o&&s?o="*":a.test(o)&&(c=t(i).addClass(u),o="."+u+" "+o);var l=n(i,o)}catch(h){throw console.error("error performing selector: %o",r),h}finally{c&&c.removeClass(u)}return s?e.uniq(t.map(l,function(t,e){return s.call(t,e,l,f)})):l})},e.matches=function(t,e){return f(e,function(e,n,r){return!(e&&!i(t,e)||n&&n.call(t,null,r)!==t)})}}(Zepto),function(t){function l(t){return t._zid||(t._zid=e++)}function h(t,e,n,i){if(e=p(e),e.ns)var r=d(e.ns);return(s[l(t)]||[]).filter(function(t){return!(!t||e.e&&t.e!=e.e||e.ns&&!r.test(t.ns)||n&&l(t.fn)!==l(n)||i&&t.sel!=i)})}function p(t){var e=(""+t).split(".");return{e:e[0],ns:e.slice(1).sort().join(" ")}}function d(t){return new RegExp("(?:^| )"+t.replace(" "," .* ?")+"(?: |$)")}function m(t,e){return t.del&&!u&&t.e in f||!!e}function g(t){return c[t]||u&&f[t]||t}function v(e,i,r,o,a,u,f){var h=l(e),d=s[h]||(s[h]=[]);i.split(/\s/).forEach(function(i){if("ready"==i)return t(document).ready(r);var s=p(i);s.fn=r,s.sel=a,s.e in c&&(r=function(e){var n=e.relatedTarget;return!n||n!==this&&!t.contains(this,n)?s.fn.apply(this,arguments):void 0}),s.del=u;var l=u||r;s.proxy=function(t){if(t=E(t),!t.isImmediatePropagationStopped()){t.data=o;var i=l.apply(e,t._args==n?[t]:[t].concat(t._args));return i===!1&&(t.preventDefault(),t.stopPropagation()),i}},s.i=d.length,d.push(s),"addEventListener"in e&&e.addEventListener(g(s.e),s.proxy,m(s,f))})}function y(t,e,n,i,r){var o=l(t);(e||"").split(/\s/).forEach(function(e){h(t,e,n,i).forEach(function(e){delete s[o][e.i],"removeEventListener"in t&&t.removeEventListener(g(e.e),e.proxy,m(e,r))})})}function E(e,i){return(i||!e.isDefaultPrevented)&&(i||(i=e),t.each(T,function(t,n){var r=i[t];e[t]=function(){return this[n]=w,r&&r.apply(i,arguments)},e[n]=b}),(i.defaultPrevented!==n?i.defaultPrevented:"returnValue"in i?i.returnValue===!1:i.getPreventDefault&&i.getPreventDefault())&&(e.isDefaultPrevented=w)),e}function S(t){var e,i={originalEvent:t};for(e in t)x.test(e)||t[e]===n||(i[e]=t[e]);return E(i,t)}var n,e=1,i=Array.prototype.slice,r=t.isFunction,o=function(t){return"string"==typeof t},s={},a={},u="onfocusin"in window,f={focus:"focusin",blur:"focusout"},c={mouseenter:"mouseover",mouseleave:"mouseout"};a.click=a.mousedown=a.mouseup=a.mousemove="MouseEvents",t.event={add:v,remove:y},t.proxy=function(e,n){var s=2 in arguments&&i.call(arguments,2);if(r(e)){var a=function(){return e.apply(n,s?s.concat(i.call(arguments)):arguments)};return a._zid=l(e),a}if(o(n))return s?(s.unshift(e[n],e),t.proxy.apply(null,s)):t.proxy(e[n],e);throw new TypeError("expected function")},t.fn.bind=function(t,e,n){return this.on(t,e,n)},t.fn.unbind=function(t,e){return this.off(t,e)},t.fn.one=function(t,e,n,i){return this.on(t,e,n,i,1)};var w=function(){return!0},b=function(){return!1},x=/^([A-Z]|returnValue$|layer[XY]$)/,T={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};t.fn.delegate=function(t,e,n){return this.on(e,t,n)},t.fn.undelegate=function(t,e,n){return this.off(e,t,n)},t.fn.live=function(e,n){return t(document.body).delegate(this.selector,e,n),this},t.fn.die=function(e,n){return t(document.body).undelegate(this.selector,e,n),this},t.fn.on=function(e,s,a,u,f){var c,l,h=this;return e&&!o(e)?(t.each(e,function(t,e){h.on(t,s,a,e,f)}),h):(o(s)||r(u)||u===!1||(u=a,a=s,s=n),(r(a)||a===!1)&&(u=a,a=n),u===!1&&(u=b),h.each(function(n,r){f&&(c=function(t){return y(r,t.type,u),u.apply(this,arguments)}),s&&(l=function(e){var n,o=t(e.target).closest(s,r).get(0);return o&&o!==r?(n=t.extend(S(e),{currentTarget:o,liveFired:r}),(c||u).apply(o,[n].concat(i.call(arguments,1)))):void 0}),v(r,e,u,a,s,l||c)}))},t.fn.off=function(e,i,s){var a=this;return e&&!o(e)?(t.each(e,function(t,e){a.off(t,i,e)}),a):(o(i)||r(s)||s===!1||(s=i,i=n),s===!1&&(s=b),a.each(function(){y(this,e,s,i)}))},t.fn.trigger=function(e,n){return e=o(e)||t.isPlainObject(e)?t.Event(e):E(e),e._args=n,this.each(function(){e.type in f&&"function"==typeof this[e.type]?this[e.type]():"dispatchEvent"in this?this.dispatchEvent(e):t(this).triggerHandler(e,n)})},t.fn.triggerHandler=function(e,n){var i,r;return this.each(function(s,a){i=S(o(e)?t.Event(e):e),i._args=n,i.target=a,t.each(h(a,e.type||e),function(t,e){return r=e.proxy(i),i.isImmediatePropagationStopped()?!1:void 0})}),r},"focusin focusout focus blur load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(e){t.fn[e]=function(t){return 0 in arguments?this.bind(e,t):this.trigger(e)}}),t.Event=function(t,e){o(t)||(e=t,t=e.type);var n=document.createEvent(a[t]||"Events"),i=!0;if(e)for(var r in e)"bubbles"==r?i=!!e[r]:n[r]=e[r];return n.initEvent(t,i,!0),E(n)}}(Zepto),function(t){t.Callbacks=function(e){e=t.extend({},e);var n,i,r,o,s,a,u=[],f=!e.once&&[],c=function(t){for(n=e.memory&&t,i=!0,a=o||0,o=0,s=u.length,r=!0;u&&s>a;++a)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}r=!1,u&&(f?f.length&&c(f.shift()):n?u.length=0:l.disable())},l={add:function(){if(u){var i=u.length,a=function(n){t.each(n,function(t,n){"function"==typeof n?e.unique&&l.has(n)||u.push(n):n&&n.length&&"string"!=typeof n&&a(n)})};a(arguments),r?s=u.length:n&&(o=i,c(n))}return this},remove:function(){return u&&t.each(arguments,function(e,n){for(var i;(i=t.inArray(n,u,i))>-1;)u.splice(i,1),r&&(s>=i&&--s,a>=i&&--a)}),this },has:function(e){return!(!u||!(e?t.inArray(e,u)>-1:u.length))},empty:function(){return s=u.length=0,this},disable:function(){return u=f=n=void 0,this},disabled:function(){return!u},lock:function(){return f=void 0,n||l.disable(),this},locked:function(){return!f},fireWith:function(t,e){return!u||i&&!f||(e=e||[],e=[t,e.slice?e.slice():e],r?f.push(e):c(e)),this},fire:function(){return l.fireWith(this,arguments)},fired:function(){return!!i}};return l}}(Zepto); module.exports = Zepto; },{}]},{},[3,1]) //# sourceMappingURL=clappr.map
ajax/libs/react-datepicker/0.6.1/react-datepicker.min.js
dannyxx001/cdnjs
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react"),require("moment"),require("react-onclickoutside")):"function"==typeof define&&define.amd?define(["react","moment","react-onclickoutside"],e):"object"==typeof exports?exports.DatePicker=e(require("react"),require("moment"),require("react-onclickoutside")):t.DatePicker=e(t.React,t.moment,t.OnClickOutside)}(this,function(t,e,o){return function(t){function e(n){if(o[n])return o[n].exports;var i=o[n]={exports:{},id:n,loaded:!1};return t[n].call(i.exports,i,i.exports,e),i.loaded=!0,i.exports}var o={};return e.m=t,e.c=o,e.p="",e(0)}([function(t,e,o){"use strict";var n=o(1),i=o(2),s=(o(3),o(4)),r=o(5),a=n.createClass({displayName:"DatePicker",getInitialState:function(){return{focus:!1}},handleFocus:function(){this.setState({focus:!0})},hideCalendar:function(){setTimeout(function(){this.setState({focus:!1})}.bind(this),0)},handleSelect:function(t){this.setSelected(t),setTimeout(function(){this.hideCalendar()}.bind(this),200)},setSelected:function(t){this.props.onChange(t.moment())},onInputClick:function(){this.setState({focus:!0})},calendar:function(){return this.state.focus?n.createElement(i,null,n.createElement(s,{selected:this.props.selected,onSelect:this.handleSelect,hideCalendar:this.hideCalendar,minDate:this.props.minDate,maxDate:this.props.maxDate,weekStart:this.props.weekStart})):void 0},render:function(){return n.createElement("div",null,n.createElement(r,{date:this.props.selected,dateFormat:this.props.dateFormat,focus:this.state.focus,onFocus:this.handleFocus,handleClick:this.onInputClick,handleEnter:this.hideCalendar,setSelected:this.setSelected,hideCalendar:this.hideCalendar,placeholderText:this.props.placeholderText}),this.calendar())}});t.exports=a},function(e){e.exports=t},function(t,e,o){"use strict";var n=o(1),i=o(9),s=n.createClass({displayName:"Popover",componentWillMount:function(){var t=document.createElement("span");t.className="datepicker__container",this._popoverElement=t,document.querySelector("body").appendChild(this._popoverElement)},componentDidMount:function(){this._renderPopover()},componentDidUpdate:function(){this._renderPopover()},_popoverComponent:function(){var t=this.props.className;return n.createElement("div",{className:t},this.props.children)},_tetherOptions:function(){return{element:this._popoverElement,target:this.getDOMNode().parentElement,attachment:"top left",targetAttachment:"bottom left",targetOffset:"10px 0",optimizations:{moveElement:!1}}},_renderPopover:function(){n.render(this._popoverComponent(),this._popoverElement),null!=this._tether?this._tether.setOptions(this._tetherOptions()):this._tether=new i(this._tetherOptions())},componentWillUnmount:function(){this._tether.destroy(),n.unmountComponentAtNode(this._popoverElement),this._popoverElement.parentNode&&this._popoverElement.parentNode.removeChild(this._popoverElement)},render:function(){return n.createElement("span",null)}});t.exports=s},function(t){"use strict";function e(t){this._date=t}e.prototype.isBefore=function(t){return this._date.isBefore(t._date,"day")},e.prototype.isAfter=function(t){return this._date.isAfter(t._date,"day")},e.prototype.sameDay=function(t){return this._date.isSame(t._date,"day")},e.prototype.sameMonth=function(t){return this._date.isSame(t._date,"month")},e.prototype.day=function(){return this._date.date()},e.prototype.mapDaysInWeek=function(t){for(var o=[],n=this._date.clone(),i=0;7>i;i++){var s=new e(n.clone().add(i,"days"));o[i]=t(s,i)}return o},e.prototype.mapWeeksInMonth=function(t){for(var o=[],n=this._date.clone().startOf("month").startOf("week"),i=0;6>i;i++){var s=new e(n.clone().add(i,"weeks"));o[i]=t(s,i)}return o},e.prototype.weekInMonth=function(t){var e=this._date.clone(),o=this._date.clone().weekday(7);return e.isSame(t._date,"month")||o.isSame(t._date,"month")},e.prototype.format=function(){return this._date.format.apply(this._date,arguments)},e.prototype.addMonth=function(){return new e(this._date.clone().add(1,"month"))},e.prototype.subtractMonth=function(){return new e(this._date.clone().subtract(1,"month"))},e.prototype.clone=function(){return new e(this._date.clone())},e.prototype.safeClone=function(t){return this._date?this.clone():(void 0===t&&(t=null),new e(t))},e.prototype.moment=function(){return this._date},t.exports=e},function(t,e,o){"use strict";var n=o(1),i=o(8),s=o(3),r=o(6),a=n.createClass({displayName:"Calendar",mixins:[o(7)],handleClickOutside:function(){this.props.hideCalendar()},getInitialState:function(){return{date:new s(this.props.selected).safeClone(r())}},getDefaultProps:function(){return{weekStart:1}},componentWillMount:function(){this.initializeMomentLocale()},componentWillReceiveProps:function(t){t.selected!==this.props.selected&&this.setState({date:new s(t.selected).clone()})},initializeMomentLocale:function(){var t=["Su","Mo","Tu","We","Th","Fr","Sa"];t=t.concat(t.splice(0,this.props.weekStart)),r.locale("en",{week:{dow:this.props.weekStart},weekdaysMin:t})},increaseMonth:function(){this.setState({date:this.state.date.addMonth()})},decreaseMonth:function(){this.setState({date:this.state.date.subtractMonth()})},weeks:function(){return this.state.date.mapWeeksInMonth(this.renderWeek)},handleDayClick:function(t){this.props.onSelect(t)},renderWeek:function(t,e){return t.weekInMonth(this.state.date)?n.createElement("div",{key:e},this.days(t)):void 0},renderDay:function(t,e){var o=new s(this.props.minDate).safeClone(),r=new s(this.props.maxDate).safeClone(),a=t.isBefore(o)||t.isAfter(r);return n.createElement(i,{key:e,day:t,date:this.state.date,onClick:this.handleDayClick.bind(this,t),selected:new s(this.props.selected),disabled:a})},days:function(t){return t.mapDaysInWeek(this.renderDay)},header:function(){return r.weekdaysMin().map(function(t,e){return n.createElement("div",{className:"datepicker__day",key:e},t)})},render:function(){return n.createElement("div",{className:"datepicker"},n.createElement("div",{className:"datepicker__triangle"}),n.createElement("div",{className:"datepicker__header"},n.createElement("a",{className:"datepicker__navigation datepicker__navigation--previous",onClick:this.decreaseMonth}),n.createElement("span",{className:"datepicker__current-month"},this.state.date.format("MMMM YYYY")),n.createElement("a",{className:"datepicker__navigation datepicker__navigation--next",onClick:this.increaseMonth}),n.createElement("div",null,this.header())),n.createElement("div",{className:"datepicker__month"},this.weeks()))}});t.exports=a},function(t,e,o){"use strict";var n=o(1),i=o(3),s=o(6),r=n.createClass({displayName:"DateInput",getDefaultProps:function(){return{dateFormat:"YYYY-MM-DD"}},getInitialState:function(){return{value:this.safeDateFormat(this.props.date)}},componentDidMount:function(){this.toggleFocus(this.props.focus)},componentWillReceiveProps:function(t){this.toggleFocus(t.focus),this.setState({value:this.safeDateFormat(t.date)})},toggleFocus:function(t){t?this.refs.input.getDOMNode().focus():this.refs.input.getDOMNode().blur()},handleChange:function(t){var e=s(t.target.value,this.props.dateFormat,!0);this.setState({value:t.target.value}),this.isValueAValidDate()&&this.props.setSelected(new i(e))},safeDateFormat:function(t){return t?t.format(this.props.dateFormat):null},isValueAValidDate:function(){var t=s(event.target.value,this.props.dateFormat,!0);return t.isValid()},handleKeyDown:function(t){switch(t.key){case"Enter":t.preventDefault(),this.props.handleEnter()}},handleClick:function(t){this.props.handleClick(t)},render:function(){return n.createElement("input",{ref:"input",type:"text",value:this.state.value,onClick:this.handleClick,onKeyDown:this.handleKeyDown,onFocus:this.props.onFocus,onChange:this.handleChange,className:"datepicker__input",placeholder:this.props.placeholderText})}});t.exports=r},function(t){t.exports=e},function(t){t.exports=o},function(t,e,o){"use strict";var n=o(1),i=o(6),s=n.createClass({displayName:"Day",handleClick:function(t){this.props.disabled||this.props.onClick(t)},render:function(){var t=n.addons.classSet({datepicker__day:!0,"datepicker__day--disabled":this.props.disabled,"datepicker__day--selected":this.props.day.sameDay(this.props.selected),"datepicker__day--today":this.props.day.sameDay(i())});return n.createElement("div",{className:t,onClick:this.handleClick},this.props.day.day())}});t.exports=s},function(t,e,o){var n,i;/*! tether 0.6.5 */ !function(s,r){n=r,i="function"==typeof n?n.call(e,o,e,t):n,!(void 0!==i&&(t.exports=i))}(this,function(){return function(){var t,e,o,n,i,s,r,a,l,h,p,u,c,d,f,m,g,v,b,y={}.hasOwnProperty,C=[].indexOf||function(t){for(var e=0,o=this.length;o>e;e++)if(e in this&&this[e]===t)return e;return-1},w=[].slice;null==this.Tether&&(this.Tether={modules:[]}),u=function(t){var e,o,n,i,s;if(o=getComputedStyle(t).position,"fixed"===o)return t;for(n=void 0,e=t;e=e.parentNode;){try{i=getComputedStyle(e)}catch(r){}if(null==i)return e;if(/(auto|scroll)/.test(i.overflow+i.overflowY+i.overflowX)&&("absolute"!==o||"relative"===(s=i.position)||"absolute"===s||"fixed"===s))return e}return document.body},g=function(){var t;return t=0,function(){return t++}}(),b={},h=function(t){var e,n,s,r,a;if(s=t._tetherZeroElement,null==s&&(s=t.createElement("div"),s.setAttribute("data-tether-id",g()),i(s.style,{top:0,left:0,position:"absolute"}),t.body.appendChild(s),t._tetherZeroElement=s),e=s.getAttribute("data-tether-id"),null==b[e]){b[e]={},a=s.getBoundingClientRect();for(n in a)r=a[n],b[e][n]=r;o(function(){return b[e]=void 0})}return b[e]},d=null,r=function(t){var e,o,n,i,s,r,a;t===document?(o=document,t=document.documentElement):o=t.ownerDocument,n=o.documentElement,e={},a=t.getBoundingClientRect();for(i in a)r=a[i],e[i]=r;return s=h(o),e.top-=s.top,e.left-=s.left,null==e.width&&(e.width=document.body.scrollWidth-e.left-e.right),null==e.height&&(e.height=document.body.scrollHeight-e.top-e.bottom),e.top=e.top-n.clientTop,e.left=e.left-n.clientLeft,e.right=o.body.clientWidth-e.width-e.left,e.bottom=o.body.clientHeight-e.height-e.top,e},l=function(t){return t.offsetParent||document.documentElement},p=function(){var t,e,o,n,s;return t=document.createElement("div"),t.style.width="100%",t.style.height="200px",e=document.createElement("div"),i(e.style,{position:"absolute",top:0,left:0,pointerEvents:"none",visibility:"hidden",width:"200px",height:"150px",overflow:"hidden"}),e.appendChild(t),document.body.appendChild(e),n=t.offsetWidth,e.style.overflow="scroll",s=t.offsetWidth,n===s&&(s=e.clientWidth),document.body.removeChild(e),o=n-s,{width:o,height:o}},i=function(t){var e,o,n,i,s,r,a;for(null==t&&(t={}),e=[],Array.prototype.push.apply(e,arguments),a=e.slice(1),s=0,r=a.length;r>s;s++)if(n=a[s])for(o in n)y.call(n,o)&&(i=n[o],t[o]=i);return t},f=function(t,e){var o,n,i,s,r,l;if(null!=t.classList){for(r=e.split(" "),l=[],i=0,s=r.length;s>i;i++)n=r[i],n.trim()&&l.push(t.classList.remove(n));return l}return o=a(t).replace(new RegExp("(^| )"+e.split(" ").join("|")+"( |$)","gi")," "),m(t,o)},e=function(t,e){var o,n,i,s,r;if(null!=t.classList){for(s=e.split(" "),r=[],n=0,i=s.length;i>n;n++)o=s[n],o.trim()&&r.push(t.classList.add(o));return r}return f(t,e),o=a(t)+(" "+e),m(t,o)},c=function(t,e){return null!=t.classList?t.classList.contains(e):new RegExp("(^| )"+e+"( |$)","gi").test(a(t))},a=function(t){return t.className instanceof SVGAnimatedString?t.className.baseVal:t.className},m=function(t,e){return t.setAttribute("class",e)},v=function(t,o,n){var i,s,r,a,l,h;for(s=0,a=n.length;a>s;s++)i=n[s],C.call(o,i)<0&&c(t,i)&&f(t,i);for(h=[],r=0,l=o.length;l>r;r++)i=o[r],h.push(c(t,i)?void 0:e(t,i));return h},n=[],o=function(t){return n.push(t)},s=function(){var t,e;for(e=[];t=n.pop();)e.push(t());return e},t=function(){function t(){}return t.prototype.on=function(t,e,o,n){var i;return null==n&&(n=!1),null==this.bindings&&(this.bindings={}),null==(i=this.bindings)[t]&&(i[t]=[]),this.bindings[t].push({handler:e,ctx:o,once:n})},t.prototype.once=function(t,e,o){return this.on(t,e,o,!0)},t.prototype.off=function(t,e){var o,n,i;if(null!=(null!=(n=this.bindings)?n[t]:void 0)){if(null==e)return delete this.bindings[t];for(o=0,i=[];o<this.bindings[t].length;)i.push(this.bindings[t][o].handler===e?this.bindings[t].splice(o,1):o++);return i}},t.prototype.trigger=function(){var t,e,o,n,i,s,r,a,l;if(o=arguments[0],t=2<=arguments.length?w.call(arguments,1):[],null!=(r=this.bindings)?r[o]:void 0){for(i=0,l=[];i<this.bindings[o].length;)a=this.bindings[o][i],n=a.handler,e=a.ctx,s=a.once,n.apply(null!=e?e:this,t),l.push(s?this.bindings[o].splice(i,1):i++);return l}},t}(),this.Tether.Utils={getScrollParent:u,getBounds:r,getOffsetParent:l,extend:i,addClass:e,removeClass:f,hasClass:c,updateClasses:v,defer:o,flush:s,uniqueId:g,Evented:t,getScrollBarSize:p}}.call(this),function(){var t,e,o,n,i,s,r,a,l,h,p,u,c,d,f,m,g,v,b,y,C,w,_,k,E,S,x,O,M,D=[].slice,T=function(t,e){return function(){return t.apply(e,arguments)}};if(null==this.Tether)throw new Error("You must include the utils.js file before tether.js");n=this.Tether,M=n.Utils,m=M.getScrollParent,g=M.getSize,d=M.getOuterSize,u=M.getBounds,c=M.getOffsetParent,h=M.extend,i=M.addClass,_=M.removeClass,S=M.updateClasses,l=M.defer,p=M.flush,f=M.getScrollBarSize,x=function(t,e,o){return null==o&&(o=1),t+o>=e&&e>=t-o},E=function(){var t,e,o,n,i;for(t=document.createElement("div"),i=["transform","webkitTransform","OTransform","MozTransform","msTransform"],o=0,n=i.length;n>o;o++)if(e=i[o],void 0!==t.style[e])return e}(),k=[],w=function(){var t,e,o;for(e=0,o=k.length;o>e;e++)t=k[e],t.position(!1);return p()},v=function(){var t;return null!=(t="undefined"!=typeof performance&&null!==performance&&"function"==typeof performance.now?performance.now():void 0)?t:+new Date},function(){var t,e,o,n,i,s,r,a,l;for(e=null,o=null,n=null,i=function(){if(null!=o&&o>16)return o=Math.min(o-16,250),void(n=setTimeout(i,250));if(!(null!=e&&v()-e<10))return null!=n&&(clearTimeout(n),n=null),e=v(),w(),o=v()-e},a=["resize","scroll","touchmove"],l=[],s=0,r=a.length;r>s;s++)t=a[s],l.push(window.addEventListener(t,i));return l}(),t={center:"center",left:"right",right:"left"},e={middle:"middle",top:"bottom",bottom:"top"},o={top:0,left:0,middle:"50%",center:"50%",bottom:"100%",right:"100%"},a=function(o,n){var i,s;return i=o.left,s=o.top,"auto"===i&&(i=t[n.left]),"auto"===s&&(s=e[n.top]),{left:i,top:s}},r=function(t){var e,n;return{left:null!=(e=o[t.left])?e:t.left,top:null!=(n=o[t.top])?n:t.top}},s=function(){var t,e,o,n,i,s,r;for(e=1<=arguments.length?D.call(arguments,0):[],o={top:0,left:0},i=0,s=e.length;s>i;i++)r=e[i],n=r.top,t=r.left,"string"==typeof n&&(n=parseFloat(n,10)),"string"==typeof t&&(t=parseFloat(t,10)),o.top+=n,o.left+=t;return o},b=function(t,e){return"string"==typeof t.left&&-1!==t.left.indexOf("%")&&(t.left=parseFloat(t.left,10)/100*e.width),"string"==typeof t.top&&-1!==t.top.indexOf("%")&&(t.top=parseFloat(t.top,10)/100*e.height),t},y=C=function(t){var e,o,n;return n=t.split(" "),o=n[0],e=n[1],{top:o,left:e}},O=function(){function t(t){this.position=T(this.position,this);var e,o,i,s,r;for(k.push(this),this.history=[],this.setOptions(t,!1),s=n.modules,o=0,i=s.length;i>o;o++)e=s[o],null!=(r=e.initialize)&&r.call(this);this.position()}return t.modules=[],t.prototype.getClass=function(t){var e,o;return(null!=(e=this.options.classes)?e[t]:void 0)?this.options.classes[t]:(null!=(o=this.options.classes)?o[t]:void 0)!==!1?this.options.classPrefix?""+this.options.classPrefix+"-"+t:t:""},t.prototype.setOptions=function(t,e){var o,n,s,r,a,l;for(this.options=t,null==e&&(e=!0),o={offset:"0 0",targetOffset:"0 0",targetAttachment:"auto auto",classPrefix:"tether"},this.options=h(o,this.options),a=this.options,this.element=a.element,this.target=a.target,this.targetModifier=a.targetModifier,"viewport"===this.target?(this.target=document.body,this.targetModifier="visible"):"scroll-handle"===this.target&&(this.target=document.body,this.targetModifier="scroll-handle"),l=["element","target"],s=0,r=l.length;r>s;s++){if(n=l[s],null==this[n])throw new Error("Tether Error: Both element and target must be defined");null!=this[n].jquery?this[n]=this[n][0]:"string"==typeof this[n]&&(this[n]=document.querySelector(this[n]))}if(i(this.element,this.getClass("element")),i(this.target,this.getClass("target")),!this.options.attachment)throw new Error("Tether Error: You must provide an attachment");return this.targetAttachment=y(this.options.targetAttachment),this.attachment=y(this.options.attachment),this.offset=C(this.options.offset),this.targetOffset=C(this.options.targetOffset),null!=this.scrollParent&&this.disable(),this.scrollParent="scroll-handle"===this.targetModifier?this.target:m(this.target),this.options.enabled!==!1?this.enable(e):void 0},t.prototype.getTargetBounds=function(){var t,e,o,n,i,s,r,a,l;if(null==this.targetModifier)return u(this.target);switch(this.targetModifier){case"visible":return this.target===document.body?{top:pageYOffset,left:pageXOffset,height:innerHeight,width:innerWidth}:(t=u(this.target),i={height:t.height,width:t.width,top:t.top,left:t.left},i.height=Math.min(i.height,t.height-(pageYOffset-t.top)),i.height=Math.min(i.height,t.height-(t.top+t.height-(pageYOffset+innerHeight))),i.height=Math.min(innerHeight,i.height),i.height-=2,i.width=Math.min(i.width,t.width-(pageXOffset-t.left)),i.width=Math.min(i.width,t.width-(t.left+t.width-(pageXOffset+innerWidth))),i.width=Math.min(innerWidth,i.width),i.width-=2,i.top<pageYOffset&&(i.top=pageYOffset),i.left<pageXOffset&&(i.left=pageXOffset),i);case"scroll-handle":return l=this.target,l===document.body?(l=document.documentElement,t={left:pageXOffset,top:pageYOffset,height:innerHeight,width:innerWidth}):t=u(l),a=getComputedStyle(l),o=l.scrollWidth>l.clientWidth||"scroll"===[a.overflow,a.overflowX]||this.target!==document.body,s=0,o&&(s=15),n=t.height-parseFloat(a.borderTopWidth)-parseFloat(a.borderBottomWidth)-s,i={width:15,height:.975*n*(n/l.scrollHeight),left:t.left+t.width-parseFloat(a.borderLeftWidth)-15},e=0,408>n&&this.target===document.body&&(e=-11e-5*Math.pow(n,2)-.00727*n+22.58),this.target!==document.body&&(i.height=Math.max(i.height,24)),r=this.target.scrollTop/(l.scrollHeight-n),i.top=r*(n-i.height-e)+t.top+parseFloat(a.borderTopWidth),this.target===document.body&&(i.height=Math.max(i.height,24)),i}},t.prototype.clearCache=function(){return this._cache={}},t.prototype.cache=function(t,e){return null==this._cache&&(this._cache={}),null==this._cache[t]&&(this._cache[t]=e.call(this)),this._cache[t]},t.prototype.enable=function(t){return null==t&&(t=!0),i(this.target,this.getClass("enabled")),i(this.element,this.getClass("enabled")),this.enabled=!0,this.scrollParent!==document&&this.scrollParent.addEventListener("scroll",this.position),t?this.position():void 0},t.prototype.disable=function(){return _(this.target,this.getClass("enabled")),_(this.element,this.getClass("enabled")),this.enabled=!1,null!=this.scrollParent?this.scrollParent.removeEventListener("scroll",this.position):void 0},t.prototype.destroy=function(){var t,e,o,n,i;for(this.disable(),i=[],t=o=0,n=k.length;n>o;t=++o){if(e=k[t],e===this){k.splice(t,1);break}i.push(void 0)}return i},t.prototype.updateAttachClasses=function(t,e){var o,n,i,s,r,a,h,p,u,c=this;for(null==t&&(t=this.attachment),null==e&&(e=this.targetAttachment),s=["left","top","bottom","right","middle","center"],(null!=(u=this._addAttachClasses)?u.length:void 0)&&this._addAttachClasses.splice(0,this._addAttachClasses.length),o=null!=this._addAttachClasses?this._addAttachClasses:this._addAttachClasses=[],t.top&&o.push(""+this.getClass("element-attached")+"-"+t.top),t.left&&o.push(""+this.getClass("element-attached")+"-"+t.left),e.top&&o.push(""+this.getClass("target-attached")+"-"+e.top),e.left&&o.push(""+this.getClass("target-attached")+"-"+e.left),n=[],r=0,h=s.length;h>r;r++)i=s[r],n.push(""+this.getClass("element-attached")+"-"+i);for(a=0,p=s.length;p>a;a++)i=s[a],n.push(""+this.getClass("target-attached")+"-"+i);return l(function(){return null!=c._addAttachClasses?(S(c.element,c._addAttachClasses,n),S(c.target,c._addAttachClasses,n),c._addAttachClasses=void 0):void 0})},t.prototype.position=function(t){var e,o,i,l,h,d,m,g,v,y,C,w,_,k,E,S,x,O,M,D,T,W,F,N,A,P,Y,z,B,L,H,I,X,q,j,R=this;if(null==t&&(t=!0),this.enabled){for(this.clearCache(),D=a(this.targetAttachment,this.attachment),this.updateAttachClasses(this.attachment,D),e=this.cache("element-bounds",function(){return u(R.element)}),A=e.width,i=e.height,0===A&&0===i&&null!=this.lastSize?(L=this.lastSize,A=L.width,i=L.height):this.lastSize={width:A,height:i},F=W=this.cache("target-bounds",function(){return R.getTargetBounds()}),v=b(r(this.attachment),{width:A,height:i}),T=b(r(D),F),h=b(this.offset,{width:A,height:i}),d=b(this.targetOffset,F),v=s(v,h),T=s(T,d),l=W.left+T.left-v.left,N=W.top+T.top-v.top,H=n.modules,P=0,z=H.length;z>P;P++)if(m=H[P],E=m.position.call(this,{left:l,top:N,targetAttachment:D,targetPos:W,attachment:this.attachment,elementPos:e,offset:v,targetOffset:T,manualOffset:h,manualTargetOffset:d,scrollbarSize:O}),null!=E&&"object"==typeof E){if(E===!1)return!1;N=E.top,l=E.left}if(g={page:{top:N,left:l},viewport:{top:N-pageYOffset,bottom:pageYOffset-N-i+innerHeight,left:l-pageXOffset,right:pageXOffset-l-A+innerWidth}},document.body.scrollWidth>window.innerWidth&&(O=this.cache("scrollbar-size",f),g.viewport.bottom-=O.height),document.body.scrollHeight>window.innerHeight&&(O=this.cache("scrollbar-size",f),g.viewport.right-=O.width),(""!==(I=document.body.style.position)&&"static"!==I||""!==(X=document.body.parentElement.style.position)&&"static"!==X)&&(g.page.bottom=document.body.scrollHeight-N-i,g.page.right=document.body.scrollWidth-l-A),(null!=(q=this.options.optimizations)?q.moveElement:void 0)!==!1&&null==this.targetModifier){for(C=this.cache("target-offsetparent",function(){return c(R.target)}),k=this.cache("target-offsetparent-bounds",function(){return u(C)}),_=getComputedStyle(C),o=getComputedStyle(this.element),w=k,y={},j=["Top","Left","Bottom","Right"],Y=0,B=j.length;B>Y;Y++)M=j[Y],y[M.toLowerCase()]=parseFloat(_["border"+M+"Width"]);k.right=document.body.scrollWidth-k.left-w.width+y.right,k.bottom=document.body.scrollHeight-k.top-w.height+y.bottom,g.page.top>=k.top+y.top&&g.page.bottom>=k.bottom&&g.page.left>=k.left+y.left&&g.page.right>=k.right&&(x=C.scrollTop,S=C.scrollLeft,g.offset={top:g.page.top-k.top+x-y.top,left:g.page.left-k.left+S-y.left})}return this.move(g),this.history.unshift(g),this.history.length>3&&this.history.pop(),t&&p(),!0}},t.prototype.move=function(t){var e,o,n,i,s,r,a,p,u,d,f,m,g,v,b,y,C,w=this;if(null!=this.element.parentNode){p={};for(d in t){p[d]={};for(i in t[d]){for(n=!1,y=this.history,v=0,b=y.length;b>v;v++)if(a=y[v],!x(null!=(C=a[d])?C[i]:void 0,t[d][i])){n=!0;break}n||(p[d][i]=!0)}}e={top:"",left:"",right:"",bottom:""},u=function(t,o){var n,i,s;return(null!=(s=w.options.optimizations)?s.gpu:void 0)===!1?(t.top?e.top=""+o.top+"px":e.bottom=""+o.bottom+"px",t.left?e.left=""+o.left+"px":e.right=""+o.right+"px"):(t.top?(e.top=0,i=o.top):(e.bottom=0,i=-o.bottom),t.left?(e.left=0,n=o.left):(e.right=0,n=-o.right),e[E]="translateX("+Math.round(n)+"px) translateY("+Math.round(i)+"px)","msTransform"!==E?e[E]+=" translateZ(0)":void 0)},s=!1,(p.page.top||p.page.bottom)&&(p.page.left||p.page.right)?(e.position="absolute",u(p.page,t.page)):(p.viewport.top||p.viewport.bottom)&&(p.viewport.left||p.viewport.right)?(e.position="fixed",u(p.viewport,t.viewport)):null!=p.offset&&p.offset.top&&p.offset.left?(e.position="absolute",r=this.cache("target-offsetparent",function(){return c(w.target)}),c(this.element)!==r&&l(function(){return w.element.parentNode.removeChild(w.element),r.appendChild(w.element)}),u(p.offset,t.offset),s=!0):(e.position="absolute",u({top:!0,left:!0},t.page)),s||"BODY"===this.element.parentNode.tagName||(this.element.parentNode.removeChild(this.element),document.body.appendChild(this.element)),g={},m=!1;for(i in e)f=e[i],o=this.element.style[i],""===o||""===f||"top"!==i&&"left"!==i&&"bottom"!==i&&"right"!==i||(o=parseFloat(o),f=parseFloat(f)),o!==f&&(m=!0,g[i]=e[i]);return m?l(function(){return h(w.element.style,g)}):void 0}},t}(),n.position=w,this.Tether=h(O,n)}.call(this),function(){var t,e,o,n,i,s,r,a,l,h,p=[].indexOf||function(t){for(var e=0,o=this.length;o>e;e++)if(e in this&&this[e]===t)return e;return-1};h=this.Tether.Utils,r=h.getOuterSize,s=h.getBounds,a=h.getSize,n=h.extend,l=h.updateClasses,o=h.defer,e={left:"right",right:"left",top:"bottom",bottom:"top",middle:"middle"},t=["left","top","right","bottom"],i=function(e,o){var n,i,r,a,l,h,p;if("scrollParent"===o?o=e.scrollParent:"window"===o&&(o=[pageXOffset,pageYOffset,innerWidth+pageXOffset,innerHeight+pageYOffset]),o===document&&(o=o.documentElement),null!=o.nodeType)for(i=a=s(o),l=getComputedStyle(o),o=[i.left,i.top,a.width+i.left,a.height+i.top],n=h=0,p=t.length;p>h;n=++h)r=t[n],r=r[0].toUpperCase()+r.substr(1),"Top"===r||"Left"===r?o[n]+=parseFloat(l["border"+r+"Width"]):o[n]-=parseFloat(l["border"+r+"Width"]);return o},this.Tether.modules.push({position:function(e){var r,a,h,u,c,d,f,m,g,v,b,y,C,w,_,k,E,S,x,O,M,D,T,W,F,N,A,P,Y,z,B,L,H,I,X,q,j,R,U,V,K,Z,$,G,J,Q,tt,et=this;if(N=e.top,b=e.left,M=e.targetAttachment,!this.options.constraints)return!0;for(S=function(e){var o,n,i,s;for(et.removeClass(e),s=[],n=0,i=t.length;i>n;n++)o=t[n],s.push(et.removeClass(""+e+"-"+o));return s},V=this.cache("element-bounds",function(){return s(et.element)}),v=V.height,A=V.width,0===A&&0===v&&null!=this.lastSize&&(K=this.lastSize,A=K.width,v=K.height),T=this.cache("target-bounds",function(){return et.getTargetBounds()}),D=T.height,W=T.width,O={},g={},a=[this.getClass("pinned"),this.getClass("out-of-bounds")],Z=this.options.constraints,P=0,L=Z.length;L>P;P++)m=Z[P],m.outOfBoundsClass&&a.push(m.outOfBoundsClass),m.pinnedClass&&a.push(m.pinnedClass);for(Y=0,H=a.length;H>Y;Y++)for(f=a[Y],$=["left","top","right","bottom"],z=0,I=$.length;I>z;z++)x=$[z],a.push(""+f+"-"+x);for(r=[],O=n({},M),g=n({},this.attachment),G=this.options.constraints,B=0,X=G.length;X>B;B++){if(m=G[B],F=m.to,h=m.attachment,_=m.pin,null==h&&(h=""),p.call(h," ")>=0?(J=h.split(" "),d=J[0],c=J[1]):c=d=h,u=i(this,F),("target"===d||"both"===d)&&(N<u[1]&&"top"===O.top&&(N+=D,O.top="bottom"),N+v>u[3]&&"bottom"===O.top&&(N-=D,O.top="top")),"together"===d&&(N<u[1]&&"top"===O.top&&("bottom"===g.top?(N+=D,O.top="bottom",N+=v,g.top="top"):"top"===g.top&&(N+=D,O.top="bottom",N-=v,g.top="bottom")),N+v>u[3]&&"bottom"===O.top&&("top"===g.top?(N-=D,O.top="top",N-=v,g.top="bottom"):"bottom"===g.top&&(N-=D,O.top="top",N+=v,g.top="top")),"middle"===O.top&&(N+v>u[3]&&"top"===g.top?(N-=v,g.top="bottom"):N<u[1]&&"bottom"===g.top&&(N+=v,g.top="top"))),("target"===c||"both"===c)&&(b<u[0]&&"left"===O.left&&(b+=W,O.left="right"),b+A>u[2]&&"right"===O.left&&(b-=W,O.left="left")),"together"===c&&(b<u[0]&&"left"===O.left?"right"===g.left?(b+=W,O.left="right",b+=A,g.left="left"):"left"===g.left&&(b+=W,O.left="right",b-=A,g.left="right"):b+A>u[2]&&"right"===O.left?"left"===g.left?(b-=W,O.left="left",b-=A,g.left="right"):"right"===g.left&&(b-=W,O.left="left",b+=A,g.left="left"):"center"===O.left&&(b+A>u[2]&&"left"===g.left?(b-=A,g.left="right"):b<u[0]&&"right"===g.left&&(b+=A,g.left="left"))),("element"===d||"both"===d)&&(N<u[1]&&"bottom"===g.top&&(N+=v,g.top="top"),N+v>u[3]&&"top"===g.top&&(N-=v,g.top="bottom")),("element"===c||"both"===c)&&(b<u[0]&&"right"===g.left&&(b+=A,g.left="left"),b+A>u[2]&&"left"===g.left&&(b-=A,g.left="right")),"string"==typeof _?_=function(){var t,e,o,n;for(o=_.split(","),n=[],e=0,t=o.length;t>e;e++)w=o[e],n.push(w.trim());return n}():_===!0&&(_=["top","left","right","bottom"]),_||(_=[]),k=[],y=[],N<u[1]&&(p.call(_,"top")>=0?(N=u[1],k.push("top")):y.push("top")),N+v>u[3]&&(p.call(_,"bottom")>=0?(N=u[3]-v,k.push("bottom")):y.push("bottom")),b<u[0]&&(p.call(_,"left")>=0?(b=u[0],k.push("left")):y.push("left")),b+A>u[2]&&(p.call(_,"right")>=0?(b=u[2]-A,k.push("right")):y.push("right")),k.length)for(E=null!=(Q=this.options.pinnedClass)?Q:this.getClass("pinned"),r.push(E),R=0,q=k.length;q>R;R++)x=k[R],r.push(""+E+"-"+x);if(y.length)for(C=null!=(tt=this.options.outOfBoundsClass)?tt:this.getClass("out-of-bounds"),r.push(C),U=0,j=y.length;j>U;U++)x=y[U],r.push(""+C+"-"+x);(p.call(k,"left")>=0||p.call(k,"right")>=0)&&(g.left=O.left=!1),(p.call(k,"top")>=0||p.call(k,"bottom")>=0)&&(g.top=O.top=!1),(O.top!==M.top||O.left!==M.left||g.top!==this.attachment.top||g.left!==this.attachment.left)&&this.updateAttachClasses(g,O)}return o(function(){return l(et.target,r,a),l(et.element,r,a)}),{top:N,left:b}}})}.call(this),function(){var t,e,o,n;n=this.Tether.Utils,e=n.getBounds,o=n.updateClasses,t=n.defer,this.Tether.modules.push({position:function(n){var i,s,r,a,l,h,p,u,c,d,f,m,g,v,b,y,C,w,_,k,E,S,x,O,M,D=this;if(f=n.top,h=n.left,E=this.cache("element-bounds",function(){return e(D.element)}),l=E.height,m=E.width,d=this.getTargetBounds(),a=f+l,p=h+m,i=[],f<=d.bottom&&a>=d.top)for(S=["left","right"],g=0,C=S.length;C>g;g++)u=S[g],((x=d[u])===h||x===p)&&i.push(u);if(h<=d.right&&p>=d.left)for(O=["top","bottom"],v=0,w=O.length;w>v;v++)u=O[v],((M=d[u])===f||M===a)&&i.push(u);for(r=[],s=[],c=["left","top","right","bottom"],r.push(this.getClass("abutted")),b=0,_=c.length;_>b;b++)u=c[b],r.push(""+this.getClass("abutted")+"-"+u);for(i.length&&s.push(this.getClass("abutted")),y=0,k=i.length;k>y;y++)u=i[y],s.push(""+this.getClass("abutted")+"-"+u);return t(function(){return o(D.target,s,r),o(D.element,s,r)}),!0}})}.call(this),function(){this.Tether.modules.push({position:function(t){var e,o,n,i,s,r,a;return r=t.top,e=t.left,this.options.shift?(o=function(t){return"function"==typeof t?t.call(this,{top:r,left:e}):t},n=o(this.options.shift),"string"==typeof n?(n=n.split(" "),n[1]||(n[1]=n[0]),s=n[0],i=n[1],s=parseFloat(s,10),i=parseFloat(i,10)):(a=[n.top,n.left],s=a[0],i=a[1]),r+=s,e+=i,{top:r,left:e}):void 0}})}.call(this),this.Tether})}])});
blueprints/view/files/__test__/views/__name__View.spec.js
BrysonPacocha/SportsStats
import React from 'react' describe('(View) <%= pascalEntityName %>', () => { it('should exist', () => { }) })
src/index.js
rogerio-toledo/Weather-Forecast
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import ReduxPromise from 'redux-promise' import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
src/collections/BootTable/BootTable.js
shengnian/shengnian-ui-react
import React from 'react' import PropTypes from 'prop-types' import cx from 'classnames' import { mapToCssModules } from '../../lib/' const propTypes = { className: PropTypes.string, cssModule: PropTypes.object, size: PropTypes.string, bordered: PropTypes.bool, striped: PropTypes.bool, inverse: PropTypes.bool, hover: PropTypes.bool, reflow: PropTypes.bool, responsive: PropTypes.bool, tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), responsiveTag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), } const defaultProps = { tag: 'table', responsiveTag: 'div', } const Table = (props) => { const { className, cssModule, size, bordered, striped, inverse, hover, reflow, responsive, tag: Tag, responsiveTag: ResponsiveTag, ...attributes } = props const classes = mapToCssModules(cx( className, 'table', size ? `table-${size}` : false, bordered ? 'table-bordered' : false, striped ? 'table-striped' : false, inverse ? 'table-inverse' : false, hover ? 'table-hover' : false, reflow ? 'table-reflow' : false, ), cssModule) const table = <Tag {...attributes} className={classes} /> if (responsive) { return ( <ResponsiveTag className='table-responsive'>{table}</ResponsiveTag> ) } return table } Table.propTypes = propTypes Table.defaultProps = defaultProps export default Table
ajax/libs/6to5/1.14.1/browser.js
pombredanne/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.to5=e()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){(function(root,mod){if(typeof exports=="object"&&typeof module=="object")return mod(exports);if(typeof define=="function"&&define.amd)return define(["exports"],mod);mod(root.acorn||(root.acorn={}))})(this,function(exports){"use strict";exports.version="0.9.1";var options,input,inputLen,sourceFile;exports.parse=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();var startPos=options.locations?[tokPos,new Position]:tokPos;initParserState();return parseTopLevel(options.program||startNodeAt(startPos))};var defaultOptions=exports.defaultOptions={playground:false,ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};exports.parseExpressionAt=function(inpt,pos,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState(pos);initParserState();return parseExpression()};var isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"};function setOptions(opts){options={};for(var opt in defaultOptions)options[opt]=opts&&has(opts,opt)?opts[opt]:defaultOptions[opt];sourceFile=options.sourceFile||null;if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){tokens.push(token)}}if(isArray(options.onComment)){var comments=options.onComment;options.onComment=function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation;comment.loc.start=startLoc;comment.loc.end=endLoc}if(options.ranges)comment.range=[start,end];comments.push(comment)}}if(options.strictMode){strict=true}if(options.ecmaVersion>=7){isKeyword=isEcma7Keyword}else if(options.ecmaVersion===6){isKeyword=isEcma6Keyword}else{isKeyword=isEcma5AndLessKeyword}}var getLineInfo=exports.getLineInfo=function(input,offset){for(var line=1,cur=0;;){lineBreak.lastIndex=cur;var match=lineBreak.exec(input);if(match&&match.index<offset){++line;cur=match.index+match[0].length}else break}return{line:line,column:offset-cur}};function Token(){this.type=tokType;this.value=tokVal;this.start=tokStart;this.end=tokEnd;if(options.locations){this.loc=new SourceLocation;this.loc.end=tokEndLoc;this.startLoc=tokStartLoc;this.endLoc=tokEndLoc}if(options.ranges)this.range=[tokStart,tokEnd]}exports.Token=Token;exports.tokenize=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();skipSpace();function getToken(forceRegexp){lastEnd=tokEnd;readToken(forceRegexp);return new Token}getToken.jumpTo=function(pos,reAllowed){tokPos=pos;if(options.locations){tokCurLine=1;tokLineStart=lineBreak.lastIndex=0;var match;while((match=lineBreak.exec(input))&&match.index<pos){++tokCurLine;tokLineStart=match.index+match[0].length}}tokRegexpAllowed=reAllowed;skipSpace()};getToken.noRegexp=function(){tokRegexpAllowed=false};getToken.options=options;return getToken};var tokPos;var tokStart,tokEnd;var tokStartLoc,tokEndLoc;var tokType,tokVal;var tokRegexpAllowed;var tokCurLine,tokLineStart;var lastStart,lastEnd,lastEndLoc;var inFunction,inGenerator,inAsync,labels,strict,inXJSChild,inXJSTag,inXJSChildExpression;var metParenL;var inTemplate;function initParserState(){lastStart=lastEnd=tokPos;if(options.locations)lastEndLoc=new Position;inFunction=inGenerator=inAsync=strict=false;labels=[];skipSpace();readToken()}function raise(pos,message){var loc=getLineInfo(input,pos);message+=" ("+loc.line+":"+loc.column+")";var err=new SyntaxError(message);err.pos=pos;err.loc=loc;err.raisedAt=tokPos;throw err}var empty=[];var _num={type:"num"},_regexp={type:"regexp"},_string={type:"string"};var _name={type:"name"},_eof={type:"eof"};var _xjsName={type:"xjsName"},_xjsText={type:"xjsText"};var _break={keyword:"break"},_case={keyword:"case",beforeExpr:true},_catch={keyword:"catch"};var _continue={keyword:"continue"},_debugger={keyword:"debugger"},_default={keyword:"default"};var _do={keyword:"do",isLoop:true},_else={keyword:"else",beforeExpr:true};var _finally={keyword:"finally"},_for={keyword:"for",isLoop:true},_function={keyword:"function"};var _if={keyword:"if"},_return={keyword:"return",beforeExpr:true},_switch={keyword:"switch"};var _throw={keyword:"throw",beforeExpr:true},_try={keyword:"try"},_var={keyword:"var"};var _let={keyword:"let"},_const={keyword:"const"};var _while={keyword:"while",isLoop:true},_with={keyword:"with"},_new={keyword:"new",beforeExpr:true};var _this={keyword:"this"};var _class={keyword:"class"},_extends={keyword:"extends",beforeExpr:true};var _export={keyword:"export"},_import={keyword:"import"};var _yield={keyword:"yield",beforeExpr:true};var _async={keyword:"async"},_await={keyword:"await",beforeExpr:true};var _null={keyword:"null",atomValue:null},_true={keyword:"true",atomValue:true};var _false={keyword:"false",atomValue:false};var _in={keyword:"in",binop:7,beforeExpr:true};var keywordTypes={"break":_break,"case":_case,"catch":_catch,"continue":_continue,"debugger":_debugger,"default":_default,"do":_do,"else":_else,"finally":_finally,"for":_for,"function":_function,"if":_if,"return":_return,"switch":_switch,"throw":_throw,"try":_try,"var":_var,let:_let,"const":_const,"while":_while,"with":_with,"null":_null,"true":_true,"false":_false,"new":_new,"in":_in,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:true},"this":_this,"typeof":{keyword:"typeof",prefix:true,beforeExpr:true},"void":{keyword:"void",prefix:true,beforeExpr:true},"delete":{keyword:"delete",prefix:true,beforeExpr:true},"class":_class,"extends":_extends,"export":_export,"import":_import,"yield":_yield,await:_await,async:_async};var _bracketL={type:"[",beforeExpr:true},_bracketR={type:"]"},_braceL={type:"{",beforeExpr:true};var _braceR={type:"}"},_parenL={type:"(",beforeExpr:true},_parenR={type:")"};var _comma={type:",",beforeExpr:true},_semi={type:";",beforeExpr:true};var _colon={type:":",beforeExpr:true},_dot={type:"."},_question={type:"?",beforeExpr:true};var _arrow={type:"=>",beforeExpr:true},_bquote={type:"`"},_dollarBraceL={type:"${",beforeExpr:true};var _ltSlash={type:"</"};var _ellipsis={type:"...",prefix:true,beforeExpr:true};var _doubleColon={type:"::",beforeExpr:true};var _slash={binop:10,beforeExpr:true},_eq={isAssign:true,beforeExpr:true};var _assign={isAssign:true,beforeExpr:true};var _incDec={postfix:true,prefix:true,isUpdate:true},_prefix={prefix:true,beforeExpr:true};var _logicalOR={binop:1,beforeExpr:true};var _logicalAND={binop:2,beforeExpr:true};var _bitwiseOR={binop:3,beforeExpr:true};var _bitwiseXOR={binop:4,beforeExpr:true};var _bitwiseAND={binop:5,beforeExpr:true};var _equality={binop:6,beforeExpr:true};var _relational={binop:7,beforeExpr:true};var _bitShift={binop:8,beforeExpr:true};var _plusMin={binop:9,prefix:true,beforeExpr:true};var _modulo={binop:10,beforeExpr:true};var _star={binop:10,beforeExpr:true};var _exponent={binop:10,beforeExpr:true};var _lt={binop:7,beforeExpr:true},_gt={binop:7,beforeExpr:true};exports.tokTypes={bracketL:_bracketL,bracketR:_bracketR,braceL:_braceL,braceR:_braceR,parenL:_parenL,parenR:_parenR,comma:_comma,semi:_semi,colon:_colon,dot:_dot,ellipsis:_ellipsis,question:_question,slash:_slash,eq:_eq,name:_name,eof:_eof,num:_num,regexp:_regexp,string:_string,arrow:_arrow,bquote:_bquote,dollarBraceL:_dollarBraceL,star:_star,assign:_assign,xjsName:_xjsName,xjsText:_xjsText,doubleColon:_doubleColon,exponent:_exponent};for(var kw in keywordTypes)exports.tokTypes["_"+kw]=keywordTypes[kw];function makePredicate(words){words=words.split(" ");var f="",cats=[];out:for(var i=0;i<words.length;++i){for(var j=0;j<cats.length;++j)if(cats[j][0].length==words[i].length){cats[j].push(words[i]);continue out}cats.push([words[i]])}function compareTo(arr){if(arr.length==1)return f+="return str === "+JSON.stringify(arr[0])+";";f+="switch(str){";for(var i=0;i<arr.length;++i)f+="case "+JSON.stringify(arr[i])+":";f+="return true}return false;"}if(cats.length>3){cats.sort(function(a,b){return b.length-a.length});f+="switch(str.length){";for(var i=0;i<cats.length;++i){var cat=cats[i];f+="case "+cat[0].length+":";compareTo(cat)}f+="}"}else{compareTo(words)}return new Function("str",f)}var isReservedWord3=makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile");var isReservedWord5=makePredicate("class enum extends super const export import");var isStrictReservedWord=makePredicate("implements interface let package private protected public static yield");var isStrictBadIdWord=makePredicate("eval arguments");var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var isEcma5AndLessKeyword=makePredicate(ecma5AndLessKeywords);var ecma6AndLessKeywords=ecma5AndLessKeywords+" let const class extends export import yield";var isEcma6Keyword=makePredicate(ecma6AndLessKeywords);var isEcma7Keyword=makePredicate(ecma6AndLessKeywords+" async await");var isKeyword=isEcma5AndLessKeyword;var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var nonASCIIidentifierChars="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");var newline=/[\n\r\u2028\u2029]/;var lineBreak=/\r\n|[\n\r\u2028\u2029]/g;var isIdentifierStart=exports.isIdentifierStart=function(code){if(code<65)return code===36;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))};var isIdentifierChar=exports.isIdentifierChar=function(code){if(code<48)return code===36;if(code<58)return true;if(code<65)return false;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))};function Position(){this.line=tokCurLine;this.column=tokPos-tokLineStart}function initTokenState(pos){if(pos){tokPos=pos;tokLineStart=Math.max(0,input.lastIndexOf("\n",pos));tokCurLine=input.slice(0,tokLineStart).split(newline).length}else{tokCurLine=1;tokPos=tokLineStart=0}tokRegexpAllowed=true;metParenL=0;inTemplate=inXJSChild=inXJSTag=false}function finishToken(type,val,shouldSkipSpace){tokEnd=tokPos;if(options.locations)tokEndLoc=new Position;tokType=type;if(shouldSkipSpace!==false&&!(inXJSChild&&tokType!==_braceL)){skipSpace()}tokVal=val;tokRegexpAllowed=type.beforeExpr;if(options.onToken){options.onToken(new Token)}}function skipBlockComment(){var startLoc=options.onComment&&options.locations&&new Position;var start=tokPos,end=input.indexOf("*/",tokPos+=2);if(end===-1)raise(tokPos-2,"Unterminated comment");tokPos=end+2;if(options.locations){lineBreak.lastIndex=start;var match;while((match=lineBreak.exec(input))&&match.index<tokPos){++tokCurLine;tokLineStart=match.index+match[0].length}}if(options.onComment)options.onComment(true,input.slice(start+2,end),start,tokPos,startLoc,options.locations&&new Position)}function skipLineComment(startSkip){var start=tokPos;var startLoc=options.onComment&&options.locations&&new Position;var ch=input.charCodeAt(tokPos+=startSkip);while(tokPos<inputLen&&ch!==10&&ch!==13&&ch!==8232&&ch!==8233){++tokPos;ch=input.charCodeAt(tokPos)}if(options.onComment)options.onComment(false,input.slice(start+startSkip,tokPos),start,tokPos,startLoc,options.locations&&new Position)}function skipSpace(){while(tokPos<inputLen){var ch=input.charCodeAt(tokPos);if(ch===32){++tokPos}else if(ch===13){++tokPos;var next=input.charCodeAt(tokPos);if(next===10){++tokPos}if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch===10||ch===8232||ch===8233){++tokPos;if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch>8&&ch<14){++tokPos}else if(ch===47){var next=input.charCodeAt(tokPos+1);if(next===42){skipBlockComment()}else if(next===47){skipLineComment(2)}else break}else if(ch===160){++tokPos}else if(ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++tokPos}else{break}}}function readToken_dot(){var next=input.charCodeAt(tokPos+1);if(next>=48&&next<=57)return readNumber(true);var next2=input.charCodeAt(tokPos+2);if(options.ecmaVersion>=6&&next===46&&next2===46){tokPos+=3;return finishToken(_ellipsis)}else{++tokPos;return finishToken(_dot)}}function readToken_slash(){var next=input.charCodeAt(tokPos+1);if(tokRegexpAllowed){++tokPos;return readRegexp()}if(next===61)return finishOp(_assign,2);return finishOp(_slash,1)}function readToken_modulo(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_modulo,1)}function readToken_mult(){var type=_star;var width=1;var next=input.charCodeAt(tokPos+1);if(options.ecmaVersion>=7&&next===42){width++;next=input.charCodeAt(tokPos+2);type=_exponent}if(next===61){width++;type=_assign}return finishOp(type,width)}function readToken_pipe_amp(code){var next=input.charCodeAt(tokPos+1);if(next===code)return finishOp(code===124?_logicalOR:_logicalAND,2);if(next===61)return finishOp(_assign,2);return finishOp(code===124?_bitwiseOR:_bitwiseAND,1)}function readToken_caret(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_bitwiseXOR,1)}function readToken_plus_min(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(next==45&&input.charCodeAt(tokPos+2)==62&&newline.test(input.slice(lastEnd,tokPos))){skipLineComment(3);skipSpace();return readToken()}return finishOp(_incDec,2)}if(next===61)return finishOp(_assign,2);return finishOp(_plusMin,1)}function readToken_lt_gt(code){var next=input.charCodeAt(tokPos+1);var size=1;if(next===code){size=code===62&&input.charCodeAt(tokPos+2)===62?3:2;if(input.charCodeAt(tokPos+size)===61)return finishOp(_assign,size+1);return finishOp(_bitShift,size)}if(next==33&&code==60&&input.charCodeAt(tokPos+2)==45&&input.charCodeAt(tokPos+3)==45){skipLineComment(4);skipSpace();return readToken()}if(next===61){size=input.charCodeAt(tokPos+2)===61?3:2;return finishOp(_relational,size)}if(next===47){size=2;return finishOp(_ltSlash,size)}return code===60?finishOp(_lt,size):finishOp(_gt,size,!inXJSTag)}function readToken_eq_excl(code){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_equality,input.charCodeAt(tokPos+2)===61?3:2);if(code===61&&next===62&&options.ecmaVersion>=6){tokPos+=2;return finishToken(_arrow)}return finishOp(code===61?_eq:_prefix,1)}function getTemplateToken(code){if(tokType===_string){if(code===96){++tokPos;return finishToken(_bquote)}else if(code===36&&input.charCodeAt(tokPos+1)===123){tokPos+=2;return finishToken(_dollarBraceL)}}if(code===125){++tokPos;return finishToken(_braceR,undefined,false)}return readTmplString()}function getTokenFromCode(code){switch(code){case 46:return readToken_dot();case 40:++tokPos;return finishToken(_parenL);case 41:++tokPos;return finishToken(_parenR);case 59:++tokPos;return finishToken(_semi);case 44:++tokPos;return finishToken(_comma);case 91:++tokPos;return finishToken(_bracketL);case 93:++tokPos;return finishToken(_bracketR);case 123:++tokPos;return finishToken(_braceL);case 125:++tokPos;return finishToken(_braceR,undefined,!inXJSChildExpression);case 63:++tokPos;return finishToken(_question);case 58:++tokPos;if(options.ecmaVersion>=7){var next=input.charCodeAt(tokPos);if(next===58){++tokPos;return finishToken(_doubleColon)}}return finishToken(_colon);case 96:if(options.ecmaVersion>=6){++tokPos;return finishToken(_bquote,undefined,false)}case 48:var next=input.charCodeAt(tokPos+1);if(next===120||next===88)return readRadixNumber(16);if(options.ecmaVersion>=6){if(next===111||next===79)return readRadixNumber(8);if(next===98||next===66)return readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return readNumber(false);case 34:case 39:return inXJSTag?readXJSStringLiteral():readString(code);case 47:return readToken_slash();case 37:return readToken_modulo();case 42:return readToken_mult();case 124:case 38:return readToken_pipe_amp(code);case 94:return readToken_caret();case 43:case 45:return readToken_plus_min(code);case 60:case 62:return readToken_lt_gt(code);case 61:case 33:return readToken_eq_excl(code);case 126:return finishOp(_prefix,1)}return false}function readToken(forceRegexp){if(!forceRegexp)tokStart=tokPos;else tokPos=tokStart+1;if(options.locations)tokStartLoc=new Position;if(forceRegexp)return readRegexp();if(tokPos>=inputLen)return finishToken(_eof);var code=input.charCodeAt(tokPos);if(inXJSChild&&tokType!==_braceL&&code!==60&&code!==123&&code!==125){return readXJSText(["<","{"])}if(inTemplate)return getTemplateToken(code);if(isIdentifierStart(code)||code===92)return readWord();var tok=getTokenFromCode(code);if(tok===false){var ch=String.fromCharCode(code);if(ch==="\\"||nonASCIIidentifierStart.test(ch))return readWord();raise(tokPos,"Unexpected character '"+ch+"'")}return tok}function finishOp(type,size,shouldSkipSpace){var str=input.slice(tokPos,tokPos+size);tokPos+=size;finishToken(type,str,shouldSkipSpace)}var regexpUnicodeSupport=false;try{new RegExp("￿","u");regexpUnicodeSupport=true}catch(e){}function readRegexp(){var content="",escaped,inClass,start=tokPos;for(;;){if(tokPos>=inputLen)raise(start,"Unterminated regular expression");var ch=nextChar();if(newline.test(ch))raise(start,"Unterminated regular expression");if(!escaped){if(ch==="[")inClass=true;else if(ch==="]"&&inClass)inClass=false;else if(ch==="/"&&!inClass)break;escaped=ch==="\\"}else escaped=false;++tokPos}var content=input.slice(start,tokPos);++tokPos;var mods=readWord1();var tmp=content;if(mods){var validFlags=/^[gmsiy]*$/;if(options.ecmaVersion>=6)validFlags=/^[gmsiyu]*$/;if(!validFlags.test(mods))raise(start,"Invalid regular expression flag");if(mods.indexOf("u")>=0&&!regexpUnicodeSupport){tmp=tmp.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}}try{new RegExp(tmp)}catch(e){if(e instanceof SyntaxError)raise(start,"Error parsing regular expression: "+e.message);raise(e)}try{var value=new RegExp(content,mods)}catch(err){value=null}return finishToken(_regexp,{pattern:content,flags:mods,value:value})}function readInt(radix,len){var start=tokPos,total=0;for(var i=0,e=len==null?Infinity:len;i<e;++i){var code=input.charCodeAt(tokPos),val;if(code>=97)val=code-97+10;else if(code>=65)val=code-65+10;else if(code>=48&&code<=57)val=code-48;else val=Infinity;if(val>=radix)break;++tokPos;total=total*radix+val}if(tokPos===start||len!=null&&tokPos-start!==len)return null;return total}function readRadixNumber(radix){tokPos+=2;var val=readInt(radix);if(val==null)raise(tokStart+2,"Expected number in radix "+radix);if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");return finishToken(_num,val)}function readNumber(startsWithDot){var start=tokPos,isFloat=false,octal=input.charCodeAt(tokPos)===48;if(!startsWithDot&&readInt(10)===null)raise(start,"Invalid number");if(input.charCodeAt(tokPos)===46){++tokPos;readInt(10);isFloat=true}var next=input.charCodeAt(tokPos);if(next===69||next===101){next=input.charCodeAt(++tokPos);if(next===43||next===45)++tokPos;if(readInt(10)===null)raise(start,"Invalid number");isFloat=true}if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");var str=input.slice(start,tokPos),val;if(isFloat)val=parseFloat(str);else if(!octal||str.length===1)val=parseInt(str,10);else if(/[89]/.test(str)||strict)raise(start,"Invalid number");else val=parseInt(str,8);return finishToken(_num,val)}function readCodePoint(){var ch=input.charCodeAt(tokPos),code;if(ch===123){if(options.ecmaVersion<6)unexpected();++tokPos;code=readHexChar(input.indexOf("}",tokPos)-tokPos);++tokPos;if(code>1114111)unexpected()}else{code=readHexChar(4)}if(code<=65535){return String.fromCharCode(code)}var cu1=(code-65536>>10)+55296;var cu2=(code-65536&1023)+56320;return String.fromCharCode(cu1,cu2)}function readString(quote){++tokPos;var out="";for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===quote){++tokPos;return finishToken(_string,out)}if(ch===92){out+=readEscapedChar()}else{++tokPos;if(newline.test(String.fromCharCode(ch))){raise(tokStart,"Unterminated string constant")}out+=String.fromCharCode(ch)}}}function readTmplString(){var out="";for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===96||ch===36&&input.charCodeAt(tokPos+1)===123)return finishToken(_string,out);if(ch===92){out+=readEscapedChar()}else{++tokPos;if(newline.test(String.fromCharCode(ch))){if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;ch=10}if(options.locations){++tokCurLine;tokLineStart=tokPos}}out+=String.fromCharCode(ch)}}}function readEscapedChar(){var ch=input.charCodeAt(++tokPos);var octal=/^[0-7]+/.exec(input.slice(tokPos,tokPos+3));if(octal)octal=octal[0];while(octal&&parseInt(octal,8)>255)octal=octal.slice(0,-1);if(octal==="0")octal=null;++tokPos;if(octal){if(strict)raise(tokPos-2,"Octal literal in strict mode");tokPos+=octal.length-1;return String.fromCharCode(parseInt(octal,8))}else{switch(ch){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(readHexChar(2));case 117:return readCodePoint();case 116:return" ";case 98:return"\b";case 118:return" ";case 102:return"\f";case 48:return"\x00";case 13:if(input.charCodeAt(tokPos)===10)++tokPos;case 10:if(options.locations){tokLineStart=tokPos;++tokCurLine}return"";default:return String.fromCharCode(ch)}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readXJSEntity(){var str="",count=0,entity;var ch=nextChar();if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");tokPos++;while(tokPos<inputLen&&count++<10){ch=nextChar();tokPos++;if(ch===";"){break}str+=ch}if(str[0]==="#"&&str[1]==="x"){entity=String.fromCharCode(parseInt(str.substr(2),16))}else if(str[0]==="#"){entity=String.fromCharCode(parseInt(str.substr(1),10))}else{entity=XHTMLEntities[str]}return entity}function readXJSText(stopChars){var str="";while(tokPos<inputLen){var ch=nextChar();if(stopChars.indexOf(ch)!==-1){break}if(ch==="&"){str+=readXJSEntity()}else{++tokPos;if(ch==="\r"&&nextChar()==="\n"){str+=ch;++tokPos;ch="\n"}if(ch==="\n"&&options.locations){tokLineStart=tokPos;++tokCurLine}str+=ch}}return finishToken(_xjsText,str)}function readXJSStringLiteral(){var quote=input.charCodeAt(tokPos);if(quote!==34&&quote!==39){raise("String literal must starts with a quote")}++tokPos;readXJSText([String.fromCharCode(quote)]);if(quote!==input.charCodeAt(tokPos)){unexpected()}++tokPos;return finishToken(tokType,tokVal)}function readHexChar(len){var n=readInt(16,len);if(n===null)raise(tokStart,"Bad character escape sequence");return n}var containsEsc;function readWord1(){containsEsc=false;var word,first=true,start=tokPos;for(;;){var ch=input.charCodeAt(tokPos);if(isIdentifierChar(ch)||inXJSTag&&ch===45){if(containsEsc)word+=nextChar();++tokPos}else if(ch===92&&!inXJSTag){if(!containsEsc)word=input.slice(start,tokPos);containsEsc=true;if(input.charCodeAt(++tokPos)!=117)raise(tokPos,"Expecting Unicode escape sequence \\uXXXX");++tokPos;var esc=readHexChar(4);var escStr=String.fromCharCode(esc);if(!escStr)raise(tokPos-1,"Invalid Unicode escape");if(!(first?isIdentifierStart(esc):isIdentifierChar(esc)))raise(tokPos-4,"Invalid Unicode escape");word+=escStr}else{break}first=false}return containsEsc?word:input.slice(start,tokPos)}function readWord(){var word=readWord1();var type=inXJSTag?_xjsName:_name;if(!containsEsc&&isKeyword(word))type=keywordTypes[word];return finishToken(type,word)}function next(){lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;readToken()}function setStrict(strct){strict=strct;tokPos=tokStart;if(options.locations){while(tokPos<tokLineStart){tokLineStart=input.lastIndexOf("\n",tokLineStart-2)+1;--tokCurLine}}skipSpace();readToken()}function Node(){this.type=null;this.start=tokStart;this.end=null}exports.Node=Node;function SourceLocation(){this.start=tokStartLoc;this.end=null;if(sourceFile!==null)this.source=sourceFile}function startNode(){var node=new Node;if(options.locations)node.loc=new SourceLocation;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[tokStart,0];return node}function storeCurrentPos(){return options.locations?[tokStart,tokStartLoc]:tokStart}function startNodeAt(pos){var node=new Node,start=pos;if(options.locations){node.loc=new SourceLocation;node.loc.start=start[1];start=pos[0]}node.start=start;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[start,0];return node}function finishNode(node,type){node.type=type;node.end=lastEnd;if(options.locations)node.loc.end=lastEndLoc;if(options.ranges)node.range[1]=lastEnd;return node}function isUseStrict(stmt){return options.ecmaVersion>=5&&stmt.type==="ExpressionStatement"&&stmt.expression.type==="Literal"&&stmt.expression.value==="use strict"}function eat(type){if(tokType===type){next();return true}else{return false}}function canInsertSemicolon(){return!options.strictSemicolons&&(tokType===_eof||tokType===_braceR||newline.test(input.slice(lastEnd,tokStart)))}function semicolon(){if(!eat(_semi)&&!canInsertSemicolon())unexpected()}function expect(type){eat(type)||unexpected()}function nextChar(){return input.charAt(tokPos)}function unexpected(pos){raise(pos!=null?pos:tokStart,"Unexpected token")}function has(obj,propName){return Object.prototype.hasOwnProperty.call(obj,propName)}function toAssignable(node,allowSpread,checkType){if(options.ecmaVersion>=6&&node){switch(node.type){case"Identifier":case"MemberExpression":break;case"ObjectExpression":node.type="ObjectPattern";for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(prop.type==="Property"&&prop.kind!=="init")unexpected(prop.key.start);toAssignable(prop.value,false,checkType)}break;case"ArrayExpression":node.type="ArrayPattern";for(var i=0,lastI=node.elements.length-1;i<=lastI;i++){toAssignable(node.elements[i],i===lastI,checkType)}break;case"SpreadElement":if(allowSpread){toAssignable(node.argument,false,checkType);checkSpreadAssign(node.argument)}else{unexpected(node.start)}break;default:if(checkType)unexpected(node.start)}}return node}function checkSpreadAssign(node){if(node.type!=="Identifier"&&node.type!=="ArrayPattern")unexpected(node.start)}function checkFunctionParam(param,nameHash){switch(param.type){case"Identifier":if(isStrictReservedWord(param.name)||isStrictBadIdWord(param.name))raise(param.start,"Defining '"+param.name+"' in strict mode");if(has(nameHash,param.name))raise(param.start,"Argument name clash in strict mode");nameHash[param.name]=true;break;case"ObjectPattern":for(var i=0;i<param.properties.length;i++)checkFunctionParam(param.properties[i].value,nameHash);break;case"ArrayPattern":for(var i=0;i<param.elements.length;i++){var elem=param.elements[i];if(elem)checkFunctionParam(elem,nameHash)}break}}function checkPropClash(prop,propHash){if(options.ecmaVersion>=6)return; var key=prop.key,name;switch(key.type){case"Identifier":name=key.name;break;case"Literal":name=String(key.value);break;default:return}var kind=prop.kind||"init",other;if(has(propHash,name)){other=propHash[name];var isGetSet=kind!=="init";if((strict||isGetSet)&&other[kind]||!(isGetSet^other.init))raise(key.start,"Redefinition of property")}else{other=propHash[name]={init:false,get:false,set:false}}other[kind]=true}function checkLVal(expr,isBinding){switch(expr.type){case"Identifier":if(strict&&(isStrictBadIdWord(expr.name)||isStrictReservedWord(expr.name)))raise(expr.start,isBinding?"Binding "+expr.name+" in strict mode":"Assigning to "+expr.name+" in strict mode");break;case"MemberExpression":if(!isBinding)break;case"ObjectPattern":for(var i=0;i<expr.properties.length;i++){var prop=expr.properties[i];if(prop.type==="Property")prop=prop.value;checkLVal(prop,isBinding)}break;case"ArrayPattern":for(var i=0;i<expr.elements.length;i++){var elem=expr.elements[i];if(elem)checkLVal(elem,isBinding)}break;case"SpreadProperty":case"SpreadElement":case"VirtualPropertyExpression":break;default:raise(expr.start,"Assigning to rvalue")}}function parseTopLevel(node){var first=true;if(!node.body)node.body=[];while(tokType!==_eof){var stmt=parseStatement();node.body.push(stmt);if(first&&isUseStrict(stmt))setStrict(true);first=false}lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;return finishNode(node,"Program")}var loopLabel={kind:"loop"},switchLabel={kind:"switch"};function parseStatement(){if(tokType===_slash||tokType===_assign&&tokVal=="/=")readToken(true);var starttype=tokType,node=startNode();switch(starttype){case _break:case _continue:return parseBreakContinueStatement(node,starttype.keyword);case _debugger:return parseDebuggerStatement(node);case _do:return parseDoStatement(node);case _for:return parseForStatement(node);case _async:return parseAsync(node,true);case _function:return parseFunctionStatement(node);case _class:return parseClass(node,true);case _if:return parseIfStatement(node);case _return:return parseReturnStatement(node);case _switch:return parseSwitchStatement(node);case _throw:return parseThrowStatement(node);case _try:return parseTryStatement(node);case _var:case _let:case _const:return parseVarStatement(node,starttype.keyword);case _while:return parseWhileStatement(node);case _with:return parseWithStatement(node);case _braceL:return parseBlock();case _semi:return parseEmptyStatement(node);case _export:return parseExport(node);case _import:return parseImport(node);default:var maybeName=tokVal,expr=parseExpression();if(starttype===_name&&expr.type==="Identifier"&&eat(_colon))return parseLabeledStatement(node,maybeName,expr);else return parseExpressionStatement(node,expr)}}function parseBreakContinueStatement(node,keyword){var isBreak=keyword=="break";next();if(eat(_semi)||canInsertSemicolon())node.label=null;else if(tokType!==_name)unexpected();else{node.label=parseIdent();semicolon()}for(var i=0;i<labels.length;++i){var lab=labels[i];if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind==="loop"))break;if(node.label&&isBreak)break}}if(i===labels.length)raise(node.start,"Unsyntactic "+keyword);return finishNode(node,isBreak?"BreakStatement":"ContinueStatement")}function parseDebuggerStatement(node){next();semicolon();return finishNode(node,"DebuggerStatement")}function parseDoStatement(node){next();labels.push(loopLabel);node.body=parseStatement();labels.pop();expect(_while);node.test=parseParenExpression();semicolon();return finishNode(node,"DoWhileStatement")}function parseForStatement(node){next();labels.push(loopLabel);expect(_parenL);if(tokType===_semi)return parseFor(node,null);if(tokType===_var||tokType===_let){var init=startNode(),varKind=tokType.keyword,isLet=tokType===_let;next();parseVar(init,true,varKind);finishNode(init,"VariableDeclaration");if((tokType===_in||options.ecmaVersion>=6&&tokType===_name&&tokVal==="of")&&init.declarations.length===1&&!(isLet&&init.declarations[0].init))return parseForIn(node,init);return parseFor(node,init)}var init=parseExpression(false,true);if(tokType===_in||options.ecmaVersion>=6&&tokType===_name&&tokVal==="of"){checkLVal(init);return parseForIn(node,init)}return parseFor(node,init)}function parseFunctionStatement(node){next();return parseFunction(node,true,false)}function parseAsync(node,isStatement){if(options.ecmaVersion<7){unexpected()}next();switch(tokType){case _function:next();return parseFunction(node,isStatement,true);if(!isStatement)unexpected();case _name:var id=parseIdent(tokType!==_name);if(eat(_arrow)){return parseArrowExpression(node,[id],true)}case _parenL:var oldParenL=++metParenL;var exprList=[];next();if(tokType!==_parenR){var val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){return parseArrowExpression(node,exprList,true)}default:unexpected()}}function parseIfStatement(node){next();node.test=parseParenExpression();node.consequent=parseStatement();node.alternate=eat(_else)?parseStatement():null;return finishNode(node,"IfStatement")}function parseReturnStatement(node){if(!inFunction&&!options.allowReturnOutsideFunction)raise(tokStart,"'return' outside of function");next();if(eat(_semi)||canInsertSemicolon())node.argument=null;else{node.argument=parseExpression();semicolon()}return finishNode(node,"ReturnStatement")}function parseSwitchStatement(node){next();node.discriminant=parseParenExpression();node.cases=[];expect(_braceL);labels.push(switchLabel);for(var cur,sawDefault;tokType!=_braceR;){if(tokType===_case||tokType===_default){var isCase=tokType===_case;if(cur)finishNode(cur,"SwitchCase");node.cases.push(cur=startNode());cur.consequent=[];next();if(isCase)cur.test=parseExpression();else{if(sawDefault)raise(lastStart,"Multiple default clauses");sawDefault=true;cur.test=null}expect(_colon)}else{if(!cur)unexpected();cur.consequent.push(parseStatement())}}if(cur)finishNode(cur,"SwitchCase");next();labels.pop();return finishNode(node,"SwitchStatement")}function parseThrowStatement(node){next();if(newline.test(input.slice(lastEnd,tokStart)))raise(lastEnd,"Illegal newline after throw");node.argument=parseExpression();semicolon();return finishNode(node,"ThrowStatement")}function parseTryStatement(node){next();node.block=parseBlock();node.handler=null;if(tokType===_catch){var clause=startNode();next();expect(_parenL);clause.param=parseIdent();if(strict&&isStrictBadIdWord(clause.param.name))raise(clause.param.start,"Binding "+clause.param.name+" in strict mode");expect(_parenR);clause.guard=null;clause.body=parseBlock();node.handler=finishNode(clause,"CatchClause")}node.guardedHandlers=empty;node.finalizer=eat(_finally)?parseBlock():null;if(!node.handler&&!node.finalizer)raise(node.start,"Missing catch or finally clause");return finishNode(node,"TryStatement")}function parseVarStatement(node,kind){next();parseVar(node,false,kind);semicolon();return finishNode(node,"VariableDeclaration")}function parseWhileStatement(node){next();node.test=parseParenExpression();labels.push(loopLabel);node.body=parseStatement();labels.pop();return finishNode(node,"WhileStatement")}function parseWithStatement(node){if(strict)raise(tokStart,"'with' in strict mode");next();node.object=parseParenExpression();node.body=parseStatement();return finishNode(node,"WithStatement")}function parseEmptyStatement(node){next();return finishNode(node,"EmptyStatement")}function parseLabeledStatement(node,maybeName,expr){for(var i=0;i<labels.length;++i)if(labels[i].name===maybeName)raise(expr.start,"Label '"+maybeName+"' is already declared");var kind=tokType.isLoop?"loop":tokType===_switch?"switch":null;labels.push({name:maybeName,kind:kind});node.body=parseStatement();labels.pop();node.label=expr;return finishNode(node,"LabeledStatement")}function parseExpressionStatement(node,expr){node.expression=expr;semicolon();return finishNode(node,"ExpressionStatement")}function parseParenExpression(){expect(_parenL);var val=parseExpression();expect(_parenR);return val}function parseBlock(allowStrict){var node=startNode(),first=true,oldStrict;node.body=[];expect(_braceL);while(!eat(_braceR)){var stmt=parseStatement();node.body.push(stmt);if(first&&allowStrict&&isUseStrict(stmt)){oldStrict=strict;setStrict(strict=true)}first=false}if(oldStrict===false)setStrict(false);return finishNode(node,"BlockStatement")}function parseFor(node,init){node.init=init;expect(_semi);node.test=tokType===_semi?null:parseExpression();expect(_semi);node.update=tokType===_parenR?null:parseExpression();expect(_parenR);node.body=parseStatement();labels.pop();return finishNode(node,"ForStatement")}function parseForIn(node,init){var type=tokType===_in?"ForInStatement":"ForOfStatement";next();node.left=init;node.right=parseExpression();expect(_parenR);node.body=parseStatement();labels.pop();return finishNode(node,type)}function parseVar(node,noIn,kind){node.declarations=[];node.kind=kind;for(;;){var decl=startNode();decl.id=options.ecmaVersion>=6?toAssignable(parseExprAtom()):parseIdent();checkLVal(decl.id,true);decl.init=eat(_eq)?parseExpression(true,noIn):kind===_const.keyword?unexpected():null;node.declarations.push(finishNode(decl,"VariableDeclarator"));if(!eat(_comma))break}return node}function parseExpression(noComma,noIn){var start=storeCurrentPos();var expr=parseMaybeAssign(noIn);if(!noComma&&tokType===_comma){var node=startNodeAt(start);node.expressions=[expr];while(eat(_comma))node.expressions.push(parseMaybeAssign(noIn));return finishNode(node,"SequenceExpression")}return expr}function parseMaybeAssign(noIn){var start=storeCurrentPos();var left=parseMaybeConditional(noIn);if(tokType.isAssign){var node=startNodeAt(start);node.operator=tokVal;node.left=tokType===_eq?toAssignable(left):left;checkLVal(left);next();node.right=parseMaybeAssign(noIn);return finishNode(node,"AssignmentExpression")}return left}function parseMaybeConditional(noIn){var start=storeCurrentPos();var expr=parseExprOps(noIn);if(eat(_question)){var node=startNodeAt(start);if(eat(_eq)){var left=node.left=toAssignable(expr);if(left.type!=="MemberExpression")raise(left.start,"You can only use member expressions in memoization assignment");node.right=parseMaybeAssign(noIn);node.operator="?=";return finishNode(node,"AssignmentExpression")}node.test=expr;node.consequent=parseExpression(true);expect(_colon);node.alternate=parseExpression(true,noIn);return finishNode(node,"ConditionalExpression")}return expr}function parseExprOps(noIn){var start=storeCurrentPos();return parseExprOp(parseMaybeUnary(),start,-1,noIn)}function parseExprOp(left,leftStart,minPrec,noIn){var prec=tokType.binop;if(prec!=null&&(!noIn||tokType!==_in)){if(prec>minPrec){var node=startNodeAt(leftStart);node.left=left;node.operator=tokVal;var op=tokType;next();var start=storeCurrentPos();node.right=parseExprOp(parseMaybeUnary(),start,prec,noIn);finishNode(node,op===_logicalOR||op===_logicalAND?"LogicalExpression":"BinaryExpression");return parseExprOp(node,leftStart,minPrec,noIn)}}return left}function parseMaybeUnary(){if(tokType.prefix){var node=startNode(),update=tokType.isUpdate,nodeType;if(tokType===_ellipsis){nodeType="SpreadElement"}else{nodeType=update?"UpdateExpression":"UnaryExpression";node.operator=tokVal;node.prefix=true}tokRegexpAllowed=true;next();node.argument=parseMaybeUnary();if(update)checkLVal(node.argument);else if(strict&&node.operator==="delete"&&node.argument.type==="Identifier")raise(node.start,"Deleting local variable in strict mode");return finishNode(node,nodeType)}var start=storeCurrentPos();var expr=parseExprSubscripts();while(tokType.postfix&&!canInsertSemicolon()){var node=startNodeAt(start);node.operator=tokVal;node.prefix=false;node.argument=expr;checkLVal(expr);next();expr=finishNode(node,"UpdateExpression")}return expr}function parseExprSubscripts(){var start=storeCurrentPos();return parseSubscripts(parseExprAtom(),start)}function parseSubscripts(base,start,noCalls){if(options.playground&&eat(_colon)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return parseSubscripts(finishNode(node,"BindMemberExpression"),start,noCalls)}else if(eat(_doubleColon)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);return parseSubscripts(finishNode(node,"VirtualPropertyExpression"),start,noCalls)}else if(eat(_dot)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);node.computed=false;return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(eat(_bracketL)){var node=startNodeAt(start);node.object=base;node.property=parseExpression();node.computed=true;expect(_bracketR);return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(!noCalls&&eat(_parenL)){var node=startNodeAt(start);node.callee=base;node.arguments=parseExprList(_parenR,false);return parseSubscripts(finishNode(node,"CallExpression"),start,noCalls)}else if(tokType===_bquote){var node=startNodeAt(start);node.tag=base;node.quasi=parseTemplate();return parseSubscripts(finishNode(node,"TaggedTemplateExpression"),start,noCalls)}return base}function parseExprAtom(){switch(tokType){case _this:var node=startNode();next();return finishNode(node,"ThisExpression");case _yield:if(inGenerator)return parseYield();case _await:if(inAsync)return parseAwait();case _name:var start=storeCurrentPos();var id=parseIdent(tokType!==_name);if(eat(_arrow)){return parseArrowExpression(startNodeAt(start),[id])}return id;case _regexp:var node=startNode();node.regex={pattern:tokVal.pattern,flags:tokVal.flags};node.value=tokVal.value;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _num:case _string:case _xjsText:var node=startNode();node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _null:case _true:case _false:var node=startNode();node.value=tokType.atomValue;node.raw=tokType.keyword;next();return finishNode(node,"Literal");case _parenL:var start=storeCurrentPos();var val,exprList;next();if(options.ecmaVersion>=7&&tokType===_for){val=parseComprehension(startNodeAt(start),true)}else{var oldParenL=++metParenL;if(tokType!==_parenR){val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}else{exprList=[]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){val=parseArrowExpression(startNodeAt(start),exprList)}else{if(!val)unexpected(lastStart);if(options.ecmaVersion>=6){for(var i=0;i<exprList.length;i++){if(exprList[i].type==="SpreadElement")unexpected()}}if(options.preserveParens){var par=startNodeAt(start);par.expression=val;val=finishNode(par,"ParenthesizedExpression")}}}return val;case _bracketL:var node=startNode();next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(node,false)}node.elements=parseExprList(_bracketR,true,true);return finishNode(node,"ArrayExpression");case _braceL:return parseObj();case _async:return parseAsync(startNode(),false);case _function:var node=startNode();next();return parseFunction(node,false,false);case _class:return parseClass(startNode(),false);case _new:return parseNew();case _bquote:return parseTemplate();case _lt:return parseXJSElement();default:unexpected()}}function parseNew(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL))node.arguments=parseExprList(_parenR,false);else node.arguments=empty;return finishNode(node,"NewExpression")}function parseTemplate(){var node=startNode();node.expressions=[];node.quasis=[];inTemplate=true;next();for(;;){var elem=startNode();elem.value={cooked:tokVal,raw:input.slice(tokStart,tokEnd)};elem.tail=false;next();node.quasis.push(finishNode(elem,"TemplateElement"));if(tokType===_bquote){elem.tail=true;break}inTemplate=false;expect(_dollarBraceL);node.expressions.push(parseExpression());inTemplate=true;tokPos=tokEnd;expect(_braceR)}inTemplate=false;next();return finishNode(node,"TemplateLiteral")}function parseObj(){var node=startNode(),first=true,propHash={};node.properties=[];var origInXJSChildExpression=inXJSChildExpression;inXJSChildExpression=false;next();while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var prop=startNode(),isGenerator,isAsync;if(options.ecmaVersion>=7){isAsync=eat(_async);if(isAsync&&tokType===_star)unexpected()}if(options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;isGenerator=eat(_star)}if(options.ecmaVersion>=7&&tokType===_ellipsis){if(isAsync||isGenerator)unexpected();prop=parseMaybeUnary();prop.type="SpreadProperty";node.properties.push(prop);continue}parsePropertyName(prop);if(eat(_colon)){prop.value=parseExpression(true);prop.kind="init"}else if(options.ecmaVersion>=6&&tokType===_parenL){prop.kind="init";prop.method=true;prop.value=parseMethod(isGenerator,isAsync)}else if(options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")){if(isGenerator||isAsync)unexpected();prop.kind=prop.key.name;parsePropertyName(prop);prop.value=parseMethod(false,false)}else if(options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){prop.kind="init";prop.value=prop.key;prop.shorthand=true}else unexpected();checkPropClash(prop,propHash);node.properties.push(finishNode(prop,"Property"))}inXJSChildExpression=origInXJSChildExpression;return finishNode(node,"ObjectExpression")}function parsePropertyName(prop){if(options.ecmaVersion>=6){if(eat(_bracketL)){prop.computed=true;prop.key=parseExpression();expect(_bracketR);return}else{prop.computed=false}}prop.key=tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function initFunction(node,isAsync){node.id=null;node.params=[];if(options.ecmaVersion>=6){node.defaults=[];node.rest=null;node.generator=false}if(options.ecmaVersion>=7){node.async=isAsync}}function parseFunction(node,isStatement,isAsync,allowExpressionBody){initFunction(node,isAsync);if(options.ecmaVersion>=6){if(isAsync&&tokType===_star)unexpected();node.generator=eat(_star)}if(isStatement||tokType===_name){node.id=parseIdent()}parseFunctionParams(node);parseFunctionBody(node,allowExpressionBody);return finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")}function parseMethod(isGenerator,isAsync){var node=startNode();initFunction(node,isAsync);parseFunctionParams(node);var allowExpressionBody;if(options.ecmaVersion>=6){node.generator=isGenerator;allowExpressionBody=true}else{allowExpressionBody=false}parseFunctionBody(node,allowExpressionBody);return finishNode(node,"FunctionExpression")}function parseArrowExpression(node,params,isAsync){initFunction(node,isAsync);var defaults=node.defaults,hasDefaults=false;for(var i=0,lastI=params.length-1;i<=lastI;i++){var param=params[i];if(param.type==="AssignmentExpression"&&param.operator==="="){hasDefaults=true;params[i]=param.left;defaults.push(param.right)}else{toAssignable(param,i===lastI,true);defaults.push(null);if(param.type==="SpreadElement"){params.length--;node.rest=param.argument;break}}}node.params=params;if(!hasDefaults)node.defaults=[];parseFunctionBody(node,true);return finishNode(node,"ArrowFunctionExpression")}function parseFunctionParams(node){var defaults=[],hasDefaults=false;expect(_parenL);for(;;){if(eat(_parenR)){break}else if(options.ecmaVersion>=6&&eat(_ellipsis)){node.rest=toAssignable(parseExprAtom(),false,true);checkSpreadAssign(node.rest);expect(_parenR);defaults.push(null);break}else{node.params.push(options.ecmaVersion>=6?toAssignable(parseExprAtom(),false,true):parseIdent());if(options.ecmaVersion>=6){if(eat(_eq)){hasDefaults=true;defaults.push(parseExpression(true))}else{defaults.push(null)}}if(!eat(_comma)){expect(_parenR);break}}}if(hasDefaults)node.defaults=defaults}function parseFunctionBody(node,allowExpression){var isExpression=allowExpression&&tokType!==_braceL;var oldInAsync=inAsync;inAsync=node.async;if(isExpression){node.body=parseExpression(true);node.expression=true}else{var oldInFunc=inFunction,oldInGen=inGenerator,oldLabels=labels;inFunction=true;inGenerator=node.generator;labels=[];node.body=parseBlock(true);node.expression=false;inFunction=oldInFunc;inGenerator=oldInGen;labels=oldLabels}inAsync=oldInAsync;if(strict||!isExpression&&node.body.body.length&&isUseStrict(node.body.body[0])){var nameHash={};if(node.id)checkFunctionParam(node.id,{});for(var i=0;i<node.params.length;i++)checkFunctionParam(node.params[i],nameHash);if(node.rest)checkFunctionParam(node.rest,nameHash)}}function parseClass(node,isStatement){next();node.id=tokType===_name?parseIdent():isStatement?unexpected():null;node.superClass=eat(_extends)?parseExpression():null;var classBody=startNode();classBody.body=[];expect(_braceL);while(!eat(_braceR)){var method=startNode();if(tokType===_name&&tokVal==="static"){next();method["static"]=true}else{method["static"]=false}var isAsync=false;if(options.ecmaVersion>=7){isAsync=eat(_async);if(isAsync&&tokType===_star)unexpected()}var isGenerator=eat(_star);parsePropertyName(method);if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&(method.key.name==="get"||method.key.name==="set")){if(isGenerator||isAsync)unexpected();method.kind=method.key.name;parsePropertyName(method)}else{method.kind=""}method.value=parseMethod(isGenerator,isAsync);classBody.body.push(finishNode(method,"MethodDefinition"));eat(_semi)}node.body=finishNode(classBody,"ClassBody");return finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}function parseExprList(close,allowTrailingComma,allowEmpty){var elts=[],first=true;while(!eat(close)){if(!first){expect(_comma);if(allowTrailingComma&&options.allowTrailingCommas&&eat(close))break}else first=false;if(allowEmpty&&tokType===_comma)elts.push(null);else elts.push(parseExpression(true))}return elts}function parseIdent(liberal){var node=startNode();if(liberal&&options.forbidReserved=="everywhere")liberal=false;if(tokType===_name){if(!liberal&&(options.forbidReserved&&(options.ecmaVersion===3?isReservedWord3:isReservedWord5)(tokVal)||strict&&isStrictReservedWord(tokVal))&&input.slice(tokStart,tokEnd).indexOf("\\")==-1)raise(tokStart,"The keyword '"+tokVal+"' is reserved");node.name=tokVal}else if(liberal&&tokType.keyword){node.name=tokType.keyword}else{unexpected()}tokRegexpAllowed=false;next();return finishNode(node,"Identifier")}function parseExport(node){next();if(tokType===_var||tokType===_const||tokType===_let||tokType===_function||tokType===_class||tokType===_async){node.declaration=parseStatement();node["default"]=false;node.specifiers=null;node.source=null}else if(eat(_default)){node.declaration=parseExpression(true);node["default"]=true;node.specifiers=null;node.source=null;semicolon()}else{var isBatch=tokType===_star;node.declaration=null;node["default"]=false;node.specifiers=parseExportSpecifiers();if(tokType===_name&&tokVal==="from"){next();node.source=tokType===_string?parseExprAtom():unexpected()}else{if(isBatch)unexpected();node.source=null}semicolon()}return finishNode(node,"ExportDeclaration")}function parseExportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();nodes.push(finishNode(node,"ExportBatchSpecifier"))}else{expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(tokType===_default);if(tokType===_name&&tokVal==="as"){next();node.name=parseIdent(true)}else{node.name=null}nodes.push(finishNode(node,"ExportSpecifier"))}}return nodes}function parseImport(node){next();if(tokType===_string){node.specifiers=[];node.source=parseExprAtom();node.kind=""}else{node.specifiers=parseImportSpecifiers();if(tokType!==_name||tokVal!=="from")unexpected();next();node.source=tokType===_string?parseExprAtom():unexpected();node.kind=node.specifiers[0]["default"]?"default":"named"}semicolon();return finishNode(node,"ImportDeclaration")}function parseImportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();if(tokType!==_name||tokVal!=="as")unexpected();next();node.name=parseIdent();checkLVal(node.name,true);nodes.push(finishNode(node,"ImportBatchSpecifier"));return nodes}if(tokType===_name){var node=startNode();node.id=parseIdent();checkLVal(node.id,true);node.name=null;node["default"]=true;nodes.push(finishNode(node,"ImportSpecifier"));if(!eat(_comma))return nodes}expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(true);if(tokType===_name&&tokVal==="as"){next();node.name=parseIdent()}else{node.name=null}checkLVal(node.name||node.id,true);node["default"]=false;nodes.push(finishNode(node,"ImportSpecifier"))}return nodes}function parseYield(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){node.delegate=false;node.argument=null}else{node.delegate=eat(_star);node.argument=parseExpression(true)}return finishNode(node,"YieldExpression")}function parseAwait(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){unexpected()}node.delegate=eat(_star);node.argument=parseExpression(true);return finishNode(node,"AwaitExpression")}function parseComprehension(node,isGenerator){node.blocks=[];while(tokType===_for){var block=startNode();next();expect(_parenL);block.left=toAssignable(parseExprAtom());checkLVal(block.left,true);if(tokType!==_name||tokVal!=="of")unexpected();next();block.of=true;block.right=parseExpression();expect(_parenR);node.blocks.push(finishNode(block,"ComprehensionBlock"))}node.filter=eat(_if)?parseParenExpression():null;node.body=parseExpression();expect(isGenerator?_parenR:_bracketR);node.generator=isGenerator;return finishNode(node,"ComprehensionExpression")}function getQualifiedXJSName(object){if(object.type==="XJSIdentifier"){return object.name}if(object.type==="XJSNamespacedName"){return object.namespace.name+":"+object.name.name}if(object.type==="XJSMemberExpression"){return getQualifiedXJSName(object.object)+"."+getQualifiedXJSName(object.property)}}function parseXJSIdentifier(){var node=startNode();if(tokType===_xjsName){node.name=tokVal}else if(tokType.keyword){node.name=tokType.keyword}else{unexpected()}tokRegexpAllowed=false;next();return finishNode(node,"XJSIdentifier")}function parseXJSNamespacedName(){var node=startNode();node.namespace=parseXJSIdentifier();expect(_colon);node.name=parseXJSIdentifier();return finishNode(node,"XJSNamespacedName")}function parseXJSMemberExpression(){var start=storeCurrentPos();var node=parseXJSIdentifier();while(eat(_dot)){var newNode=startNodeAt(start);newNode.object=node;newNode.property=parseXJSIdentifier();node=finishNode(newNode,"XJSMemberExpression")}return node}function parseXJSElementName(){switch(nextChar()){case":":return parseXJSNamespacedName();case".":return parseXJSMemberExpression();default:return parseXJSIdentifier()}}function parseXJSAttributeName(){if(nextChar()===":"){return parseXJSNamespacedName()}return parseXJSIdentifier()}function parseXJSAttributeValue(){switch(tokType){case _braceL:var node=parseXJSExpressionContainer();if(node.expression.type==="XJSEmptyExpression"){raise(node.start,"XJS attributes must only be assigned a non-empty "+"expression")}return node;case _lt:return parseXJSElement();case _xjsText:return parseExprAtom();default:raise(tokStart,"XJS value should be either an expression or a quoted XJS text")}}function parseXJSEmptyExpression(){if(tokType!==_braceR){unexpected()}var tmp;tmp=tokStart;tokStart=lastEnd;lastEnd=tmp;tmp=tokStartLoc;tokStartLoc=lastEndLoc;lastEndLoc=tmp;return finishNode(startNode(),"XJSEmptyExpression")}function parseXJSExpressionContainer(){var node=startNode();var origInXJSTag=inXJSTag,origInXJSChild=inXJSChild;inXJSTag=false;inXJSChild=false;inXJSChildExpression=origInXJSChild;next();node.expression=tokType===_braceR?parseXJSEmptyExpression():parseExpression();inXJSTag=origInXJSTag;inXJSChild=origInXJSChild;inXJSChildExpression=false;expect(_braceR);return finishNode(node,"XJSExpressionContainer")}function parseXJSAttribute(){if(tokType===_braceL){var tokStart1=tokStart,tokStartLoc1=tokStartLoc;var origInXJSTag=inXJSTag,origInXJSChildExpression=inXJSChildExpression;inXJSTag=inXJSChildExpression=false;next();if(tokType!==_ellipsis)unexpected();var node=parseMaybeUnary();inXJSChildExpression=origInXJSChildExpression;inXJSTag=origInXJSTag;expect(_braceR);node.type="XJSSpreadAttribute";node.start=tokStart1;node.end=lastEnd;if(options.locations){node.loc.start=tokStartLoc1;node.loc.end=lastEndLoc}if(options.ranges){node.range=[tokStart1,lastEnd]}return node}var node=startNode();node.name=parseXJSAttributeName();if(tokType===_eq){next();node.value=parseXJSAttributeValue()}else{node.value=null}return finishNode(node,"XJSAttribute")}function parseXJSChild(){switch(tokType){case _braceL:return parseXJSExpressionContainer();case _xjsText:return parseExprAtom();default:return parseXJSElement()}}function parseXJSOpeningElement(){var node=startNode(),attributes=node.attributes=[];var origInXJSChild=inXJSChild;var origInXJSTag=inXJSTag;inXJSChild=false;inXJSTag=true;next();node.name=parseXJSElementName();while(tokType!==_eof&&tokType!==_slash&&tokType!==_gt){attributes.push(parseXJSAttribute())}inXJSTag=false;if(node.selfClosing=!!eat(_slash)){inXJSTag=origInXJSTag;inXJSChild=origInXJSChild}else{inXJSChild=true}expect(_gt);return finishNode(node,"XJSOpeningElement")}function parseXJSClosingElement(){var node=startNode();var origInXJSChild=inXJSChild;var origInXJSTag=inXJSTag;inXJSChild=false;inXJSTag=true;tokRegexpAllowed=false;expect(_ltSlash);node.name=parseXJSElementName();skipSpace();inXJSChild=origInXJSChild;inXJSTag=origInXJSTag;tokRegexpAllowed=false;if(inXJSChild){tokPos=tokEnd}expect(_gt);return finishNode(node,"XJSClosingElement")}function parseXJSElement(){var node=startNode();var children=[];var origInXJSChild=inXJSChild;var openingElement=parseXJSOpeningElement();var closingElement=null;if(!openingElement.selfClosing){while(tokType!==_eof&&tokType!==_ltSlash){inXJSChild=true;children.push(parseXJSChild())}inXJSChild=origInXJSChild;closingElement=parseXJSClosingElement();if(getQualifiedXJSName(closingElement.name)!==getQualifiedXJSName(openingElement.name)){raise(closingElement.start,"Expected corresponding XJS closing tag for '"+getQualifiedXJSName(openingElement.name)+"'")}}if(!origInXJSChild&&tokType===_lt){raise(tokStart,"Adjacent XJS elements must be wrapped in an enclosing tag")}node.openingElement=openingElement;node.closingElement=closingElement;node.children=children;return finishNode(node,"XJSElement")}})},{}],2:[function(require,module,exports){(function(global){var transform=module.exports=require("./transformation/transform");transform.transform=transform;transform.run=function(code,opts){opts=opts||{};opts.sourceMap="inline";return new Function(transform(code,opts).code)()};transform.load=function(url,callback,opts,hold){opts=opts||{};opts.filename=opts.filename||url;var xhr=global.ActiveXObject?new global.ActiveXObject("Microsoft.XMLHTTP"):new global.XMLHttpRequest;xhr.open("GET",url,true);if("overrideMimeType"in xhr)xhr.overrideMimeType("text/plain");xhr.onreadystatechange=function(){if(xhr.readyState!==4)return;var status=xhr.status;if(status===0||status===200){var param=[xhr.responseText,opts];if(!hold)transform.run.apply(transform,param);if(callback)callback(param)}else{throw new Error("Could not load "+url)}};xhr.send(null)};var runScripts=function(){var scripts=[];var types=["text/ecmascript-6","text/6to5"];var index=0;var exec=function(){var param=scripts[index];if(param instanceof Array){transform.run.apply(transform,param);index++;exec()}};var run=function(script,i){var opts={};if(script.src){transform.load(script.src,function(param){scripts[i]=param;exec()},opts,true)}else{opts.filename="embedded"; scripts[i]=[script.innerHTML,opts]}};var _scripts=global.document.getElementsByTagName("script");for(var i in _scripts){var _script=_scripts[i];if(types.indexOf(_script.type)>=0)scripts.push(_script)}for(i in scripts){run(scripts[i],i)}exec()};if(global.addEventListener){global.addEventListener("DOMContentLoaded",runScripts,false)}else if(global.attachEvent){global.attachEvent("onload",runScripts)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transformation/transform":30}],3:[function(require,module,exports){module.exports=File;var SHEBANG_REGEX=/^\#\!.*/;var transform=require("./transformation/transform");var generate=require("./generation/generator");var Scope=require("./traverse/scope");var util=require("./util");var t=require("./types");var _=require("lodash");function File(opts){this.opts=File.normaliseOptions(opts);this.uids={};this.ast={}}File.declarations=["extends","class-props","apply-constructor","tagged-template-literal","interop-require","to-array","object-spread","has-own","slice"];File.normaliseOptions=function(opts){opts=_.cloneDeep(opts||{});_.defaults(opts,{experimental:false,playground:false,whitespace:true,blacklist:[],whitelist:[],sourceMap:false,comments:true,filename:"unknown",modules:"common",runtime:false,code:true});opts.filename=opts.filename.replace(/\\/g,"/");opts.blacklist=util.arrayify(opts.blacklist);opts.whitelist=util.arrayify(opts.whitelist);_.defaults(opts,{moduleRoot:opts.sourceRoot});_.defaults(opts,{sourceRoot:opts.moduleRoot});_.defaults(opts,{filenameRelative:opts.filename});_.defaults(opts,{sourceFileName:opts.filenameRelative,sourceMapName:opts.filenameRelative});if(opts.runtime===true){opts.runtime="to5Runtime"}if(opts.playground){opts.experimental=true}transform._ensureTransformerNames("blacklist",opts.blacklist);transform._ensureTransformerNames("whitelist",opts.whitelist);return opts};File.prototype.toArray=function(node){if(t.isArrayExpression(node)){return node}else if(t.isIdentifier(node)&&node.name==="arguments"){return t.callExpression(t.memberExpression(this.addDeclaration("slice"),t.identifier("call")),[node])}else{return t.callExpression(this.addDeclaration("to-array"),[node])}};File.prototype.getModuleFormatter=function(type){var ModuleFormatter=_.isFunction(type)?type:transform.moduleFormatters[type];if(!ModuleFormatter){var loc=util.resolve(type);if(loc)ModuleFormatter=require(loc)}if(!ModuleFormatter){throw new ReferenceError("unknown module formatter type "+type)}return new ModuleFormatter(this)};File.prototype.parseShebang=function(code){var shebangMatch=code.match(SHEBANG_REGEX);if(shebangMatch){this.shebang=shebangMatch[0];code=code.replace(SHEBANG_REGEX,"")}return code};File.prototype.addDeclaration=function(name){if(!_.contains(File.declarations,name)){throw new ReferenceError("unknown declaration "+name)}var program=this.ast.program;var declar=program._declarations&&program._declarations[name];if(declar)return declar.id;var ref;var runtimeNamespace=this.opts.runtime;if(runtimeNamespace){name=t.identifier(t.toIdentifier(name));return t.memberExpression(t.identifier(runtimeNamespace),name)}else{ref=util.template(name)}var uid=this.generateUidIdentifier(name);this.scope.push({key:name,id:uid,init:ref});return uid};File.prototype.errorWithNode=function(node,msg,Error){Error=Error||SyntaxError;var loc=node.loc.start;var err=new Error("Line "+loc.line+": "+msg);err.loc=loc;return err};File.prototype.parse=function(code){code=(code||"")+"";var self=this;this.code=code;code=this.parseShebang(code);return util.parse(this.opts,code,function(tree){self.transform(tree);return self.generate()})};File.prototype.transform=function(ast){this.ast=ast;this.scope=new Scope(ast.program);this.moduleFormatter=this.getModuleFormatter(this.opts.modules);var self=this;_.each(transform.transformers,function(transformer){transformer.transform(self)})};File.prototype.generate=function(){var opts=this.opts;var ast=this.ast;if(!opts.code){return{code:"",map:null,ast:ast}}var result=generate(ast,opts,this.code);if(this.shebang){result.code=this.shebang+"\n"+result.code}if(opts.sourceMap==="inline"){result.code+="\n"+util.sourceMapToComment(result.map)}result.ast=result;return result};File.prototype.generateUid=function(name,scope){name=t.toIdentifier(name);scope=scope||this.scope;var uid;do{uid=this._generateUid(name)}while(scope.has(uid));return uid};File.prototype.generateUidIdentifier=function(name,scope){return t.identifier(this.generateUid(name,scope))};File.prototype._generateUid=function(name){var uids=this.uids;var i=uids[name]||1;var id=name;if(i>1)id+=i;uids[name]=i+1;return"_"+id}},{"./generation/generator":5,"./transformation/transform":30,"./traverse/scope":73,"./types":76,"./util":78,lodash:109}],4:[function(require,module,exports){module.exports=Buffer;var util=require("../util");var _=require("lodash");function Buffer(position,format){this.position=position;this._indent=format.indent.base;this.format=format;this.buf=""}Buffer.prototype.get=function(){return util.trimRight(this.buf)};Buffer.prototype.getIndent=function(){if(this.format.compact){return""}else{return util.repeat(this._indent,this.format.indent.style)}};Buffer.prototype.indentSize=function(){return this.getIndent().length};Buffer.prototype.indent=function(){this._indent++};Buffer.prototype.dedent=function(){this._indent--};Buffer.prototype.semicolon=function(){if(this.format.semicolons)this.push(";")};Buffer.prototype.ensureSemicolon=function(){if(!this.isLast(";"))this.semicolon()};Buffer.prototype.rightBrace=function(){this.newline(true);this.push("}")};Buffer.prototype.keyword=function(name){this.push(name);this.push(" ")};Buffer.prototype.space=function(){if(this.buf&&!this.isLast([" ","\n"])){this.push(" ")}};Buffer.prototype.removeLast=function(cha){if(!this.isLast(cha))return;this.buf=this.buf.slice(0,-1);this.position.unshift(cha)};Buffer.prototype.newline=function(i,removeLast){if(!this.buf)return;if(this.format.compact)return;if(this.endsWith("{\n"))return;if(_.isBoolean(i)){removeLast=i;i=null}if(_.isNumber(i)){if(this.endsWith(util.repeat(i,"\n")))return;var self=this;_.times(i,function(){self.newline(null,removeLast)});return}if(removeLast&&this.isLast("\n"))this.removeLast("\n");this.removeLast(" ");this.buf=this.buf.replace(/\n +$/,"\n");this._push("\n")};Buffer.prototype.push=function(str,noIndent){if(this._indent&&!noIndent&&str!=="\n"){var indent=this.getIndent();str=str.replace(/\n/g,"\n"+indent);if(this.isLast("\n"))str=indent+str}this._push(str)};Buffer.prototype._push=function(str){this.position.push(str);this.buf+=str};Buffer.prototype.endsWith=function(str){return this.buf.slice(-str.length)===str};Buffer.prototype.isLast=function(cha,trimRight){var buf=this.buf;if(trimRight)buf=util.trimRight(buf);var chars=[].concat(cha);return _.contains(chars,_.last(buf))}},{"../util":78,lodash:109}],5:[function(require,module,exports){module.exports=function(ast,opts,code){var gen=new CodeGenerator(ast,opts,code);return gen.generate()};module.exports.CodeGenerator=CodeGenerator;var Whitespace=require("./whitespace");var SourceMap=require("./source-map");var Position=require("./position");var Buffer=require("./buffer");var util=require("../util");var n=require("./node");var t=require("../types");var _=require("lodash");function CodeGenerator(ast,opts,code){opts=opts||{};this.comments=ast.comments||[];this.tokens=ast.tokens||[];this.format=CodeGenerator.normaliseOptions(opts);this.ast=ast;this.whitespace=new Whitespace(this.tokens,this.comments);this.position=new Position;this.map=new SourceMap(this.position,opts,code);this.buffer=new Buffer(this.position,this.format)}_.each(Buffer.prototype,function(fn,key){CodeGenerator.prototype[key]=function(){return fn.apply(this.buffer,arguments)}});CodeGenerator.normaliseOptions=function(opts){return _.merge({parentheses:true,semicolons:true,comments:opts.comments==null||opts.comments,compact:false,indent:{adjustMultilineComment:true,style:" ",base:0}},opts.format||{})};CodeGenerator.generators={templateLiterals:require("./generators/template-literals"),comprehensions:require("./generators/comprehensions"),expressions:require("./generators/expressions"),statements:require("./generators/statements"),playground:require("./generators/playground"),classes:require("./generators/classes"),methods:require("./generators/methods"),modules:require("./generators/modules"),types:require("./generators/types"),base:require("./generators/base"),jsx:require("./generators/jsx")};_.each(CodeGenerator.generators,function(generator){_.extend(CodeGenerator.prototype,generator)});CodeGenerator.prototype.generate=function(){var ast=this.ast;this.print(ast);return{map:this.map.get(),code:this.buffer.get()}};CodeGenerator.prototype.buildPrint=function(parent){var self=this;var print=function(node,opts){return self.print(node,parent,opts)};print.sequence=function(nodes,opts){opts=opts||{};opts.statement=true;return self.printJoin(print,nodes,opts)};print.join=function(nodes,opts){return self.printJoin(print,nodes,opts)};print.block=function(node){return self.printBlock(print,node)};print.indentOnComments=function(node){return self.printAndIndentOnComments(print,node)};return print};CodeGenerator.prototype.print=function(node,parent,opts){if(!node)return"";var self=this;opts=opts||{};var newline=function(leading){if(!opts.statement&&!n.isUserWhitespacable(node,parent)){return}var lines=0;if(node.start!=null){if(leading){lines=self.whitespace.getNewlinesBefore(node)}else{lines=self.whitespace.getNewlinesAfter(node)}}else{if(!leading)lines++;var needs=n.needsWhitespaceAfter;if(leading)needs=n.needsWhitespaceBefore;lines+=needs(node,parent)}self.newline(lines)};if(this[node.type]){this.printLeadingComments(node,parent);newline(true);if(opts.before)opts.before();this.map.mark(node,"start");var needsParens=parent!==node._parent&&n.needsParens(node,parent);if(needsParens)this.push("(");this[node.type](node,this.buildPrint(node),parent);if(needsParens)this.push(")");this.map.mark(node,"end");if(opts.after)opts.after();newline(false);this.printTrailingComments(node,parent)}else{throw new ReferenceError("unknown node "+node.type+" "+JSON.stringify(node))}};CodeGenerator.prototype.printJoin=function(print,nodes,opts){if(!nodes||!nodes.length)return;opts=opts||{};var self=this;var len=nodes.length;if(opts.indent)self.indent();_.each(nodes,function(node,i){print(node,{statement:opts.statement,after:function(){if(opts.iterator){opts.iterator(node,i)}if(opts.separator&&i<len-1){self.push(opts.separator)}}})});if(opts.indent)self.dedent()};CodeGenerator.prototype.printAndIndentOnComments=function(print,node){var indent=!!node.leadingComments;if(indent)this.indent();print(node);if(indent)this.dedent()};CodeGenerator.prototype.printBlock=function(print,node){if(t.isEmptyStatement(node)){this.semicolon()}else{this.push(" ");print(node)}};CodeGenerator.prototype.generateComment=function(comment){var val=comment.value;if(comment.type==="Line"){val="//"+val}else{val="/*"+val+"*/"}return val};CodeGenerator.prototype.printTrailingComments=function(node,parent){this._printComments(this.getComments("trailingComments",node,parent))};CodeGenerator.prototype.printLeadingComments=function(node,parent){this._printComments(this.getComments("leadingComments",node,parent))};CodeGenerator.prototype.getComments=function(key,node,parent){if(t.isExpressionStatement(parent)){return[]}var comments=[];var nodes=[node];var self=this;if(t.isExpressionStatement(node)){nodes.push(node.argument)}_.each(nodes,function(node){comments=comments.concat(self._getComments(key,node))});return comments};CodeGenerator.prototype._getComments=function(key,node){return node&&node[key]||[]};CodeGenerator.prototype._printComments=function(comments){if(this.format.compact)return;if(!this.format.comments)return;if(!comments||!comments.length)return;var self=this;_.each(comments,function(comment){self.newline(self.whitespace.getNewlinesBefore(comment));var column=self.position.column;var val=self.generateComment(comment);if(column&&!self.isLast(["\n"," ","[","{"])){self._push(" ");column++}if(comment.type==="Block"&&self.format.indent.adjustMultilineComment){var offset=comment.loc.start.column;if(offset){var newlineRegex=new RegExp("\\n\\s{1,"+offset+"}","g");val=val.replace(newlineRegex,"\n")}var indent=Math.max(self.indentSize(),column);val=val.replace(/\n/g,"\n"+util.repeat(indent))}if(column===0){val=self.getIndent()+val}self._push(val);self.newline(self.whitespace.getNewlinesAfter(comment))})}},{"../types":76,"../util":78,"./buffer":4,"./generators/base":6,"./generators/classes":7,"./generators/comprehensions":8,"./generators/expressions":9,"./generators/jsx":10,"./generators/methods":11,"./generators/modules":12,"./generators/playground":13,"./generators/statements":14,"./generators/template-literals":15,"./generators/types":16,"./node":17,"./position":20,"./source-map":21,"./whitespace":22,lodash:109}],6:[function(require,module,exports){exports.File=function(node,print){print(node.program)};exports.Program=function(node,print){print.sequence(node.body)};exports.BlockStatement=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();print.sequence(node.body,{indent:true});this.removeLast("\n");this.rightBrace()}}},{}],7:[function(require,module,exports){exports.ClassExpression=exports.ClassDeclaration=function(node,print){this.push("class");if(node.id){this.space();print(node.id)}if(node.superClass){this.push(" extends ");print(node.superClass)}this.space();print(node.body)};exports.ClassBody=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();this.indent();print.sequence(node.body);this.dedent();this.rightBrace()}};exports.MethodDefinition=function(node,print){if(node.static){this.push("static ")}this._method(node,print)}},{}],8:[function(require,module,exports){exports.ComprehensionBlock=function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" of ");print(node.right);this.push(")")};exports.ComprehensionExpression=function(node,print){this.push(node.generator?"(":"[");print.join(node.blocks,{separator:" "});this.space();if(node.filter){this.keyword("if");this.push("(");print(node.filter);this.push(")");this.space()}print(node.body);this.push(node.generator?")":"]")}},{}],9:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.UnaryExpression=function(node,print){var hasSpace=/[a-z]$/.test(node.operator);var arg=node.argument;if(t.isUpdateExpression(arg)||t.isUnaryExpression(arg)){hasSpace=true}if(t.isUnaryExpression(arg)&&arg.operator==="!"){hasSpace=false}this.push(node.operator);if(hasSpace)this.space();print(node.argument)};exports.ParenthesizedExpression=function(node,print){this.push("(");print(node.expression);this.push(")")};exports.UpdateExpression=function(node,print){if(node.prefix){this.push(node.operator);print(node.argument)}else{print(node.argument);this.push(node.operator)}};exports.ConditionalExpression=function(node,print){print(node.test);this.push(" ? ");print(node.consequent);this.push(" : ");print(node.alternate)};exports.NewExpression=function(node,print){this.push("new ");print(node.callee);if(node.arguments.length||this.format.parentheses){this.push("(");print.join(node.arguments,{separator:", "});this.push(")")}};exports.SequenceExpression=function(node,print){print.join(node.expressions,{separator:", "})};exports.ThisExpression=function(){this.push("this")};exports.CallExpression=function(node,print){print(node.callee);this.push("(");print.join(node.arguments,{separator:", "});this.push(")")};var buildYieldAwait=function(keyword){return function(node,print){this.push(keyword);if(node.delegate)this.push("*");if(node.argument){this.space();print(node.argument)}}};exports.YieldExpression=buildYieldAwait("yield");exports.AwaitExpression=buildYieldAwait("await");exports.EmptyStatement=function(){this.semicolon()};exports.ExpressionStatement=function(node,print){print(node.expression);this.semicolon()};exports.BinaryExpression=exports.LogicalExpression=exports.AssignmentExpression=function(node,print){print(node.left);this.push(" "+node.operator+" ");print(node.right)};exports.MemberExpression=function(node,print){print(node.object);if(node.computed){this.push("[");print(node.property);this.push("]")}else{if(t.isLiteral(node.object)&&util.isInteger(node.object.value)){this.push(".")}this.push(".");print(node.property)}}},{"../../types":76,"../../util":78}],10:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.XJSAttribute=function(node,print){print(node.name);if(node.value){this.push("=");print(node.value)}};exports.XJSIdentifier=function(node){this.push(node.name)};exports.XJSNamespacedName=function(node,print){print(node.namespace);this.push(":");print(node.name)};exports.XJSMemberExpression=function(node,print){print(node.object);this.push(".");print(node.property)};exports.XJSSpreadAttribute=function(node,print){this.push("{...");print(node.argument);this.push("}")};exports.XJSExpressionContainer=function(node,print){this.push("{");print(node.expression);this.push("}")};exports.XJSElement=function(node,print){var self=this;var open=node.openingElement;print(open);if(open.selfClosing)return;this.indent();_.each(node.children,function(child){if(t.isLiteral(child)){self.push(child.value)}else{print(child)}});this.dedent();print(node.closingElement)};exports.XJSOpeningElement=function(node,print){this.push("<");print(node.name);if(node.attributes.length>0){this.space();print.join(node.attributes,{separator:" "})}this.push(node.selfClosing?" />":">")};exports.XJSClosingElement=function(node,print){this.push("</");print(node.name);this.push(">")};exports.XJSEmptyExpression=function(){}},{"../../types":76,lodash:109}],11:[function(require,module,exports){var t=require("../../types");exports._params=function(node,print){var self=this;this.push("(");print.join(node.params,{separator:", ",iterator:function(param,i){var def=node.defaults&&node.defaults[i];if(def){self.push(" = ");print(def)}}});if(node.rest){if(node.params.length){this.push(", ")}this.push("...");print(node.rest)}this.push(")")};exports._method=function(node,print){var value=node.value;var kind=node.kind;var key=node.key;if(!kind||kind==="init"){if(value.generator){this.push("*")}}else{this.push(kind+" ")}if(value.async)this.push("async ");if(node.computed){this.push("[");print(key);this.push("]")}else{print(key)}this._params(value,print);this.space();print(value.body)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,print){if(node.async)this.push("async ");this.push("function");if(node.generator)this.push("*");this.space();if(node.id)print(node.id);this._params(node,print);this.space();print(node.body)};exports.ArrowFunctionExpression=function(node,print){if(node.async)this.push("async ");if(node.params.length===1&&!node.defaults.length&&!node.rest&&t.isIdentifier(node.params[0])){print(node.params[0])}else{this._params(node,print)}this.push(" => ");print(node.body)}},{"../../types":76}],12:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.ImportSpecifier=exports.ExportSpecifier=function(node,print){print(node.id);if(node.name){this.push(" as ");print(node.name)}};exports.ExportBatchSpecifier=function(){this.push("*")};exports.ExportDeclaration=function(node,print){this.push("export ");var specifiers=node.specifiers;if(node.default){this.push("default ")}if(node.declaration){print(node.declaration);if(t.isStatement(node.declaration))return}else{if(specifiers.length===1&&t.isExportBatchSpecifier(specifiers[0])){print(specifiers[0])}else{this.push("{");if(specifiers.length){this.space();print.join(specifiers,{separator:", "});this.space()}this.push("}")}if(node.source){this.push(" from ");print(node.source)}}this.ensureSemicolon()};exports.ImportDeclaration=function(node,print){var self=this;this.push("import ");var specfiers=node.specifiers;if(specfiers&&specfiers.length){var foundImportSpecifier=false;_.each(node.specifiers,function(spec,i){if(+i>0){self.push(", ")}if(!spec.default&&spec.type!=="ImportBatchSpecifier"&&!foundImportSpecifier){foundImportSpecifier=true;self.push("{ ")}print(spec)});if(foundImportSpecifier){this.push(" }")}this.push(" from ")}print(node.source);this.semicolon()};exports.ImportBatchSpecifier=function(node,print){this.push("* as ");print(node.name)}},{"../../types":76,lodash:109}],13:[function(require,module,exports){var _=require("lodash");_.each(["BindMemberExpression"],function(type){exports[type]=function(){throw new ReferenceError("Trying to render non-standard playground node "+JSON.stringify(type))}})},{lodash:109}],14:[function(require,module,exports){var t=require("../../types");exports.WithStatement=function(node,print){this.keyword("with");this.push("(");print(node.object);this.push(")");print.block(node.body)};exports.IfStatement=function(node,print){this.keyword("if");this.push("(");print(node.test);this.push(") ");print.indentOnComments(node.consequent);if(node.alternate){if(this.isLast("}"))this.space();this.keyword("else");print.indentOnComments(node.alternate)}};exports.ForStatement=function(node,print){this.keyword("for");this.push("(");print(node.init);this.push(";");if(node.test){this.space();print(node.test)}this.push(";");if(node.update){this.space();print(node.update)}this.push(")");print.block(node.body)};exports.WhileStatement=function(node,print){this.keyword("while");this.push("(");print(node.test);this.push(")");print.block(node.body)};var buildForXStatement=function(op){return function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" "+op+" ");print(node.right);this.push(")");print.block(node.body)}};exports.ForInStatement=buildForXStatement("in");exports.ForOfStatement=buildForXStatement("of");exports.DoWhileStatement=function(node,print){this.keyword("do");print(node.body);this.space();this.keyword("while");this.push("(");print(node.test);this.push(");")};var buildLabelStatement=function(prefix,key){return function(node,print){this.push(prefix);var label=node[key||"label"];if(label){this.space();print(label)}this.semicolon()}};exports.ContinueStatement=buildLabelStatement("continue");exports.ReturnStatement=buildLabelStatement("return","argument");exports.BreakStatement=buildLabelStatement("break");exports.LabeledStatement=function(node,print){print(node.label);this.push(": ");print(node.body)};exports.TryStatement=function(node,print){this.keyword("try");print(node.block);this.space();print(node.handler);if(node.finalizer){this.space();this.push("finally ");print(node.finalizer)}};exports.CatchClause=function(node,print){this.keyword("catch");this.push("(");print(node.param);this.push(") ");print(node.body)};exports.ThrowStatement=function(node,print){this.push("throw ");print(node.argument);this.semicolon()};exports.SwitchStatement=function(node,print){this.keyword("switch");this.push("(");print(node.discriminant);this.push(") {");print.sequence(node.cases,{indent:true});this.push("}")};exports.SwitchCase=function(node,print){if(node.test){this.push("case ");print(node.test);this.push(":")}else{this.push("default:")}this.space();print.sequence(node.consequent,{indent:true})};exports.DebuggerStatement=function(){this.push("debugger;")};exports.VariableDeclaration=function(node,print,parent){this.push(node.kind+" ");print.join(node.declarations,{separator:", "});if(!t.isFor(parent)){this.semicolon()}};exports.VariableDeclarator=function(node,print){if(node.init){print(node.id);this.push(" = ");print(node.init)}else{print(node.id)}}},{"../../types":76}],15:[function(require,module,exports){var _=require("lodash");exports.TaggedTemplateExpression=function(node,print){print(node.tag);print(node.quasi)};exports.TemplateElement=function(node){this._push(node.value.raw)};exports.TemplateLiteral=function(node,print){this.push("`");var quasis=node.quasis;var self=this;var len=quasis.length;_.each(quasis,function(quasi,i){print(quasi);if(i+1<len){self.push("${ ");print(node.expressions[i]);self.push(" }")}});this._push("`")}},{lodash:109}],16:[function(require,module,exports){var _=require("lodash");exports.Identifier=function(node){this.push(node.name)};exports.SpreadElement=exports.SpreadProperty=function(node,print){this.push("...");print(node.argument)};exports.VirtualPropertyExpression=function(node,print){print(node.object);this.push("::");print(node.property)};exports.ObjectExpression=exports.ObjectPattern=function(node,print){var props=node.properties;if(props.length){this.push("{");this.space();print.join(props,{separator:", ",indent:true});this.space();this.push("}")}else{this.push("{}")}};exports.Property=function(node,print){if(node.method||node.kind==="get"||node.kind==="set"){this._method(node,print)}else{if(node.computed){this.push("[");print(node.key);this.push("]")}else{print(node.key);if(node.shorthand)return}this.push(": ");print(node.value)}};exports.ArrayExpression=exports.ArrayPattern=function(node,print){var elems=node.elements;var self=this;var len=elems.length;this.push("[");_.each(elems,function(elem,i){if(!elem){self.push(",")}else{if(i>0)self.push(" ");print(elem);if(i<len-1)self.push(",")}});this.push("]")};exports.Literal=function(node){var val=node.value;var type=typeof val;if(type==="string"){val=JSON.stringify(val);val=val.replace(/[\u007f-\uffff]/g,function(c){return"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)});this.push(val)}else if(type==="boolean"||type==="number"){this.push(JSON.stringify(val))}else if(node.regex){this.push("/"+node.regex.pattern+"/"+node.regex.flags)}else if(val===null){this.push("null")}}},{lodash:109}],17:[function(require,module,exports){module.exports=Node;var whitespace=require("./whitespace");var parens=require("./parentheses");var t=require("../../types");var _=require("lodash");var find=function(obj,node,parent){var result;_.each(obj,function(fn,type){if(t["is"+type](node)){result=fn(node,parent);if(result!=null)return false}});return result};function Node(node,parent){this.parent=parent;this.node=node}Node.prototype.isUserWhitespacable=function(){return t.isUserWhitespacable(this.node)};Node.prototype.needsWhitespace=function(type){var parent=this.parent;var node=this.node;if(!node)return 0;if(t.isExpressionStatement(node)){node=node.expression}var lines=find(whitespace[type].nodes,node,parent);if(lines)return lines;_.each(find(whitespace[type].list,node,parent),function(expr){lines=Node.needsWhitespace(expr,node,type);if(lines)return false});return lines||0};Node.prototype.needsWhitespaceBefore=function(){return this.needsWhitespace("before")};Node.prototype.needsWhitespaceAfter=function(){return this.needsWhitespace("after")};Node.prototype.needsParens=function(){var parent=this.parent;var node=this.node;if(!parent)return false;if(t.isNewExpression(parent)&&parent.callee===node){return t.isCallExpression(node)||_.some(node,function(val){return t.isCallExpression(val)})}return find(parens,node,parent)};_.each(Node.prototype,function(fn,key){Node[key]=function(node,parent){var n=new Node(node,parent);var args=_.toArray(arguments).slice(2);return n[key].apply(n,args)}})},{"../../types":76,"./parentheses":18,"./whitespace":19,lodash:109}],18:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var PRECEDENCE={};_.each([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]],function(tier,i){_.each(tier,function(op){PRECEDENCE[op]=i})});exports.Binary=function(node,parent){if(t.isCallExpression(parent)&&parent.callee===node){return true}if(t.isUnaryLike(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isBinary(parent)){var parentOp=parent.operator;var parentPos=PRECEDENCE[parentOp];var nodeOp=node.operator;var nodePos=PRECEDENCE[nodeOp];if(parentPos>nodePos){return true}if(parentPos===nodePos&&parent.right===node){return true}}};exports.BinaryExpression=function(node,parent){if(node.operator==="in"){if(t.isVariableDeclarator(parent)){return true}if(t.isFor(parent)){return true}}};exports.SequenceExpression=function(node,parent){if(t.isForStatement(parent)){return false}if(t.isExpressionStatement(parent)&&parent.expression===node){return false}return true};exports.YieldExpression=function(node,parent){return t.isBinary(parent)||t.isUnaryLike(parent)||t.isCallExpression(parent)||t.isMemberExpression(parent)||t.isNewExpression(parent)||t.isConditionalExpression(parent)||t.isYieldExpression(parent)};exports.Literal=function(node,parent){if(_.isNumber(node.value)&&t.isMemberExpression(parent)&&parent.object===node){return true}};exports.ClassExpression=function(node,parent){return t.isExpressionStatement(parent)};exports.UnaryLike=function(node,parent){return t.isMemberExpression(parent)&&parent.object===node};exports.FunctionExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}};exports.AssignmentExpression=exports.ConditionalExpression=function(node,parent){if(t.isUnaryLike(parent)){return true}if(t.isBinary(parent)){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}if(t.isConditionalExpression(parent)&&parent.test===node){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false}},{"../../types":76,lodash:109}],19:[function(require,module,exports){var _=require("lodash");var t=require("../../types");exports.before={nodes:{Property:function(node,parent){if(parent.properties[0]===node){return 1}},SpreadProperty:function(node,parent){return exports.before.nodes.Property(node,parent)},SwitchCase:function(node,parent){if(parent.cases[0]===node){return 1}},CallExpression:function(node){if(t.isFunction(node.callee)){return 1}}}};exports.after={nodes:{},list:{VariableDeclaration:function(node){return _.map(node.declarations,"init")},ArrayExpression:function(node){return node.elements},ObjectExpression:function(node){return node.properties}}};_.each({Function:1,Class:1,For:1,SwitchStatement:1,IfStatement:{before:1},CallExpression:{after:1},Literal:{after:1}},function(amounts,type){if(_.isNumber(amounts))amounts={after:amounts,before:amounts};_.each(amounts,function(amount,key){exports[key].nodes[type]=function(){return amount}})})},{"../../types":76,lodash:109}],20:[function(require,module,exports){module.exports=Position;var _=require("lodash");function Position(){this.line=1;this.column=0}Position.prototype.push=function(str){var self=this;_.each(str,function(cha){if(cha==="\n"){self.line++;self.column=0}else{self.column++}})};Position.prototype.unshift=function(str){var self=this;_.each(str,function(cha){if(cha==="\n"){self.line--}else{self.column--}})}},{lodash:109}],21:[function(require,module,exports){module.exports=SourceMap;var sourceMap=require("source-map");var t=require("../types");function SourceMap(position,opts,code){this.position=position;this.opts=opts;if(opts.sourceMap){this.map=new sourceMap.SourceMapGenerator({file:opts.sourceMapName,sourceRoot:opts.sourceRoot});this.map.setSourceContent(opts.sourceFileName,code)}else{this.map=null}}SourceMap.prototype.get=function(){var map=this.map;if(map){return map.toJSON()}else{return map}};SourceMap.prototype.mark=function(node,type){var loc=node.loc;if(!loc)return;var map=this.map;if(!map)return;if(t.isProgram(node)||t.isFile(node))return;var position=this.position;var generated={line:position.line,column:position.column};var original=loc[type];if(generated.line===original.line&&generated.column===original.column)return;map.addMapping({source:this.opts.sourceFileName,generated:generated,original:original}) }},{"../types":76,"source-map":117}],22:[function(require,module,exports){module.exports=Whitespace;var _=require("lodash");function Whitespace(tokens,comments){this.tokens=_.sortBy(tokens.concat(comments),"start");this.used=[]}Whitespace.prototype.getNewlinesBefore=function(node){var startToken;var endToken;var tokens=this.tokens;_.each(tokens,function(token,i){if(node.start===token.start){startToken=tokens[i-1];endToken=token;return false}});return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesAfter=function(node){var startToken;var endToken;var tokens=this.tokens;_.each(tokens,function(token,i){if(node.end===token.end){startToken=token;endToken=tokens[i+1];return false}});return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesBetween=function(startToken,endToken){var start=startToken?startToken.loc.end.line:1;var end=endToken.loc.start.line;var lines=0;for(var line=start;line<end;line++){if(!_.contains(this.used,line)){this.used.push(line);lines++}}return lines}},{lodash:109}],23:[function(require,module,exports){var t=require("./types");var _=require("lodash");var types=require("ast-types");var def=types.Type.def;var or=types.Type.or;def("File").bases("Node").build("program").field("program",def("Program"));def("ParenthesizedExpression").bases("Expression").build("expression").field("expression",def("Expression"));def("ImportBatchSpecifier").bases("Specifier").build("name").field("name",def("Identifier"));def("VirtualPropertyExpression").bases("Expression").build("object","property").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression")));def("BindMemberExpression").bases("Expression").build("object","property","arguments").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("arguments",[def("Expression")]);types.finalize();var estraverse=require("estraverse");_.extend(estraverse.VisitorKeys,t.VISITOR_KEYS)},{"./types":76,"ast-types":92,estraverse:104,lodash:109}],24:[function(require,module,exports){module.exports=AMDFormatter;var CommonJSFormatter=require("./common");var util=require("../../util");var t=require("../../types");var _=require("lodash");function AMDFormatter(file){this.file=file;this.ids={}}util.inherits(AMDFormatter,CommonJSFormatter);AMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[t.literal("exports")];_.each(this.ids,function(id,name){names.push(t.literal(name))});names=t.arrayExpression(names);var params=_.values(this.ids);params.unshift(t.identifier("exports"));var container=t.functionExpression(null,params,t.blockStatement(body));var defineArgs=[names,container];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var call=t.callExpression(t.identifier("define"),defineArgs);program.body=[t.expressionStatement(call)]};AMDFormatter.prototype.getModuleName=function(){if(this.file.opts.amdModuleIds){return CommonJSFormatter.prototype.getModuleName.apply(this,arguments)}else{return null}};AMDFormatter.prototype._push=function(node){var id=node.source.value;var ids=this.ids;if(ids[id]){return ids[id]}else{return this.ids[id]=this.file.generateUidIdentifier(id)}};AMDFormatter.prototype.import=function(node){this._push(node)};AMDFormatter.prototype.importSpecifier=function(specifier,node,nodes){var key=t.getSpecifierName(specifier);var id=specifier.id;if(specifier.default){id=t.identifier("default")}var ref;if(t.isImportBatchSpecifier(specifier)){ref=this._push(node)}else{ref=t.memberExpression(this._push(node),id,false)}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,ref)]))};AMDFormatter.prototype.exportSpecifier=function(specifier,node,nodes){var self=this;return this._exportSpecifier(function(){return self._push(node)},specifier,node,nodes)}},{"../../types":76,"../../util":78,"./common":26,lodash:109}],25:[function(require,module,exports){module.exports=CommonJSInteropFormatter;var CommonJSFormatter=require("./common");var util=require("../../util");var t=require("../../types");function CommonJSInteropFormatter(){this.has=false;CommonJSFormatter.apply(this,arguments)}util.inherits(CommonJSInteropFormatter,CommonJSFormatter);CommonJSInteropFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);if(specifier.default){nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.callExpression(this.file.addDeclaration("interop-require"),[util.template("require",{MODULE_NAME:node.source.raw})]))]))}else{CommonJSFormatter.prototype.importSpecifier.apply(this,arguments)}};CommonJSInteropFormatter.prototype.export=function(node,nodes){if(node.default&&!this.has){var declar=node.declaration;var assign=util.template("exports-default-module",{VALUE:this._pushStatement(declar,nodes)},true);nodes.push(this._hoistExport(declar,assign));return}else{this.has=true}CommonJSFormatter.prototype.export.apply(this,arguments)};CommonJSInteropFormatter.prototype.exportSpecifier=function(){this.has=true;CommonJSFormatter.prototype.exportSpecifier.apply(this,arguments)}},{"../../types":76,"../../util":78,"./common":26}],26:[function(require,module,exports){module.exports=CommonJSFormatter;var util=require("../../util");var t=require("../../types");function CommonJSFormatter(file){this.file=file}CommonJSFormatter.prototype.getModuleName=function(){var opts=this.file.opts;var filenameRelative=opts.filenameRelative;var moduleName="";if(opts.moduleRoot){moduleName=opts.moduleRoot+"/"}if(!opts.filenameRelative){return moduleName+opts.filename.replace(/^\//,"")}if(opts.sourceRoot){var sourceRootRegEx=new RegExp("^"+opts.sourceRoot+"/?");filenameRelative=filenameRelative.replace(sourceRootRegEx,"")}filenameRelative=filenameRelative.replace(/\.(.*?)$/,"");moduleName+=filenameRelative;return moduleName};CommonJSFormatter.prototype.import=function(node,nodes){nodes.push(util.template("require",{MODULE_NAME:node.source.raw},true))};CommonJSFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);if(specifier.default){specifier.id=t.identifier("default")}var templateName="require-assign";if(specifier.type!=="ImportBatchSpecifier")templateName+="-key";nodes.push(util.template(templateName,{VARIABLE_NAME:variableName,MODULE_NAME:node.source.raw,KEY:specifier.id}))};CommonJSFormatter.prototype._hoistExport=function(declar,assign){if(t.isFunctionDeclaration(declar)){assign._blockHoist=true}return assign};CommonJSFormatter.prototype._pushStatement=function(ref,nodes){if(t.isClass(ref)||t.isFunction(ref)){if(ref.id){nodes.push(t.toStatement(ref));ref=ref.id}}return ref};CommonJSFormatter.prototype.export=function(node,nodes){var declar=node.declaration;if(node.default){nodes.push(util.template("exports-default",{VALUE:this._pushStatement(declar,nodes)},true))}else{var assign;if(t.isVariableDeclaration(declar)){var decl=declar.declarations[0];if(decl.init){decl.init=util.template("exports-assign",{VALUE:decl.init,KEY:decl.id})}nodes.push(declar)}else{assign=util.template("exports-assign",{VALUE:declar.id,KEY:declar.id},true);nodes.push(t.toStatement(declar));nodes.push(assign);this._hoistExport(declar,assign)}}};CommonJSFormatter.prototype._exportSpecifier=function(getRef,specifier,node,nodes){var variableName=t.getSpecifierName(specifier);var inherits=false;if(node.specifiers.length===1)inherits=node;if(node.source){if(t.isExportBatchSpecifier(specifier)){nodes.push(util.template("exports-wildcard",{OBJECT:getRef()},true))}else{nodes.push(util.template("exports-assign-key",{VARIABLE_NAME:variableName.name,OBJECT:getRef(),KEY:specifier.id},true))}}else{nodes.push(util.template("exports-assign",{VALUE:specifier.id,KEY:variableName},true))}};CommonJSFormatter.prototype.exportSpecifier=function(specifier,node,nodes){this._exportSpecifier(function(){return t.callExpression(t.identifier("require"),[node.source])},specifier,node,nodes)}},{"../../types":76,"../../util":78}],27:[function(require,module,exports){module.exports=IgnoreFormatter;var t=require("../../types");function IgnoreFormatter(){}IgnoreFormatter.prototype.import=function(){};IgnoreFormatter.prototype.importSpecifier=function(){};IgnoreFormatter.prototype.export=function(node,nodes){var declar=t.toStatement(node.declaration,true);if(declar)nodes.push(t.inherits(declar,node))};IgnoreFormatter.prototype.exportSpecifier=function(){}},{"../../types":76}],28:[function(require,module,exports){module.exports=SystemFormatter;var util=require("../../util");var t=require("../../types");var _=require("lodash");var SETTER_MODULE_NAMESPACE=t.identifier("m");var DEFAULT_IDENTIFIER=t.identifier("default");var NULL_SETTER=t.literal(null);function SystemFormatter(file){this.exportedStatements=[];this.importedModule={};this.exportIdentifier=file.generateUidIdentifier("export");this.file=file}SystemFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var moduleName=this.file.opts.filename.replace(/^.*\//,"").replace(/\..*$/,"");var dependencies=Object.keys(this.importedModule).map(t.literal);var moduleNameVariableNode=t.variableDeclaration("var",[t.variableDeclarator(t.identifier("__moduleName"),t.literal(moduleName))]);body.splice(1,0,moduleNameVariableNode);var declaredSetters=_(this.importedModule).map().flatten().pluck("variableName").pluck("name").uniq().map(t.identifier).map(function(name){return t.variableDeclarator(name)}).value();if(declaredSetters.length){body.splice(2,0,t.variableDeclaration("var",declaredSetters))}var executeFunctionExpression=t.functionExpression(null,[],t.blockStatement(this.exportedStatements));var settersArrayExpression=t.arrayExpression(this._buildSetters());var moduleReturnStatement=t.returnStatement(t.objectExpression([t.property("init",t.identifier("setters"),settersArrayExpression),t.property("init",t.identifier("execute"),executeFunctionExpression)]));body.push(moduleReturnStatement);var runner=util.template("register",{MODULE_NAME:t.literal(moduleName),MODULE_DEPENDENCIES:t.arrayExpression(dependencies),MODULE_BODY:t.functionExpression(null,[this.exportIdentifier],t.blockStatement(body))});program.body=[t.expressionStatement(runner)]};SystemFormatter.prototype._buildSetters=function(){return _.map(this.importedModule,function(specs){if(!specs.length){return NULL_SETTER}var expressionStatements=_.map(specs,function(spec){var right=SETTER_MODULE_NAMESPACE;if(!spec.isBatch){right=t.memberExpression(right,spec.key)}return t.expressionStatement(t.assignmentExpression("=",spec.variableName,right))});return t.functionExpression(null,[SETTER_MODULE_NAMESPACE],t.blockStatement(expressionStatements))})};SystemFormatter.prototype.import=function(node){var MODULE_NAME=node.source.value;this.importedModule[MODULE_NAME]=this.importedModule[MODULE_NAME]||[]};SystemFormatter.prototype.importSpecifier=function(specifier,node){var variableName=t.getSpecifierName(specifier);if(specifier.default){specifier.id=DEFAULT_IDENTIFIER}var MODULE_NAME=node.source.value;this.importedModule[MODULE_NAME]=this.importedModule[MODULE_NAME]||[];this.importedModule[MODULE_NAME].push({variableName:variableName,isBatch:specifier.type==="ImportBatchSpecifier",key:specifier.id})};SystemFormatter.prototype._export=function(name,identifier){this.exportedStatements.push(t.expressionStatement(t.callExpression(this.exportIdentifier,[t.literal(name),identifier])))};SystemFormatter.prototype.export=function(node,nodes){var declar=node.declaration;var variableName,identifier;if(node.default){variableName=DEFAULT_IDENTIFIER.name;if(t.isClass(declar)||t.isFunction(declar)){if(!declar.id){declar.id=this.file.generateUidIdentifier("anonymous")}nodes.push(t.toStatement(declar));declar=declar.id}identifier=declar}else if(t.isVariableDeclaration(declar)){variableName=declar.declarations[0].id.name;identifier=declar.declarations[0].id;nodes.push(declar)}else{variableName=declar.id.name;identifier=declar.id;nodes.push(declar)}this._export(variableName,identifier)};SystemFormatter.prototype.exportSpecifier=function(specifier,node){var variableName=t.getSpecifierName(specifier);if(node.source){if(t.isExportBatchSpecifier(specifier)){var exportIdentifier=t.identifier("exports");this.exportedStatements.push(t.variableDeclaration("var",[t.variableDeclarator(exportIdentifier,this.exportIdentifier)]));this.exportedStatements.push(util.template("exports-wildcard",{OBJECT:t.identifier(node.source.value)},true))}else{this._export(variableName.name,t.memberExpression(t.identifier(node.source.value),specifier.id))}}else{this._export(variableName.name,specifier.id)}}},{"../../types":76,"../../util":78,lodash:109}],29:[function(require,module,exports){module.exports=UMDFormatter;var AMDFormatter=require("./amd");var util=require("../../util");var t=require("../../types");var _=require("lodash");function UMDFormatter(){AMDFormatter.apply(this,arguments)}util.inherits(UMDFormatter,AMDFormatter);UMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[];_.each(this.ids,function(id,name){names.push(t.literal(name))});var ids=_.values(this.ids);var args=[t.identifier("exports")].concat(ids);var factory=t.functionExpression(null,args,t.blockStatement(body));var defineArgs=[t.arrayExpression([t.literal("exports")].concat(names))];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var runner=util.template("umd-runner-body",{AMD_ARGUMENTS:defineArgs,COMMON_ARGUMENTS:names.map(function(name){return t.callExpression(t.identifier("require"),[name])})});var call=t.callExpression(runner,[factory]);program.body=[t.expressionStatement(call)]}},{"../../types":76,"../../util":78,"./amd":24,lodash:109}],30:[function(require,module,exports){module.exports=transform;var Transformer=require("./transformer");var File=require("../file");var _=require("lodash");function transform(code,opts){var file=new File(opts);return file.parse(code)}transform._ensureTransformerNames=function(type,keys){_.each(keys,function(key){if(!_.has(transform.transformers,key)){throw new ReferenceError("unknown transformer "+key+" specified in "+type)}})};transform.transformers={};transform.moduleFormatters={common:require("./modules/common"),commonInterop:require("./modules/common-interop"),system:require("./modules/system"),ignore:require("./modules/ignore"),amd:require("./modules/amd"),umd:require("./modules/umd")};_.each({modules:require("./transformers/es6-modules"),propertyNameShorthand:require("./transformers/es6-property-name-shorthand"),arrayComprehension:require("./transformers/es7-array-comprehension"),generatorComprehension:require("./transformers/es7-generator-comprehension"),arrowFunctions:require("./transformers/es6-arrow-functions"),classes:require("./transformers/es6-classes"),computedPropertyNames:require("./transformers/es6-computed-property-names"),objectSpread:require("./transformers/es7-object-spread"),exponentiationOperator:require("./transformers/es7-exponentiation-operator"),spread:require("./transformers/es6-spread"),templateLiterals:require("./transformers/es6-template-literals"),propertyMethodAssignment:require("./transformers/es5-property-method-assignment"),defaultParameters:require("./transformers/es6-default-parameters"),restParameters:require("./transformers/es6-rest-parameters"),destructuring:require("./transformers/es6-destructuring"),forOf:require("./transformers/es6-for-of"),unicodeRegex:require("./transformers/es6-unicode-regex"),abstractReferences:require("./transformers/es7-abstract-references"),react:require("./transformers/react"),constants:require("./transformers/es6-constants"),letScoping:require("./transformers/es6-let-scoping"),generators:require("./transformers/es6-generators"),methodBinding:require("./transformers/playground-method-binding"),memoizationOperator:require("./transformers/playground-memoization-operator"),_blockHoist:require("./transformers/_block-hoist"),_declarations:require("./transformers/_declarations"),_aliasFunctions:require("./transformers/_alias-functions"),useStrict:require("./transformers/use-strict"),_propertyLiterals:require("./transformers/_property-literals"),_memberExpressioLiterals:require("./transformers/_member-expression-literals"),_memberExpressionKeywords:require("./transformers/_member-expression-keywords"),_moduleFormatter:require("./transformers/_module-formatter")},function(transformer,key){transform.transformers[key]=new Transformer(key,transformer)})},{"../file":3,"./modules/amd":24,"./modules/common":26,"./modules/common-interop":25,"./modules/ignore":27,"./modules/system":28,"./modules/umd":29,"./transformer":31,"./transformers/_alias-functions":32,"./transformers/_block-hoist":33,"./transformers/_declarations":34,"./transformers/_member-expression-keywords":35,"./transformers/_member-expression-literals":36,"./transformers/_module-formatter":37,"./transformers/_property-literals":38,"./transformers/es5-property-method-assignment":39,"./transformers/es6-arrow-functions":40,"./transformers/es6-classes":41,"./transformers/es6-computed-property-names":42,"./transformers/es6-constants":43,"./transformers/es6-default-parameters":44,"./transformers/es6-destructuring":45,"./transformers/es6-for-of":46,"./transformers/es6-generators":51,"./transformers/es6-let-scoping":56,"./transformers/es6-modules":57,"./transformers/es6-property-name-shorthand":58,"./transformers/es6-rest-parameters":59,"./transformers/es6-spread":60,"./transformers/es6-template-literals":61,"./transformers/es6-unicode-regex":62,"./transformers/es7-abstract-references":63,"./transformers/es7-array-comprehension":64,"./transformers/es7-exponentiation-operator":65,"./transformers/es7-generator-comprehension":66,"./transformers/es7-object-spread":67,"./transformers/playground-memoization-operator":68,"./transformers/playground-method-binding":69,"./transformers/react":70,"./transformers/use-strict":71,lodash:109}],31:[function(require,module,exports){module.exports=Transformer;var traverse=require("../traverse");var t=require("../types");var _=require("lodash");function Transformer(key,transformer){this.transformer=Transformer.normalise(transformer);this.key=key}Transformer.normalise=function(transformer){if(_.isFunction(transformer)){transformer={ast:transformer}}_.each(transformer,function(fns,type){if(type[0]==="_")return;if(_.isFunction(fns))fns={enter:fns};transformer[type]=fns});return transformer};Transformer.prototype.transform=function(file){if(!this.canRun(file))return;var transformer=this.transformer;var ast=file.ast;var astRun=function(key){if(transformer.ast&&transformer.ast[key]){transformer.ast[key](ast,file)}};astRun("enter");var build=function(exit){return function(node,parent,scope){var types=[node.type].concat(t.ALIAS_KEYS[node.type]||[]);var fns=transformer.all;_.each(types,function(type){fns=transformer[type]||fns});if(!fns)return;var fn=fns.enter;if(exit)fn=fns.exit;if(!fn)return;return fn(node,parent,file,scope)}};traverse(ast,{enter:build(),exit:build(true)});astRun("exit")};Transformer.prototype.canRun=function(file){var opts=file.opts;var key=this.key;var blacklist=opts.blacklist;if(blacklist.length&&_.contains(blacklist,key))return false;if(key[0]!=="_"){var whitelist=opts.whitelist;if(whitelist.length&&!_.contains(whitelist,key))return false}return true}},{"../traverse":72,"../types":76,lodash:109}],32:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");var go=function(getBody,node,file,scope){var argumentsId;var thisId;var getArgumentsId=function(){return argumentsId=argumentsId||file.generateUidIdentifier("arguments",scope)};var getThisId=function(){return thisId=thisId||file.generateUidIdentifier("this",scope)};traverse(node,function(node){if(!node._aliasFunction){if(t.isFunction(node)){return false}else{return}}traverse(node,function(node,parent){if(t.isFunction(node)&&!node._aliasFunction){return false}if(node._ignoreAliasFunctions)return false;var getId;if(t.isIdentifier(node)&&node.name==="arguments"){getId=getArgumentsId}else if(t.isThisExpression(node)){getId=getThisId}else{return}if(t.isReferenced(node,parent))return getId()});return false});var body;var pushDeclaration=function(id,init){body=body||getBody();body.unshift(t.variableDeclaration("var",[t.variableDeclarator(id,init)]))};if(argumentsId){pushDeclaration(argumentsId,t.identifier("arguments"))}if(thisId){pushDeclaration(thisId,t.identifier("this"))}};exports.Program=function(node,parent,file,scope){go(function(){return node.body},node,file,scope)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,file,scope){go(function(){t.ensureBlock(node);return node.body.body},node,file,scope)}},{"../../traverse":72,"../../types":76}],33:[function(require,module,exports){exports.BlockStatement=exports.Program={exit:function(node){var unshift=[];node.body=node.body.filter(function(bodyNode){if(bodyNode._blockHoist){unshift.push(bodyNode);return false}else{return true}});node.body=unshift.concat(node.body)}}},{}],34:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.BlockStatement=exports.Program=function(node){var kinds={};_.each(node._declarations,function(declar){var kind=declar.kind||"var";var declarNode=t.variableDeclarator(declar.id,declar.init);if(!declar.init){kinds[kind]=kinds[kind]||[];kinds[kind].push(declarNode)}else{node.body.unshift(t.variableDeclaration(kind,[declarNode]))}});_.each(kinds,function(declars,kind){node.body.unshift(t.variableDeclaration(kind,declars))})}},{"../../types":76,lodash:109}],35:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");exports.MemberExpression=function(node){var prop=node.property;if(t.isIdentifier(prop)&&esutils.keyword.isKeywordES6(prop.name,true)){node.property=t.literal(prop.name);node.computed=true}}},{"../../types":76,esutils:108}],36:[function(require,module,exports){var t=require("../../types");exports.MemberExpression=function(node){var prop=node.property;if(node.computed&&t.isLiteral(prop)&&t.isValidIdentifier(prop.value)){node.property=t.identifier(prop.value);node.computed=false}}},{"../../types":76}],37:[function(require,module,exports){var transform=require("../transform");exports.ast={exit:function(ast,file){if(!transform.transformers.modules.canRun(file))return;if(file.moduleFormatter.transform){file.moduleFormatter.transform(ast)}}}},{"../transform":30}],38:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");exports.Property=function(node){var key=node.key;if(t.isLiteral(key)&&t.isValidIdentifier(key.value)){node.key=t.identifier(key.value);node.computed=false}else if(t.isIdentifier(key)&&esutils.keyword.isKeywordES6(key.name,true)){node.key=t.literal(key.name);node.computed=true}}},{"../../types":76,esutils:108}],39:[function(require,module,exports){var util=require("../../util");var _=require("lodash");exports.Property=function(node){if(node.method)node.method=false};exports.ObjectExpression=function(node,parent,file){var mutatorMap={};node.properties=node.properties.filter(function(prop){if(prop.kind==="get"||prop.kind==="set"){util.pushMutatorMap(mutatorMap,prop.key,prop.kind,prop.value);return false}else{return true}});if(_.isEmpty(mutatorMap))return;var objId=util.getUid(parent,file);return util.template("object-define-properties-closure",{KEY:objId,OBJECT:node,CONTENT:util.template("object-define-properties",{OBJECT:objId,PROPS:util.buildDefineProperties(mutatorMap)})})}},{"../../util":78,lodash:109}],40:[function(require,module,exports){var t=require("../../types");exports.ArrowFunctionExpression=function(node){t.ensureBlock(node);node._aliasFunction=true;node.expression=false;node.type="FunctionExpression";return node}},{"../../types":76}],41:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.ClassDeclaration=function(node,parent,file,scope){var built=new Class(node,file,scope).run();var declar=t.variableDeclaration("let",[t.variableDeclarator(node.id,built)]);t.inheritsComments(declar,node);return declar};exports.ClassExpression=function(node,parent,file,scope){return new Class(node,file,scope).run()};var getMemberExpressionObject=function(node){while(t.isMemberExpression(node)){node=node.object}return node};function Class(node,file,scope){this.scope=scope;this.node=node;this.file=file;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=node.id||file.generateUidIdentifier("class",scope);this.superName=node.superClass}Class.prototype.run=function(){var superClassArgument=this.superName;var superClassCallee=this.superName;var superName=this.superName;var className=this.className;var file=this.file;if(superName){if(t.isMemberExpression(superName)){superClassArgument=superClassCallee=getMemberExpressionObject(superName)}else if(!t.isIdentifier(superName)){superClassArgument=superName;superClassCallee=superName=file.generateUidIdentifier("ref",this.scope)}}this.superName=superName;var container=util.template("class",{CLASS_NAME:className});var block=container.callee.expression.body;var body=this.body=block.body;var constructor=this.constructor=body[0].declarations[0].init;if(this.node.id)constructor.id=className;var returnStatement=body.pop();if(superName){body.push(t.expressionStatement(t.callExpression(file.addDeclaration("extends"),[className,superName])));container.arguments.push(superClassArgument);container.callee.expression.params.push(superClassCallee)}this.buildBody();if(body.length===1){return constructor}else{body.push(returnStatement);return container}};Class.prototype.buildBody=function(){var constructor=this.constructor;var className=this.className;var superName=this.superName;var classBody=this.node.body.body;var body=this.body;var self=this;_.each(classBody,function(node){self.replaceInstanceSuperReferences(node);if(node.key.name==="constructor"){self.pushConstructor(node)}else{self.pushMethod(node)}});if(!this.hasConstructor&&superName){constructor.body.body.push(util.template("class-super-constructor-call",{SUPER_NAME:superName},true))}var instanceProps;var staticProps;if(!_.isEmpty(this.instanceMutatorMap)){var protoId=util.template("prototype-identifier",{CLASS_NAME:className});instanceProps=util.buildDefineProperties(this.instanceMutatorMap,protoId)}if(!_.isEmpty(this.staticMutatorMap)){staticProps=util.buildDefineProperties(this.staticMutatorMap,className)}if(instanceProps||staticProps){staticProps=staticProps||t.literal(null);var args=[className,staticProps];if(instanceProps)args.push(instanceProps);body.push(t.expressionStatement(t.callExpression(this.file.addDeclaration("class-props"),args)))}};Class.prototype.pushMethod=function(node){var methodName=node.key;var mutatorMap=this.instanceMutatorMap;if(node.static)mutatorMap=this.staticMutatorMap;var kind=node.kind;if(kind===""){kind="value";util.pushMutatorMap(mutatorMap,methodName,"writable",t.identifier("true"))}util.pushMutatorMap(mutatorMap,methodName,kind,node)};Class.prototype.superIdentifier=function(methodNode,id,parent){var methodName=methodNode.key;var superName=this.superName||t.identifier("Function");if(parent.property===id){return}else if(t.isCallExpression(parent,{callee:id})){parent.arguments.unshift(t.thisExpression());if(methodName.name==="constructor"){return t.memberExpression(superName,t.identifier("call"))}else{id=superName;if(!methodNode.static){id=t.memberExpression(id,t.identifier("prototype"))}id=t.memberExpression(id,methodName,methodNode.computed);return t.memberExpression(id,t.identifier("call"))}}else if(t.isMemberExpression(parent)&&!methodNode.static){return t.memberExpression(superName,t.identifier("prototype"))}else{return superName}};Class.prototype.replaceInstanceSuperReferences=function(methodNode){var method=methodNode.value;var self=this;traverse(method,function(node,parent){if(t.isIdentifier(node,{name:"super"})){return self.superIdentifier(methodNode,node,parent)}else if(t.isCallExpression(node)){var callee=node.callee;if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;callee.property=t.memberExpression(callee.property,t.identifier("call"));node.arguments.unshift(t.thisExpression())}})};Class.prototype.pushConstructor=function(method){if(method.kind!==""){throw this.file.errorWithNode(method,"illegal kind for constructor method")}var construct=this.constructor;var fn=method.value;this.hasConstructor=true;t.inherits(construct,fn);t.inheritsComments(construct,method);construct.defaults=fn.defaults;construct.params=fn.params;construct.body=fn.body;construct.rest=fn.rest}},{"../../traverse":72,"../../types":76,"../../util":78,lodash:109}],42:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.ObjectExpression=function(node,parent,file){var hasComputed=false;var computed=[];node.properties=node.properties.filter(function(prop){if(prop.computed){hasComputed=true;computed.unshift(prop);return false}else{return true}});if(!hasComputed)return;var objId=util.getUid(parent,file);var container=util.template("function-return-obj",{KEY:objId,OBJECT:node});var containerCallee=container.callee.expression;var containerBody=containerCallee.body.body;containerCallee._aliasFunction=true;_.each(computed,function(prop){containerBody.unshift(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,true),prop.value)))});return container}},{"../../types":76,"../../util":78,lodash:109}],43:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");var _=require("lodash");exports.Program=exports.BlockStatement=exports.ForInStatement=exports.ForOfStatement=exports.ForStatement=function(node,parent,file){var constants={};var check=function(parent,names){_.each(names,function(nameNode,name){if(!_.has(constants,name))return;if(parent&&t.isBlockStatement(parent)&&parent!==constants[name])return;throw file.errorWithNode(nameNode,name+" is read-only")})};var getIds=function(node){return t.getIds(node,true,["MemberExpression"])};_.each(node.body,function(child,parent){if(child&&t.isVariableDeclaration(child,{kind:"const"})){_.each(child.declarations,function(declar){_.each(getIds(declar),function(nameNode,name){var names={};names[name]=nameNode;check(parent,names);constants[name]=parent});declar._ignoreConstant=true});child._ignoreConstant=true;child.kind="let"}});if(_.isEmpty(constants))return;traverse(node,function(child,parent){if(child._ignoreConstant)return;if(t.isVariableDeclaration(child))return;if(t.isVariableDeclarator(child)||t.isDeclaration(child)||t.isAssignmentExpression(child)){check(parent,getIds(child))}})}},{"../../traverse":72,"../../types":76,lodash:109}],44:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.Function=function(node,parent,file,scope){if(!node.defaults||!node.defaults.length)return;t.ensureBlock(node);var ids=node.params.map(function(param){return t.getIds(param)});var closure=false;_.each(node.defaults,function(def,i){if(!def)return;var param=node.params[i];_.each(ids.slice(i),function(ids){var check=function(node,parent){if(!t.isIdentifier(node)||!t.isReferenced(node,parent))return;if(_.contains(ids,node.name)){throw file.errorWithNode(node,"Temporal dead zone - accessing a variable before it's initialized")}if(scope.has(node.name)){closure=true}};check(def,node);traverse(def,check)});var has=scope.get(param.name);if(has&&!_.contains(node.params,has)){closure=true}});var body=[];_.each(node.defaults,function(def,i){if(!def)return;body.push(util.template("if-undefined-set-to",{VARIABLE:node.params[i],DEFAULT:def},true)) });if(closure){var container=t.functionExpression(null,[],node.body,node.generator);container._aliasFunction=true;body.push(t.returnStatement(t.callExpression(container,[])));node.body=t.blockStatement(body)}else{node.body.body=body.concat(node.body.body)}node.defaults=[]}},{"../../traverse":72,"../../types":76,"../../util":78,lodash:109}],45:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var buildVariableAssign=function(opts,id,init){var op=opts.operator;if(t.isMemberExpression(id))op="=";if(op){return t.expressionStatement(t.assignmentExpression("=",id,init))}else{return t.variableDeclaration(opts.kind,[t.variableDeclarator(id,init)])}};var push=function(opts,nodes,elem,parentId){if(t.isObjectPattern(elem)){pushObjectPattern(opts,nodes,elem,parentId)}else if(t.isArrayPattern(elem)){pushArrayPattern(opts,nodes,elem,parentId)}else{nodes.push(buildVariableAssign(opts,elem,parentId))}};var pushObjectPattern=function(opts,nodes,pattern,parentId){_.each(pattern.properties,function(prop,i){if(t.isSpreadProperty(prop)){var keys=[];_.each(pattern.properties,function(prop2,i2){if(i2>=i)return false;if(t.isSpreadProperty(prop2))return;var key=prop2.key;if(t.isIdentifier(key)){key=t.literal(prop2.key.name)}keys.push(key)});keys=t.arrayExpression(keys);var value=t.callExpression(opts.file.addDeclaration("object-spread"),[parentId,keys]);nodes.push(buildVariableAssign(opts,prop.argument,value))}else{var pattern2=prop.value;var patternId2=t.memberExpression(parentId,prop.key,prop.computed);if(t.isPattern(pattern2)){push(opts,nodes,pattern2,patternId2)}else{nodes.push(buildVariableAssign(opts,pattern2,patternId2))}}})};var pushArrayPattern=function(opts,nodes,pattern,parentId){var _parentId=opts.file.generateUidIdentifier("ref",opts.scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(_parentId,opts.file.toArray(parentId))]));parentId=_parentId;_.each(pattern.elements,function(elem,i){if(!elem)return;var newPatternId;if(t.isSpreadElement(elem)){newPatternId=opts.file.toArray(parentId);if(+i>0){newPatternId=t.callExpression(t.memberExpression(newPatternId,t.identifier("slice")),[t.literal(i)])}elem=elem.argument}else{newPatternId=t.memberExpression(parentId,t.literal(i),true)}push(opts,nodes,elem,newPatternId)})};var pushPattern=function(opts){var nodes=opts.nodes;var pattern=opts.pattern;var parentId=opts.id;var file=opts.file;var scope=opts.scope;if(!t.isMemberExpression(parentId)&&!t.isIdentifier(parentId)){var key=file.generateUidIdentifier("ref",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,parentId)]));parentId=key}push(opts,nodes,pattern,parentId)};exports.ForInStatement=exports.ForOfStatement=function(node,parent,file,scope){var declar=node.left;if(!t.isVariableDeclaration(declar))return;var pattern=declar.declarations[0].id;if(!t.isPattern(pattern))return;var key=file.generateUidIdentifier("ref",scope);node.left=t.variableDeclaration(declar.kind,[t.variableDeclarator(key,null)]);var nodes=[];push({kind:declar.kind,file:file,scope:scope},nodes,pattern,key);t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.Function=function(node,parent,file,scope){var nodes=[];var hasDestructuring=false;node.params=node.params.map(function(pattern){if(!t.isPattern(pattern))return pattern;hasDestructuring=true;var parentId=file.generateUidIdentifier("ref",scope);pushPattern({kind:"var",nodes:nodes,pattern:pattern,id:parentId,file:file,scope:scope});return parentId});if(!hasDestructuring)return;t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.ExpressionStatement=function(node,parent,file,scope){var expr=node.expression;if(expr.type!=="AssignmentExpression")return;if(!t.isPattern(expr.left))return;var nodes=[];var ref=file.generateUidIdentifier("ref",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(ref,expr.right)]));push({operator:expr.operator,file:file,scope:scope},nodes,expr.left,ref);return nodes};exports.AssignmentExpression=function(node,parent,file,scope){if(parent.type==="ExpressionStatement")return;if(!t.isPattern(node.left))return;var tempName=file.generateUid("temp",scope);var ref=t.identifier(tempName);scope.push({key:tempName,id:ref});var nodes=[];nodes.push(t.assignmentExpression("=",ref,node.right));push({operator:node.operator,file:file,scope:scope},nodes,node.left,ref);nodes.push(ref);return t.toSequenceExpression(nodes,scope)};exports.VariableDeclaration=function(node,parent,file,scope){if(t.isForInStatement(parent)||t.isForOfStatement(parent))return;var nodes=[];var hasPattern=false;_.each(node.declarations,function(declar){if(t.isPattern(declar.id)){hasPattern=true;return false}});if(!hasPattern)return;_.each(node.declarations,function(declar){var patternId=declar.init;var pattern=declar.id;var opts={kind:node.kind,nodes:nodes,pattern:pattern,id:patternId,file:file,scope:scope};if(t.isPattern(pattern)&&patternId){pushPattern(opts)}else{nodes.push(buildVariableAssign(opts,declar.id,declar.init))}});if(!t.isProgram(parent)&&!t.isBlockStatement(parent)){var declar;_.each(nodes,function(node){declar=declar||t.variableDeclaration(node.kind,[]);if(!t.isVariableDeclaration(node)&&declar.kind!==node.kind){throw file.errorWithNode(node,"Cannot use this node within the current parent")}declar.declarations=declar.declarations.concat(node.declarations)});return declar}return nodes}},{"../../types":76,lodash:109}],46:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.ForOfStatement=function(node,parent,file,scope){var left=node.left;var declar;var stepKey=file.generateUidIdentifier("step",scope);var stepValue=t.memberExpression(stepKey,t.identifier("value"));if(t.isIdentifier(left)){declar=t.expressionStatement(t.assignmentExpression("=",left,stepValue))}else if(t.isVariableDeclaration(left)){declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,stepValue)])}else{throw file.errorWithNode(left,"Unknown node type "+left.type+" in ForOfStatement")}var node2=util.template("for-of",{ITERATOR_KEY:file.generateUidIdentifier("iterator",scope),STEP_KEY:stepKey,OBJECT:node.right});t.ensureBlock(node);var block=node2.body;block.body.push(declar);block.body=block.body.concat(node.body.body);return node2}},{"../../types":76,"../../util":78}],47:[function(require,module,exports){var assert=require("assert");var loc=require("../util").loc;var t=require("../../../../types");exports.ParenthesizedExpression=function(expr,path,explodeViaTempVar,finish){return finish(this.explodeExpression(path.get("expression")))};exports.MemberExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.memberExpression(this.explodeExpression(path.get("object")),expr.computed?explodeViaTempVar(null,path.get("property")):expr.property,expr.computed))};exports.CallExpression=function(expr,path,explodeViaTempVar,finish){var oldCalleePath=path.get("callee");var newCallee=this.explodeExpression(oldCalleePath);if(!t.isMemberExpression(oldCalleePath.node)&&t.isMemberExpression(newCallee)){newCallee=t.sequenceExpression([t.literal(0),newCallee])}return finish(t.callExpression(newCallee,path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})))};exports.NewExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.newExpression(explodeViaTempVar(null,path.get("callee")),path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})))};exports.ObjectExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.objectExpression(path.get("properties").map(function(propPath){return t.property(propPath.value.kind,propPath.value.key,explodeViaTempVar(null,propPath.get("value")))})))};exports.ArrayExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.arrayExpression(path.get("elements").map(function(elemPath){return explodeViaTempVar(null,elemPath)})))};exports.SequenceExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var lastIndex=expr.expressions.length-1;var self=this;var result;path.get("expressions").each(function(exprPath){if(exprPath.name===lastIndex){result=self.explodeExpression(exprPath,ignoreResult)}else{self.explodeExpression(exprPath,true)}});return result};exports.LogicalExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var after=loc();var result;if(!ignoreResult){result=this.makeTempVar()}var left=explodeViaTempVar(result,path.get("left"));if(expr.operator==="&&"){this.jumpIfNot(left,after)}else{assert.strictEqual(expr.operator,"||");this.jumpIf(left,after)}explodeViaTempVar(result,path.get("right"),ignoreResult);this.mark(after);return result};exports.ConditionalExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var elseLoc=loc();var after=loc();var test=this.explodeExpression(path.get("test"));var result;this.jumpIfNot(test,elseLoc);if(!ignoreResult){result=this.makeTempVar()}explodeViaTempVar(result,path.get("consequent"),ignoreResult);this.jump(after);this.mark(elseLoc);explodeViaTempVar(result,path.get("alternate"),ignoreResult);this.mark(after);return result};exports.UnaryExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.unaryExpression(expr.operator,this.explodeExpression(path.get("argument")),!!expr.prefix))};exports.BinaryExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.binaryExpression(expr.operator,explodeViaTempVar(null,path.get("left")),explodeViaTempVar(null,path.get("right"))))};exports.AssignmentExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.assignmentExpression(expr.operator,this.explodeExpression(path.get("left")),this.explodeExpression(path.get("right"))))};exports.UpdateExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.updateExpression(expr.operator,this.explodeExpression(path.get("argument")),expr.prefix))};exports.YieldExpression=function(expr,path){var after=loc();var arg=expr.argument&&this.explodeExpression(path.get("argument"));var result;if(arg&&expr.delegate){result=this.makeTempVar();this.emit(t.returnStatement(t.callExpression(this.contextProperty("delegateYield"),[arg,t.literal(result.property.name),after])));this.mark(after);return result}this.emitAssign(this.contextProperty("next"),after);this.emit(t.returnStatement(arg||null));this.mark(after);return this.contextProperty("sent")}},{"../../../../types":76,"../util":54,assert:94}],48:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var leap=require("../leap");var util=require("../util");var t=require("../../../../types");var runtimeKeysMethod=util.runtimeProperty("keys");var loc=util.loc;exports.ExpressionStatement=function(path){this.explodeExpression(path.get("expression"),true)};exports.LabeledStatement=function(path,stmt){this.explodeStatement(path.get("body"),stmt.label)};exports.WhileStatement=function(path,stmt,labelId){var before=loc();var after=loc();this.mark(before);this.jumpIfNot(this.explodeExpression(path.get("test")),after);this.leapManager.withEntry(new leap.LoopEntry(after,before,labelId),function(){this.explodeStatement(path.get("body"))});this.jump(before);this.mark(after)};exports.DoWhileStatement=function(path,stmt,labelId){var first=loc();var test=loc();var after=loc();this.mark(first);this.leapManager.withEntry(new leap.LoopEntry(after,test,labelId),function(){this.explode(path.get("body"))});this.mark(test);this.jumpIf(this.explodeExpression(path.get("test")),first);this.mark(after)};exports.ForStatement=function(path,stmt,labelId){var head=loc();var update=loc();var after=loc();if(stmt.init){this.explode(path.get("init"),true)}this.mark(head);if(stmt.test){this.jumpIfNot(this.explodeExpression(path.get("test")),after)}else{}this.leapManager.withEntry(new leap.LoopEntry(after,update,labelId),function(){this.explodeStatement(path.get("body"))});this.mark(update);if(stmt.update){this.explode(path.get("update"),true)}this.jump(head);this.mark(after)};exports.ForInStatement=function(path,stmt,labelId){t.assertIdentifier(stmt.left);var head=loc();var after=loc();var keyIterNextFn=this.makeTempVar();this.emitAssign(keyIterNextFn,t.callExpression(runtimeKeysMethod,[this.explodeExpression(path.get("right"))]));this.mark(head);var keyInfoTmpVar=this.makeTempVar();this.jumpIf(t.memberExpression(t.assignmentExpression("=",keyInfoTmpVar,t.callExpression(keyIterNextFn,[])),t.identifier("done"),false),after);this.emitAssign(stmt.left,t.memberExpression(keyInfoTmpVar,t.identifier("value"),false));this.leapManager.withEntry(new leap.LoopEntry(after,head,labelId),function(){this.explodeStatement(path.get("body"))});this.jump(head);this.mark(after)};exports.BreakStatement=function(path,stmt){this.emitAbruptCompletion({type:"break",target:this.leapManager.getBreakLoc(stmt.label)})};exports.ContinueStatement=function(path,stmt){this.emitAbruptCompletion({type:"continue",target:this.leapManager.getContinueLoc(stmt.label)})};exports.SwitchStatement=function(path,stmt){var disc=this.emitAssign(this.makeTempVar(),this.explodeExpression(path.get("discriminant")));var after=loc();var defaultLoc=loc();var condition=defaultLoc;var caseLocs=[];var self=this;var cases=stmt.cases||[];for(var i=cases.length-1;i>=0;--i){var c=cases[i];t.assertSwitchCase(c);if(c.test){condition=t.conditionalExpression(t.binaryExpression("===",disc,c.test),caseLocs[i]=loc(),condition)}else{caseLocs[i]=defaultLoc}}this.jump(this.explodeExpression(new types.NodePath(condition,path,"discriminant")));this.leapManager.withEntry(new leap.SwitchEntry(after),function(){path.get("cases").each(function(casePath){var i=casePath.name;self.mark(caseLocs[i]);casePath.get("consequent").each(self.explodeStatement,self)})});this.mark(after);if(defaultLoc.value===-1){this.mark(defaultLoc);assert.strictEqual(after.value,defaultLoc.value)}};exports.IfStatement=function(path,stmt){var elseLoc=stmt.alternate&&loc();var after=loc();this.jumpIfNot(this.explodeExpression(path.get("test")),elseLoc||after);this.explodeStatement(path.get("consequent"));if(elseLoc){this.jump(after);this.mark(elseLoc);this.explodeStatement(path.get("alternate"))}this.mark(after)};exports.ReturnStatement=function(path){this.emitAbruptCompletion({type:"return",value:this.explodeExpression(path.get("argument"))})};exports.TryStatement=function(path,stmt){var after=loc();var self=this;var handler=stmt.handler;if(!handler&&stmt.handlers){handler=stmt.handlers[0]||null}var catchLoc=handler&&loc();var catchEntry=catchLoc&&new leap.CatchEntry(catchLoc,handler.param);var finallyLoc=stmt.finalizer&&loc();var finallyEntry=finallyLoc&&new leap.FinallyEntry(finallyLoc);var tryEntry=new leap.TryEntry(this.getUnmarkedCurrentLoc(),catchEntry,finallyEntry);this.tryEntries.push(tryEntry);this.updateContextPrevLoc(tryEntry.firstLoc);this.leapManager.withEntry(tryEntry,function(){this.explodeStatement(path.get("block"));if(catchLoc){if(finallyLoc){this.jump(finallyLoc)}else{this.jump(after)}this.updateContextPrevLoc(self.mark(catchLoc));var bodyPath=path.get("handler","body");var safeParam=this.makeTempVar();this.clearPendingException(tryEntry.firstLoc,safeParam);var catchScope=bodyPath.scope;var catchParamName=handler.param.name;t.assertCatchClause(catchScope.node);assert.strictEqual(catchScope.lookup(catchParamName),catchScope);types.visit(bodyPath,{visitIdentifier:function(path){if(path.value.name===catchParamName&&path.scope.lookup(catchParamName)===catchScope){return safeParam}this.traverse(path)}});this.leapManager.withEntry(catchEntry,function(){this.explodeStatement(bodyPath)})}if(finallyLoc){this.updateContextPrevLoc(this.mark(finallyLoc));this.leapManager.withEntry(finallyEntry,function(){this.explodeStatement(path.get("finalizer"))});this.emit(t.callExpression(this.contextProperty("finish"),[finallyEntry.firstLoc]))}});this.mark(after)};exports.ThrowStatement=function(path){this.emit(t.throwStatement(this.explodeExpression(path.get("argument"))))}},{"../../../../types":76,"../leap":52,"../util":54,assert:94,"ast-types":92}],49:[function(require,module,exports){exports.Emitter=Emitter;var explodeExpressions=require("./explode-expressions");var explodeStatements=require("./explode-statements");var assert=require("assert");var types=require("ast-types");var leap=require("../leap");var meta=require("../meta");var util=require("../util");var t=require("../../../../types");var _=require("lodash");var loc=util.loc;var n=types.namedTypes;function Emitter(contextId){assert.ok(this instanceof Emitter);t.assertIdentifier(contextId);this.contextId=contextId;this.listing=[];this.marked=[true];this.finalLoc=loc();this.tryEntries=[];this.leapManager=new leap.LeapManager(this)}Emitter.prototype.mark=function(loc){t.assertLiteral(loc);var index=this.listing.length;if(loc.value===-1){loc.value=index}else{assert.strictEqual(loc.value,index)}this.marked[index]=true;return loc};Emitter.prototype.emit=function(node){if(t.isExpression(node))node=t.expressionStatement(node);t.assertStatement(node);this.listing.push(node)};Emitter.prototype.emitAssign=function(lhs,rhs){this.emit(this.assign(lhs,rhs));return lhs};Emitter.prototype.assign=function(lhs,rhs){return t.expressionStatement(t.assignmentExpression("=",lhs,rhs))};Emitter.prototype.contextProperty=function(name,computed){return t.memberExpression(this.contextId,computed?t.literal(name):t.identifier(name),!!computed)};var volatileContextPropertyNames={prev:true,next:true,sent:true,rval:true};Emitter.prototype.isVolatileContextProperty=function(expr){if(t.isMemberExpression(expr)){if(expr.computed){return true}if(t.isIdentifier(expr.object)&&t.isIdentifier(expr.property)&&expr.object.name===this.contextId.name&&_.has(volatileContextPropertyNames,expr.property.name)){return true}}return false};Emitter.prototype.stop=function(rval){if(rval){this.setReturnValue(rval)}this.jump(this.finalLoc)};Emitter.prototype.setReturnValue=function(valuePath){t.assertExpression(valuePath.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(valuePath))};Emitter.prototype.clearPendingException=function(tryLoc,assignee){t.assertLiteral(tryLoc);var catchCall=t.callExpression(this.contextProperty("catch",true),[tryLoc]);if(assignee){this.emitAssign(assignee,catchCall)}else{this.emit(catchCall)}};Emitter.prototype.jump=function(toLoc){this.emitAssign(this.contextProperty("next"),toLoc);this.emit(t.breakStatement())};Emitter.prototype.jumpIf=function(test,toLoc){t.assertExpression(test);t.assertLiteral(toLoc);this.emit(t.ifStatement(test,t.blockStatement([this.assign(this.contextProperty("next"),toLoc),t.breakStatement()])))};Emitter.prototype.jumpIfNot=function(test,toLoc){t.assertExpression(test);t.assertLiteral(toLoc);var negatedTest;if(t.isUnaryExpression(test)&&test.operator==="!"){negatedTest=test.argument}else{negatedTest=t.unaryExpression("!",test)}this.emit(t.ifStatement(negatedTest,t.blockStatement([this.assign(this.contextProperty("next"),toLoc),t.breakStatement()])))};var nextTempId=0;Emitter.prototype.makeTempVar=function(){return this.contextProperty("t"+nextTempId++)};Emitter.prototype.getContextFunction=function(id){var node=t.functionExpression(id||null,[this.contextId],t.blockStatement([this.getDispatchLoop()]),false,false);node._aliasFunction=true;return node};Emitter.prototype.getDispatchLoop=function(){var self=this;var cases=[];var current;var alreadyEnded=false;self.listing.forEach(function(stmt,i){if(self.marked.hasOwnProperty(i)){cases.push(t.switchCase(t.literal(i),current=[]));alreadyEnded=false}if(!alreadyEnded){current.push(stmt);if(isSwitchCaseEnder(stmt))alreadyEnded=true}});this.finalLoc.value=this.listing.length;cases.push(t.switchCase(this.finalLoc,[]),t.switchCase(t.literal("end"),[t.returnStatement(t.callExpression(this.contextProperty("stop"),[]))]));return t.whileStatement(t.literal(true),t.switchStatement(t.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),cases))};function isSwitchCaseEnder(stmt){return t.isBreakStatement(stmt)||t.isContinueStatement(stmt)||t.isReturnStatement(stmt)||t.isThrowStatement(stmt)}Emitter.prototype.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var lastLocValue=0;return t.arrayExpression(this.tryEntries.map(function(tryEntry){var thisLocValue=tryEntry.firstLoc.value;assert.ok(thisLocValue>=lastLocValue,"try entries out of order");lastLocValue=thisLocValue;var ce=tryEntry.catchEntry;var fe=tryEntry.finallyEntry;var triple=[tryEntry.firstLoc,ce?ce.firstLoc:null];if(fe){triple[2]=fe.firstLoc}return t.arrayExpression(triple)}))};Emitter.prototype.explode=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var node=path.value;var self=this;n.Node.check(node);if(t.isStatement(node))return self.explodeStatement(path);if(t.isExpression(node))return self.explodeExpression(path,ignoreResult);if(t.isDeclaration(node))throw getDeclError(node);switch(node.type){case"Program":return path.get("body").map(self.explodeStatement,self);case"VariableDeclarator":throw getDeclError(node);case"Property":case"SwitchCase":case"CatchClause":throw new Error(node.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(node.type))}};function getDeclError(node){return new Error("all declarations should have been transformed into "+"assignments before the Exploder began its work: "+JSON.stringify(node))}Emitter.prototype.explodeStatement=function(path,labelId){assert.ok(path instanceof types.NodePath);var stmt=path.value;var self=this;t.assertStatement(stmt);if(labelId){t.assertIdentifier(labelId)}else{labelId=null}if(t.isBlockStatement(stmt)){return path.get("body").each(self.explodeStatement,self)}if(!meta.containsLeap(stmt)){self.emit(stmt);return}var fn=explodeStatements[stmt.type];if(fn){fn.call(this,path,stmt,labelId)}else{throw new Error("unknown Statement of type "+JSON.stringify(stmt.type))}};Emitter.prototype.emitAbruptCompletion=function(record){if(!isValidCompletion(record)){assert.ok(false,"invalid completion record: "+JSON.stringify(record))}assert.notStrictEqual(record.type,"normal","normal completions are not abrupt");var abruptArgs=[t.literal(record.type)];if(record.type==="break"||record.type==="continue"){t.assertLiteral(record.target);abruptArgs[1]=record.target}else if(record.type==="return"||record.type==="throw"){if(record.value){t.assertExpression(record.value);abruptArgs[1]=record.value}}this.emit(t.returnStatement(t.callExpression(this.contextProperty("abrupt"),abruptArgs)))};function isValidCompletion(record){var type=record.type;if(type==="normal"){return!_.has(record,"target")}if(type==="break"||type==="continue"){return!_.has(record,"value")&&t.isLiteral(record.target)}if(type==="return"||type==="throw"){return _.has(record,"value")&&!_.has(record,"target")}return false}Emitter.prototype.getUnmarkedCurrentLoc=function(){return t.literal(this.listing.length)};Emitter.prototype.updateContextPrevLoc=function(loc){if(loc){t.assertLiteral(loc);if(loc.value===-1){loc.value=this.listing.length}else{assert.strictEqual(loc.value,this.listing.length)}}else{loc=this.getUnmarkedCurrentLoc()}this.emitAssign(this.contextProperty("prev"),loc)};Emitter.prototype.explodeExpression=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var expr=path.value;if(expr){t.assertExpression(expr)}else{return expr}var self=this;function finish(expr){t.assertExpression(expr);if(ignoreResult){self.emit(expr)}else{return expr}}if(!meta.containsLeap(expr)){return finish(expr)}var hasLeapingChildren=meta.containsLeap.onlyChildren(expr);function explodeViaTempVar(tempVar,childPath,ignoreChildResult){assert.ok(childPath instanceof types.NodePath);assert.ok(!ignoreChildResult||!tempVar,"Ignoring the result of a child expression but forcing it to "+"be assigned to a temporary variable?");var result=self.explodeExpression(childPath,ignoreChildResult);if(ignoreChildResult){}else if(tempVar||hasLeapingChildren&&(self.isVolatileContextProperty(result)||meta.hasSideEffects(result))){result=self.emitAssign(tempVar||self.makeTempVar(),result)}return result}var fn=explodeExpressions[expr.type];if(fn){return fn.call(this,expr,path,explodeViaTempVar,finish,ignoreResult)}else{throw new Error("unknown Expression of type "+JSON.stringify(expr.type))}}},{"../../../../types":76,"../leap":52,"../meta":53,"../util":54,"./explode-expressions":47,"./explode-statements":48,assert:94,"ast-types":92,lodash:109}],50:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var t=require("../../../types");var _=require("lodash");exports.hoist=function(funPath){assert.ok(funPath instanceof types.NodePath);t.assertFunction(funPath.value);var vars={};function varDeclToExpr(vdec,includeIdentifiers){t.assertVariableDeclaration(vdec);var exprs=[];vdec.declarations.forEach(function(dec){vars[dec.id.name]=dec.id;if(dec.init){exprs.push(t.assignmentExpression("=",dec.id,dec.init))}else if(includeIdentifiers){exprs.push(dec.id)}});if(exprs.length===0)return null;if(exprs.length===1)return exprs[0];return t.sequenceExpression(exprs)}types.visit(funPath.get("body"),{visitVariableDeclaration:function(path){var expr=varDeclToExpr(path.value,false);if(expr===null){path.replace()}else{return t.expressionStatement(expr)}return false},visitForStatement:function(path){var init=path.value.init;if(t.isVariableDeclaration(init)){path.get("init").replace(varDeclToExpr(init,false))}this.traverse(path)},visitForInStatement:function(path){var left=path.value.left;if(t.isVariableDeclaration(left)){path.get("left").replace(varDeclToExpr(left,true))}this.traverse(path)},visitFunctionDeclaration:function(path){var node=path.value;vars[node.id.name]=node.id;var assignment=t.expressionStatement(t.assignmentExpression("=",node.id,t.functionExpression(node.id,node.params,node.body,node.generator,node.expression)));if(t.isBlockStatement(path.parent.node)){path.parent.get("body").unshift(assignment);path.replace()}else{path.replace(assignment)}return false},visitFunctionExpression:function(){return false}});var paramNames={};funPath.get("params").each(function(paramPath){var param=paramPath.value;if(t.isIdentifier(param)){paramNames[param.name]=param}else{}});var declarations=[];Object.keys(vars).forEach(function(name){if(!_.has(paramNames,name)){declarations.push(t.variableDeclarator(vars[name],null))}});if(declarations.length===0){return null}return t.variableDeclaration("var",declarations)}},{"../../../types":76,assert:94,"ast-types":92,lodash:109}],51:[function(require,module,exports){module.exports=require("./visit").transform},{"./visit":55}],52:[function(require,module,exports){exports.FunctionEntry=FunctionEntry;exports.FinallyEntry=FinallyEntry;exports.SwitchEntry=SwitchEntry;exports.LeapManager=LeapManager;exports.CatchEntry=CatchEntry;exports.LoopEntry=LoopEntry;exports.TryEntry=TryEntry;var assert=require("assert");var util=require("util");var t=require("../../../types");var inherits=util.inherits;function Entry(){assert.ok(this instanceof Entry)}function FunctionEntry(returnLoc){Entry.call(this);t.assertLiteral(returnLoc);this.returnLoc=returnLoc}inherits(FunctionEntry,Entry);function LoopEntry(breakLoc,continueLoc,label){Entry.call(this);t.assertLiteral(breakLoc);t.assertLiteral(continueLoc);if(label){t.assertIdentifier(label)}else{label=null}this.breakLoc=breakLoc;this.continueLoc=continueLoc;this.label=label}inherits(LoopEntry,Entry);function SwitchEntry(breakLoc){Entry.call(this);t.assertLiteral(breakLoc);this.breakLoc=breakLoc}inherits(SwitchEntry,Entry);function TryEntry(firstLoc,catchEntry,finallyEntry){Entry.call(this);t.assertLiteral(firstLoc);if(catchEntry){assert.ok(catchEntry instanceof CatchEntry)}else{catchEntry=null}if(finallyEntry){assert.ok(finallyEntry instanceof FinallyEntry)}else{finallyEntry=null}assert.ok(catchEntry||finallyEntry);this.firstLoc=firstLoc;this.catchEntry=catchEntry;this.finallyEntry=finallyEntry}inherits(TryEntry,Entry);function CatchEntry(firstLoc,paramId){Entry.call(this);t.assertLiteral(firstLoc);t.assertIdentifier(paramId);this.firstLoc=firstLoc;this.paramId=paramId}inherits(CatchEntry,Entry);function FinallyEntry(firstLoc){Entry.call(this);t.assertLiteral(firstLoc);this.firstLoc=firstLoc}inherits(FinallyEntry,Entry);function LeapManager(emitter){assert.ok(this instanceof LeapManager);var Emitter=require("./emit").Emitter;assert.ok(emitter instanceof Emitter);this.emitter=emitter;this.entryStack=[new FunctionEntry(emitter.finalLoc)]}LeapManager.prototype.withEntry=function(entry,callback){assert.ok(entry instanceof Entry);this.entryStack.push(entry);try{callback.call(this.emitter)}finally{var popped=this.entryStack.pop();assert.strictEqual(popped,entry)}};LeapManager.prototype._findLeapLocation=function(property,label){for(var i=this.entryStack.length-1;i>=0;--i){var entry=this.entryStack[i];var loc=entry[property];if(loc){if(label){if(entry.label&&entry.label.name===label.name){return loc}}else{return loc}}}return null};LeapManager.prototype.getBreakLoc=function(label){return this._findLeapLocation("breakLoc",label)};LeapManager.prototype.getContinueLoc=function(label){return this._findLeapLocation("continueLoc",label)}},{"../../../types":76,"./emit":49,assert:94,util:103}],53:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var m=require("private").makeAccessor();var _=require("lodash");var isArray=types.builtInTypes.array;var n=types.namedTypes;function makePredicate(propertyName,knownTypes){function onlyChildren(node){n.Node.check(node);var result=false;function check(child){if(result){}else if(isArray.check(child)){child.some(check)}else if(n.Node.check(child)){assert.strictEqual(result,false);result=predicate(child)}return result}types.eachField(node,function(name,child){check(child)});return result}function predicate(node){n.Node.check(node);var meta=m(node);if(_.has(meta,propertyName))return meta[propertyName];if(_.has(opaqueTypes,node.type))return meta[propertyName]=false;if(_.has(knownTypes,node.type))return meta[propertyName]=true;return meta[propertyName]=onlyChildren(node)}predicate.onlyChildren=onlyChildren;return predicate}var opaqueTypes={FunctionExpression:true};var sideEffectTypes={CallExpression:true,ForInStatement:true,UnaryExpression:true,BinaryExpression:true,AssignmentExpression:true,UpdateExpression:true,NewExpression:true};var leapTypes={YieldExpression:true,BreakStatement:true,ContinueStatement:true,ReturnStatement:true,ThrowStatement:true};for(var type in leapTypes){if(_.has(leapTypes,type)){sideEffectTypes[type]=leapTypes[type]}}exports.hasSideEffects=makePredicate("hasSideEffects",sideEffectTypes);exports.containsLeap=makePredicate("containsLeap",leapTypes)},{assert:94,"ast-types":92,lodash:109,"private":110}],54:[function(require,module,exports){var t=require("../../../types");exports.runtimeProperty=function(name){return t.memberExpression(t.identifier("regeneratorRuntime"),t.identifier(name))};exports.loc=function(){return t.literal(-1)}},{"../../../types":76}],55:[function(require,module,exports){var runtimeProperty=require("./util").runtimeProperty;var Emitter=require("./emit").Emitter;var hoist=require("./hoist").hoist;var types=require("ast-types");var t=require("../../../types");var runtimeAsyncMethod=runtimeProperty("async");var runtimeWrapMethod=runtimeProperty("wrap");var runtimeMarkMethod=runtimeProperty("mark");exports.transform=function transform(node,file){return types.visit(node,{visitFunction:function(path){return visitor.call(this,path,file)}})};var visitor=function(path,file){this.traverse(path);var node=path.value;var scope;if(!node.generator&&!node.async){return}node.generator=false;if(node.expression){node.expression=false;node.body=t.blockStatement([t.returnStatement(node.body)])}if(node.async){awaitVisitor.visit(path.get("body"))}var outerFnId=node.id||(node.id=file.generateUidIdentifier("callee",scope)); var innerFnId=t.identifier(node.id.name+"$");var contextId=file.generateUidIdentifier("context",scope);var vars=hoist(path);var emitter=new Emitter(contextId);emitter.explode(path.get("body"));var outerBody=[];if(vars&&vars.declarations.length>0){outerBody.push(vars)}var wrapArgs=[emitter.getContextFunction(innerFnId),node.async?t.literal(null):outerFnId,t.thisExpression()];var tryEntryList=emitter.getTryEntryList();if(tryEntryList){wrapArgs.push(tryEntryList)}var wrapCall=t.callExpression(node.async?runtimeAsyncMethod:runtimeWrapMethod,wrapArgs);outerBody.push(t.returnStatement(wrapCall));node.body=t.blockStatement(outerBody);if(node.async){node.async=false;return}if(t.isFunctionDeclaration(node)){var pp=path.parent;while(pp&&!(t.isBlockStatement(pp.value)||t.isProgram(pp.value))){pp=pp.parent}if(!pp){return}path.replace();node.type="FunctionExpression";var varDecl=t.variableDeclaration("var",[t.variableDeclarator(node.id,t.callExpression(runtimeMarkMethod,[node]))]);t.inheritsComments(varDecl,node);t.removeComments(node);varDecl._blockHoist=true;var bodyPath=pp.get("body");var bodyLen=bodyPath.value.length;for(var i=0;i<bodyLen;++i){var firstStmtPath=bodyPath.get(i);if(!shouldNotHoistAbove(firstStmtPath)){firstStmtPath.insertBefore(varDecl);return}}bodyPath.push(varDecl)}else{t.assertFunctionExpression(node);return t.callExpression(runtimeMarkMethod,[node])}};function shouldNotHoistAbove(stmtPath){var value=stmtPath.value;t.assertStatement(value);if(t.isExpressionStatement(value)&&t.isLiteral(value.expression)&&value.expression.value==="use strict"){return true}if(t.isVariableDeclaration(value)){for(var i=0;i<value.declarations.length;++i){var decl=value.declarations[i];if(t.isCallExpression(decl.init)&&types.astNodesAreEquivalent(decl.init.callee,runtimeMarkMethod)){return true}}}return false}var awaitVisitor=types.PathVisitor.fromMethodsObject({visitFunction:function(){return false},visitAwaitExpression:function(path){return t.yieldExpression(path.value.argument,false)}})},{"../../../types":76,"./emit":49,"./hoist":50,"./util":54,"ast-types":92}],56:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");var isLet=function(node){if(!t.isVariableDeclaration(node))return false;if(node._let)return true;if(node.kind!=="let")return false;node._let=true;node.kind="var";return true};var isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!isLet(node)};var standardiseLets=function(declars){_.each(declars,function(declar){delete declar._let})};exports.VariableDeclaration=function(node){isLet(node)};exports.For=function(node,parent,file,scope){var init=node.left||node.init;if(isLet(init)){t.ensureBlock(node);node.body._letDeclars=[init]}if(t.isLabeledStatement(parent)){node.label=parent.label}var letScoping=new LetScoping(node,node.body,parent,file,scope);letScoping.run();if(node.label&&!t.isLabeledStatement(parent)){return t.labeledStatement(node.label,node)}};exports.BlockStatement=function(block,parent,file,scope){if(!t.isFor(parent)){var letScoping=new LetScoping(false,block,parent,file,scope);letScoping.run()}};function LetScoping(forParent,block,parent,file,scope){this.forParent=forParent;this.parent=parent;this.scope=scope;this.block=block;this.file=file;this.letReferences={};this.body=[]}LetScoping.prototype.run=function(){var block=this.block;if(block._letDone)return;block._letDone=true;this.info=this.getInfo();this.remap();if(t.isFunction(this.parent))return this.noClosure();if(!this.info.keys.length)return this.noClosure();var referencesInClosure=this.getLetReferences();if(!referencesInClosure)return this.noClosure();this.has=this.checkFor();this.hoistVarDeclarations();standardiseLets(this.info.declarators);var letReferences=_.values(this.letReferences);var fn=t.functionExpression(null,letReferences,t.blockStatement(block.body));fn._aliasFunction=true;block.body=this.body;var params=this.getParams(letReferences);var call=t.callExpression(fn,params);var ret=this.file.generateUidIdentifier("ret",this.scope);var hasYield=traverse.hasType(fn.body,"YieldExpression",t.FUNCTION_TYPES);if(hasYield){fn.generator=true;call=t.yieldExpression(call,true)}this.build(ret,call)};LetScoping.prototype.noClosure=function(){standardiseLets(this.info.declarators)};LetScoping.prototype.remap=function(){var replacements=this.info.duplicates;var block=this.block;if(_.isEmpty(replacements))return;var replace=function(node,parent,scope){if(!t.isIdentifier(node))return;if(!t.isReferenced(node,parent))return;if(scope&&scope.hasOwn(node.name))return;node.name=replacements[node.name]||node.name};var traverseReplace=function(node,parent){replace(node,parent);traverse(node,replace)};var forParent=this.forParent;if(forParent){traverseReplace(forParent.right,forParent);traverseReplace(forParent.test,forParent);traverseReplace(forParent.update,forParent)}traverse(block,replace)};LetScoping.prototype.getInfo=function(){var block=this.block;var scope=this.scope;var file=this.file;var opts={outsideKeys:[],declarators:block._letDeclars||[],duplicates:{},keys:[]};var duplicates=function(id,key){var has=scope.parentGet(key);if(has&&has!==id){opts.duplicates[key]=id.name=file.generateUid(key,scope)}};_.each(opts.declarators,function(declar){opts.declarators.push(declar);var keys=t.getIds(declar,true);_.each(keys,duplicates);keys=_.keys(keys);opts.outsideKeys=opts.outsideKeys.concat(keys);opts.keys=opts.keys.concat(keys)});_.each(block.body,function(declar){if(!isLet(declar))return;_.each(t.getIds(declar,true),function(id,key){duplicates(id,key);opts.keys.push(key)})});return opts};LetScoping.prototype.checkFor=function(){var has={hasContinue:false,hasReturn:false,hasBreak:false};var forParent=this.forParent;traverse(this.block,function(node){var replace;if(t.isFunction(node)||t.isFor(node)){return false}if(forParent&&node&&!node.label){if(t.isBreakStatement(node)){has.hasBreak=true;replace=t.returnStatement(t.literal("break"))}else if(t.isContinueStatement(node)){has.hasContinue=true;replace=t.returnStatement(t.literal("continue"))}}if(t.isReturnStatement(node)){has.hasReturn=true;replace=t.returnStatement(t.objectExpression([t.property("init",t.identifier("v"),node.argument||t.identifier("undefined"))]))}if(replace)return t.inherits(replace,node)});return has};LetScoping.prototype.hoistVarDeclarations=function(){var self=this;traverse(this.block,function(node){if(t.isForStatement(node)){if(isVar(node.init)){node.init=t.sequenceExpression(self.pushDeclar(node.init))}}else if(t.isFor(node)){if(isVar(node.left)){node.left=node.left.declarations[0].id}}else if(isVar(node)){return self.pushDeclar(node).map(t.expressionStatement)}else if(t.isFunction(node)){return false}})};LetScoping.prototype.getParams=function(params){var info=this.info;params=_.cloneDeep(params);_.each(params,function(param){param.name=info.duplicates[param.name]||param.name});return params};LetScoping.prototype.getLetReferences=function(){var closurify=false;var self=this;traverse(this.block,function(node,parent,scope){if(t.isFunction(node)){traverse(node,function(node,parent){if(!t.isIdentifier(node))return;if(!t.isReferenced(node,parent))return;if(scope.hasOwn(node.name))return;closurify=true;if(!_.contains(self.info.outsideKeys,node.name))return;self.letReferences[node.name]=node});return false}else if(t.isFor(node)){return false}});return closurify};LetScoping.prototype.pushDeclar=function(node){this.body.push(t.variableDeclaration(node.kind,node.declarations.map(function(declar){return t.variableDeclarator(declar.id)})));var replace=[];_.each(node.declarations,function(declar){if(!declar.init)return;var expr=t.assignmentExpression("=",declar.id,declar.init);replace.push(t.inherits(expr,declar))});return replace};LetScoping.prototype.build=function(ret,call){var has=this.has;if(has.hasReturn||has.hasBreak||has.hasContinue){this.buildHas(ret,call)}else{this.body.push(t.expressionStatement(call))}};LetScoping.prototype.buildHas=function(ret,call){var body=this.body;body.push(t.variableDeclaration("var",[t.variableDeclarator(ret,call)]));var forParent=this.forParent;var retCheck;var has=this.has;var cases=[];if(has.hasReturn){retCheck=util.template("let-scoping-return",{RETURN:ret})}if(has.hasBreak||has.hasContinue){var label=forParent.label=forParent.label||this.file.generateUidIdentifier("loop",this.scope);if(has.hasBreak){cases.push(t.switchCase(t.literal("break"),[t.breakStatement(label)]))}if(has.hasContinue){cases.push(t.switchCase(t.literal("continue"),[t.continueStatement(label)]))}if(has.hasReturn){cases.push(t.switchCase(null,[retCheck]))}if(cases.length===1){var single=cases[0];body.push(t.ifStatement(t.binaryExpression("===",ret,single.test),single.consequent[0]))}else{body.push(t.switchStatement(ret,cases))}}else{if(has.hasReturn)body.push(retCheck)}}},{"../../traverse":72,"../../types":76,"../../util":78,lodash:109}],57:[function(require,module,exports){var _=require("lodash");exports.ImportDeclaration=function(node,parent,file){var nodes=[];if(node.specifiers.length){_.each(node.specifiers,function(specifier){file.moduleFormatter.importSpecifier(specifier,node,nodes,parent)})}else{file.moduleFormatter.import(node,nodes,parent)}return nodes};exports.ExportDeclaration=function(node,parent,file){var nodes=[];if(node.declaration){file.moduleFormatter.export(node,nodes,parent)}else{_.each(node.specifiers,function(specifier){file.moduleFormatter.exportSpecifier(specifier,node,nodes,parent)})}return nodes}},{lodash:109}],58:[function(require,module,exports){exports.Property=function(node){if(node.shorthand)node.shorthand=false}},{}],59:[function(require,module,exports){var t=require("../../types");exports.Function=function(node,parent,file){if(!node.rest)return;var rest=node.rest;delete node.rest;t.ensureBlock(node);var call=file.toArray(t.identifier("arguments"));if(node.params.length){call.arguments.push(t.literal(node.params.length))}call._ignoreAliasFunctions=true;node.body.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(rest,call)]))}},{"../../types":76}],60:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var getSpreadLiteral=function(spread,file){return file.toArray(spread.argument)};var hasSpread=function(nodes){var has=false;_.each(nodes,function(node){if(t.isSpreadElement(node)){has=true;return false}});return has};var build=function(props,file){var nodes=[];var _props=[];var push=function(){if(!_props.length)return;nodes.push(t.arrayExpression(_props));_props=[]};_.each(props,function(prop){if(t.isSpreadElement(prop)){push();nodes.push(getSpreadLiteral(prop,file))}else{_props.push(prop)}});push();return nodes};exports.ArrayExpression=function(node,parent,file){var elements=node.elements;if(!hasSpread(elements))return;var nodes=build(elements,file);var first=nodes.shift();if(!t.isArrayExpression(first)){nodes.unshift(first);first=t.arrayExpression([])}return t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)};exports.CallExpression=function(node,parent,file){var args=node.arguments;if(!hasSpread(args))return;var contextLiteral=t.literal(null);node.arguments=[];var nodes=build(args,file);var first=nodes.shift();if(nodes.length){node.arguments.push(t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes))}else{node.arguments.push(first)}var callee=node.callee;if(t.isMemberExpression(callee)){contextLiteral=callee.object;if(callee.computed){callee.object=t.memberExpression(callee.object,callee.property,true);callee.property=t.identifier("apply");callee.computed=false}else{callee.property=t.memberExpression(callee.property,t.identifier("apply"))}}else{node.callee=t.memberExpression(node.callee,t.identifier("apply"))}node.arguments.unshift(contextLiteral)};exports.NewExpression=function(node,parent,file){var args=node.arguments;if(!hasSpread(args))return;var nodes=build(args,file);var first=nodes.shift();if(nodes.length){args=t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)}else{args=first}return t.callExpression(file.addDeclaration("apply-constructor"),[node.callee,args])}},{"../../types":76,lodash:109}],61:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var buildBinaryExpression=function(left,right){return t.binaryExpression("+",left,right)};exports.TaggedTemplateExpression=function(node,parent,file){var args=[];var quasi=node.quasi;var strings=[];var raw=[];_.each(quasi.quasis,function(elem){strings.push(t.literal(elem.value.cooked));raw.push(t.literal(elem.value.raw))});args.push(t.callExpression(file.addDeclaration("tagged-template-literal"),[t.arrayExpression(strings),t.arrayExpression(raw)]));args=args.concat(quasi.expressions);return t.callExpression(node.tag,args)};exports.TemplateLiteral=function(node){var nodes=[];_.each(node.quasis,function(elem){nodes.push(t.literal(elem.value.raw));var expr=node.expressions.shift();if(expr){if(t.isBinary(expr))expr=t.parenthesizedExpression(expr);nodes.push(expr)}});if(nodes.length>1){var last=_.last(nodes);if(t.isLiteral(last,{value:""}))nodes.pop();var root=buildBinaryExpression(nodes.shift(),nodes.shift());_.each(nodes,function(node){root=buildBinaryExpression(root,node)});return root}else{return nodes[0]}}},{"../../types":76,lodash:109}],62:[function(require,module,exports){var rewritePattern=require("regexpu/rewrite-pattern");var _=require("lodash");exports.Literal=function(node){var regex=node.regex;if(!regex)return;var flags=regex.flags.split("");if(!_.contains(regex.flags,"u"))return;_.pull(flags,"u");regex.pattern=rewritePattern(regex.pattern,regex.flags);regex.flags=flags.join("")}},{lodash:109,"regexpu/rewrite-pattern":116}],63:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var container=function(parent,call,ret){if(t.isExpressionStatement(parent)){return call}else{var exprs=[];if(t.isSequenceExpression(call)){exprs=call.expressions}else{exprs.push(call)}exprs.push(ret);return t.sequenceExpression(exprs)}};exports.AssignmentExpression=function(node,parent,file,scope){var left=node.left;if(!t.isVirtualPropertyExpression(left))return;var value=node.right;var temp;if(!t.isExpressionStatement(parent)){if(t.isDynamic(value)){var tempName=file.generateUid("temp");temp=value=t.identifier(tempName);scope.push({key:tempName,id:temp})}}var call=util.template("abstract-expression-set",{PROPERTY:left.property,OBJECT:left.object,VALUE:value});if(temp){call=t.sequenceExpression([t.assignmentExpression("=",temp,node.right),call])}return container(parent,call,value)};exports.UnaryExpression=function(node,parent){var arg=node.argument;if(!t.isVirtualPropertyExpression(arg))return;if(node.operator!=="delete")return;var call=util.template("abstract-expression-delete",{PROPERTY:arg.property,OBJECT:arg.object});return container(parent,call,t.literal(true))};exports.CallExpression=function(node,parent,file,scope){var callee=node.callee;if(!t.isVirtualPropertyExpression(callee))return;var temp;if(t.isDynamic(callee.object)){var tempName=file.generateUid("temp");temp=t.identifier(tempName);scope.push({key:tempName,id:temp})}var call=util.template("abstract-expression-call",{PROPERTY:callee.property,OBJECT:temp||callee.object});call.arguments=call.arguments.concat(node.arguments);if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,callee.object),call])}else{return call}};exports.VirtualPropertyExpression=function(node){return util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object})}},{"../../types":76,"../../util":78}],64:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var _=require("lodash");var single=function(node,file){var block=node.blocks[0];var templateName="array-expression-comprehension-map";if(node.filter)templateName="array-expression-comprehension-filter";var result=util.template(templateName,{STATEMENT:node.body,FILTER:node.filter,ARRAY:file.toArray(block.right),KEY:block.left});_.each([result.callee.object,result],function(call){if(t.isCallExpression(call)){call.arguments[0]._aliasFunction=true}});return result};var multiple=function(node,file){var uid=file.generateUidIdentifier("arr");var container=util.template("array-comprehension-container",{KEY:uid});container.callee.expression._aliasFunction=true;var block=container.callee.expression.body;var body=block.body;var returnStatement=body.pop();body.push(exports._build(node,function(){return util.template("array-push",{STATEMENT:node.body,KEY:uid},true)}));body.push(returnStatement);return container};exports._build=function(node,buildBody){var self=node.blocks.shift();if(!self)return;var child=exports._build(node,buildBody);if(!child){child=buildBody();if(node.filter){child=t.ifStatement(node.filter,t.blockStatement([child]))}}return t.forOfStatement(t.variableDeclaration("var",[t.variableDeclarator(self.left)]),self.right,t.blockStatement([child]))};exports.ComprehensionExpression=function(node,parent,file){if(node.generator)return;if(node.blocks.length===1){return single(node,file)}else{return multiple(node,file)}}},{"../../types":76,"../../util":78,lodash:109}],65:[function(require,module,exports){var t=require("../../types");var pow=t.memberExpression(t.identifier("Math"),t.identifier("pow"));exports.AssignmentExpression=function(node){if(node.operator!=="**=")return;node.operator="=";node.right=t.callExpression(pow,[node.left,node.right])};exports.BinaryExpression=function(node){if(node.operator!=="**")return;return t.callExpression(pow,[node.left,node.right])}},{"../../types":76}],66:[function(require,module,exports){var arrayComprehension=require("./es7-array-comprehension");var t=require("../../types");exports.ComprehensionExpression=function(node){if(!node.generator)return;var body=[];var container=t.functionExpression(null,[],t.blockStatement(body),true);body.push(arrayComprehension._build(node,function(){return t.expressionStatement(t.yieldExpression(node.body))}));return t.callExpression(container,[])}},{"../../types":76,"./es7-array-comprehension":64}],67:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.ObjectExpression=function(node){var hasSpread=false;_.each(node.properties,function(prop){if(t.isSpreadProperty(prop)){hasSpread=true;return false}});if(!hasSpread)return;var args=[];var props=[];var push=function(){if(!props.length)return;args.push(t.objectExpression(props));props=[]};_.each(node.properties,function(prop){if(t.isSpreadProperty(prop)){push();args.push(prop.argument)}else{props.push(prop)}});push();if(!t.isObjectExpression(args[0])){args.unshift(t.objectExpression([]))}return t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("assign")),args)}},{"../../types":76,lodash:109}],68:[function(require,module,exports){var t=require("../../types");var isMemo=function(node){var is=t.isAssignmentExpression(node)&&node.operator==="?=";if(is)t.assertMemberExpression(node.left);return is};var getPropRef=function(nodes,prop,file,scope){if(t.isIdentifier(prop)){return t.literal(prop.name)}else{var temp=file.generateUidIdentifier("propKey",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,prop)]));return temp}};var getObjRef=function(nodes,obj,file,scope){if(t.isDynamic(obj)){var temp=file.generateUidIdentifier("obj",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,obj)]));return temp}else{return obj}};var buildHasOwn=function(obj,prop,file){return t.unaryExpression("!",t.callExpression(t.memberExpression(file.addDeclaration("has-own"),t.identifier("call")),[obj,prop]),true)};var buildAbsoluteRef=function(left,obj,prop){var computed=left.computed||t.isLiteral(prop);return t.memberExpression(obj,prop,computed)};var buildAssignment=function(expr,obj,prop){return t.assignmentExpression("=",buildAbsoluteRef(expr.left,obj,prop),expr.right)};exports.ExpressionStatement=function(node,parent,file,scope){var expr=node.expression;if(!isMemo(expr))return;var nodes=[];var left=expr.left;var obj=getObjRef(nodes,left.object,file,scope);var prop=getPropRef(nodes,left.property,file,scope);nodes.push(t.ifStatement(buildHasOwn(obj,prop,file),t.expressionStatement(buildAssignment(expr,obj,prop))));return nodes};exports.AssignmentExpression=function(node,parent,file,scope){if(t.isExpressionStatement(parent))return;if(!isMemo(node))return;var nodes=[];var left=node.left;var obj=getObjRef(nodes,left.object,file,scope);var prop=getPropRef(nodes,left.property,file,scope);nodes.push(t.logicalExpression("&&",buildHasOwn(obj,prop,file),buildAssignment(node,obj,prop)));nodes.push(buildAbsoluteRef(left,obj,prop));return t.toSequenceExpression(nodes,scope)}},{"../../types":76}],69:[function(require,module,exports){var t=require("../../types");exports.BindMemberExpression=function(node,parent,file,scope){var object=node.object;var prop=node.property;var temp;if(t.isDynamic(object)){var tempName=file.generateUid("temp",scope);temp=object=t.identifier(tempName);scope.push({key:tempName,id:temp})}var call=t.callExpression(t.memberExpression(t.memberExpression(object,prop),t.identifier("bind")),[object].concat(node.arguments));if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,node.object),call])}else{return call}}},{"../../types":76}],70:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");var _=require("lodash");exports.XJSIdentifier=function(node){if(esutils.keyword.isIdentifierName(node.name)){node.type="Identifier"}else{return t.literal(node.name)}};exports.XJSNamespacedName=function(node,parent,file){throw file.errorWithNode(node,"Namespace tags are not supported. ReactJSX is not XML.")};exports.XJSMemberExpression={exit:function(node){node.computed=t.isLiteral(node.property);node.type="MemberExpression"}};exports.XJSExpressionContainer=function(node){return node.expression};exports.XJSAttribute={exit:function(node){var value=node.value||t.literal(true);return t.property("init",node.name,value)}};exports.XJSOpeningElement={exit:function(node){var tagExpr=node.name;var args=[];var tagName;if(t.isIdentifier(tagExpr)){tagName=tagExpr.name}else if(t.isLiteral(tagExpr)){tagName=tagExpr.value}if(tagName&&(/[a-z]/.exec(tagName[0])||_.contains(tagName,"-"))){args.push(t.literal(tagName))}else{args.push(tagExpr)}var props=node.attributes;if(props.length){var _props=[];var objs=[];var pushProps=function(){if(!_props.length)return;objs.push(t.objectExpression(_props));_props=[]};while(props.length){var prop=props.shift();if(t.isXJSSpreadAttribute(prop)){pushProps();objs.push(prop.argument)}else{_props.push(prop)}}pushProps();if(objs.length===1){props=objs[0]}else{if(!t.isObjectExpression(objs[0])){objs.unshift(t.objectExpression([]))}props=t.callExpression(t.memberExpression(t.identifier("React"),t.identifier("__spread")),objs)}}else{props=t.literal(null)}args.push(props);tagExpr=t.memberExpression(t.identifier("React"),t.identifier("createElement"));return t.callExpression(tagExpr,args)}};exports.XJSElement={exit:function(node){var callExpr=node.openingElement;_.each(node.children,function(child){if(t.isLiteral(child)){var lines=child.value.split(/\r\n|\n|\r/);_.each(lines,function(line,i){var isFirstLine=i===0;var isLastLine=i===lines.length-1;var trimmedLine=line.replace(/\t/g," ");if(!isFirstLine){trimmedLine=trimmedLine.replace(/^[ ]+/,"")}if(!isLastLine){trimmedLine=trimmedLine.replace(/[ ]+$/,"")}if(trimmedLine){callExpr.arguments.push(t.literal(trimmedLine))}});return}else if(t.isXJSEmptyExpression(child)){return}callExpr.arguments.push(child)});return t.inherits(callExpr,node)}};var addDisplayName=function(id,call){if(!call||!t.isCallExpression(call))return;var callee=call.callee;if(!t.isMemberExpression(callee))return;var obj=callee.object;if(!t.isIdentifier(obj,{name:"React"}))return;var prop=callee.property;if(!t.isIdentifier(prop,{name:"createClass"}))return;var args=call.arguments;if(args.length!==1)return;var first=args[0];if(!t.isObjectExpression(first))return;var props=first.properties;var safe=true;_.each(props,function(prop){if(t.isIdentifier(prop.key,{name:"displayName"})){return safe=false}});if(safe){props.unshift(t.property("init",t.identifier("displayName"),t.literal(id)))}};exports.AssignmentExpression=exports.Property=exports.VariableDeclarator=function(node){var left,right;if(t.isAssignmentExpression(node)){left=node.left;right=node.right}else if(t.isProperty(node)){left=node.key;right=node.value}else if(t.isVariableDeclarator(node)){left=node.id;right=node.init}if(t.isMemberExpression(left)){left=left.property}if(t.isIdentifier(left)){addDisplayName(left.name,right)}}},{"../../types":76,esutils:108,lodash:109}],71:[function(require,module,exports){var t=require("../../types");module.exports=function(ast){var body=ast.program.body;var first=body[0];var noStrict=!first||!t.isExpressionStatement(first)||!t.isLiteral(first.expression)||first.expression.value!=="use strict";if(noStrict){body.unshift(t.expressionStatement(t.literal("use strict")))}}},{"../../types":76}],72:[function(require,module,exports){module.exports=traverse;var Scope=require("./scope");var t=require("../types");var _=require("lodash");function traverse(parent,callbacks,opts){if(!parent)return;if(_.isArray(parent)){_.each(parent,function(node){traverse(node,callbacks,opts)});return}var keys=t.VISITOR_KEYS[parent.type];if(!keys)return;opts=opts||{};if(_.isArray(opts))opts={blacklist:opts};var blacklistTypes=opts.blacklist||[];if(_.isFunction(callbacks))callbacks={enter:callbacks};for(var i in keys){var key=keys[i];var nodes=parent[key];if(!nodes)continue;var updated=false;var handle=function(obj,key){var node=obj[key];if(!node)return;if(blacklistTypes.indexOf(node.type)>-1)return;var maybeReplace=function(result){if(result===false)return;if(result!=null){updated=true;node=obj[key]=result}};var opts2={scope:opts.scope,blacklist:opts.blacklist};if(t.isScope(node))opts2.scope=new Scope(node,opts.scope);if(callbacks.enter){var result=callbacks.enter(node,parent,opts2.scope);maybeReplace(result);if(result===false)return}traverse(node,callbacks,opts2);if(callbacks.exit){maybeReplace(callbacks.exit(node,parent,opts2.scope))}};if(_.isArray(nodes)){for(i in nodes){handle(nodes,i)}if(updated)parent[key]=_.flatten(parent[key])}else{handle(parent,key)}}}traverse.removeProperties=function(tree){var clear=function(node){delete node._scopeReferences;delete node._declarations;delete node.extendedRange;delete node._parent;delete node._scope;delete node.tokens;delete node.range;delete node.start;delete node.end;delete node.loc;delete node.raw;clearComments(node.trailingComments);clearComments(node.leadingComments)};var clearComments=function(comments){_.each(comments,clear)};clear(tree);traverse(tree,clear);return tree};traverse.hasType=function(tree,type,blacklistTypes){blacklistTypes=[].concat(blacklistTypes||[]);var has=false;if(_.contains(blacklistTypes,tree.type))return false;if(tree.type===type)return true;traverse(tree,function(node){if(node.type===type){has=true;return false}},{blacklist:blacklistTypes});return has}},{"../types":76,"./scope":73,lodash:109}],73:[function(require,module,exports){module.exports=Scope;var traverse=require("./index");var t=require("../types");var _=require("lodash");var FOR_KEYS=["left","init"];function Scope(block,parent){this.parent=parent;this.block=block;this.references=this.getReferences()}Scope.add=function(node,references){if(!node)return;_.merge(references,t.getIds(node,true))};Scope.prototype.getReferences=function(){var block=this.block;if(block._scopeReferences)return block._scopeReferences;var references=block._scopeReferences={};var add=function(node){Scope.add(node,references)};if(t.isFor(block)){_.each(FOR_KEYS,function(key){var node=block[key];if(t.isLet(node))add(node)});block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){_.each(block.body,function(node){if(t.isLet(node))add(node)})}if(t.isCatchClause(block)){add(block.param)}if(t.isProgram(block)||t.isFunction(block)){traverse(block,function(node,parent,scope){if(t.isFor(node)){_.each(FOR_KEYS,function(key){var declar=node[key];if(t.isVar(declar))add(declar)})}if(t.isFunction(node))return false;if(t.isIdentifier(node)&&t.isReferenced(node,parent)&&!scope.has(node.name)){add(node)}if(t.isDeclaration(node)&&!t.isLet(node)){add(node)}},{scope:this})}if(t.isFunction(block)){add(block.rest);_.each(block.params,function(param){add(param)})}return references};Scope.prototype.push=function(opts){var block=this.block;if(t.isFor(block)||t.isCatchClause(block)||t.isFunction(block)){t.ensureBlock(block);block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){block._declarations=block._declarations||{};block._declarations[opts.key]={kind:opts.kind,id:opts.id,init:opts.init}}else{throw new TypeError("cannot add a declaration here in node type "+block.type)}};Scope.prototype.add=function(node){Scope.add(node,this.references)};Scope.prototype.get=function(id){return id&&(this.getOwn(id)||this.parentGet(id))};Scope.prototype.getOwn=function(id){return _.has(this.references,id)&&this.references[id]};Scope.prototype.parentGet=function(id){return this.parent&&this.parent.get(id)};Scope.prototype.has=function(id){return id&&(this.hasOwn(id)||this.parentHas(id))};Scope.prototype.hasOwn=function(id){return!!this.getOwn(id)};Scope.prototype.parentHas=function(id){return this.parent&&this.parent.has(id)}},{"../types":76,"./index":72,lodash:109}],74:[function(require,module,exports){module.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scope","Function"],FunctionDeclaration:["Statement","Declaration","Scope","Function"],FunctionExpression:["Scope","Function"],BlockStatement:["Statement","Scope"],Program:["Scope"],CatchClause:["Scope"],LogicalExpression:["Binary"],BinaryExpression:["Binary"],UnaryExpression:["UnaryLike"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class"],ForOfStatement:["Statement","For","Scope"],ForInStatement:["Statement","For","Scope"],ForStatement:["Statement","For","Scope"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],Property:["UserWhitespacable"],XJSElement:["UserWhitespacable"]}},{}],75:[function(require,module,exports){module.exports={ArrayExpression:["elements"],AssignmentExpression:["operator","left","right"],BinaryExpression:["operator","left","right"],BlockStatement:["body"],CallExpression:["callee","arguments"],ConditionalExpression:["test","consequent","alternate"],ExpressionStatement:["expression"],File:["program","comments","tokens"],FunctionExpression:["id","params","body","generator"],Identifier:["name"],IfStatement:["test","consequent","alternate"],Literal:["value"],LogicalExpression:["operator","left","right"],MemberExpression:["object","property","computed"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ParenthesizedExpression:["expression"],Program:["body"],Property:["kind","key","value","computed"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ThrowExpression:["argument"],UnaryExpression:["operator","argument","prefix"],VariableDeclaration:["kind","declarations"],VariableDeclarator:["id","init"],YieldExpression:["argument","delegate"]}},{}],76:[function(require,module,exports){var esutils=require("esutils"); var _=require("lodash");var t=exports;var addAssert=function(type,is){t["assert"+type]=function(node,opts){opts=opts||{};if(!is(node,opts)){throw new Error("Expected type "+JSON.stringify(type)+" with option "+JSON.stringify(opts))}}};t.VISITOR_KEYS=require("./visitor-keys");_.each(t.VISITOR_KEYS,function(keys,type){var is=t["is"+type]=function(node,opts){return node&&node.type===type&&t.shallowEqual(node,opts)};addAssert(type,is)});t.BUILDER_KEYS=_.defaults(require("./builder-keys"),t.VISITOR_KEYS);_.each(t.BUILDER_KEYS,function(keys,type){t[type[0].toLowerCase()+type.slice(1)]=function(){var args=arguments;var node={type:type};_.each(keys,function(key,i){node[key]=args[i]});return node}});t.ALIAS_KEYS=require("./alias-keys");var _aliases={};_.each(t.ALIAS_KEYS,function(aliases,type){_.each(aliases,function(alias){var types=_aliases[alias]=_aliases[alias]||[];types.push(type)})});_.each(_aliases,function(types,type){t[type.toUpperCase()+"_TYPES"]=types;var is=t["is"+type]=function(node,opts){return node&&_.contains(types,node.type)&&t.shallowEqual(node,opts)};addAssert(type,is)});t.isExpression=function(node){return!t.isStatement(node)};addAssert("Expression",t.isExpression);t.toSequenceExpression=function(nodes,scope){var exprs=[];_.each(nodes,function(node){if(t.isExpression(node)){exprs.push(node)}if(t.isExpressionStatement(node)){exprs.push(node.expression)}else if(t.isVariableDeclaration(node)){_.each(node.declarations,function(declar){scope.push({kind:node.kind,key:declar.id.name,id:declar.id});exprs.push(t.assignmentExpression("=",declar.id,declar.init))})}});return t.sequenceExpression(exprs)};t.shallowEqual=function(actual,expected){var same=true;if(expected){_.each(expected,function(val,key){if(actual[key]!==val){return same=false}})}return same};t.isDynamic=function(node){if(t.isParenthesizedExpression(node)){return t.isDynamic(node.expression)}else if(t.isIdentifier(node)||t.isLiteral(node)||t.isThisExpression(node)){return false}else if(t.isMemberExpression(node)){return t.isDynamic(node.object)||t.isDynamic(node.property)}else{return true}};t.isReferenced=function(node,parent){if(t.isProperty(parent)&&parent.key===node)return false;if(t.isVariableDeclarator(parent)&&parent.id===node)return false;var isMemberExpression=t.isMemberExpression(parent);var isComputedProperty=isMemberExpression&&parent.property===node&&parent.computed;var isObject=isMemberExpression&&parent.object===node;if(!isMemberExpression||isComputedProperty||isObject)return true;return false};t.toIdentifier=function(name){if(t.isIdentifier(name))return name.name;name=name.replace(/[^a-zA-Z0-9]/g,"-");name=name.replace(/^[-0-9]+/,"");name=name.replace(/[-_\s]+(.)?/g,function(match,c){return c?c.toUpperCase():""});return name};t.isValidIdentifier=function(name){return _.isString(name)&&esutils.keyword.isIdentifierName(name)&&!esutils.keyword.isKeywordES6(name,true)};t.ensureBlock=function(node){node.body=t.toBlock(node.body,node)};t.toStatement=function(node,ignore){if(t.isStatement(node)){return node}var mustHaveId=false;var newType;if(t.isClass(node)){mustHaveId=true;newType="ClassDeclaration"}else if(t.isFunction(node)){mustHaveId=true;newType="FunctionDeclaration"}if(mustHaveId&&!node.id){newType=false}if(!newType){if(ignore){return false}else{throw new Error("cannot turn "+node.type+" to a statement")}}node.type=newType;return node};t.toBlock=function(node,parent){if(t.isBlockStatement(node)){return node}if(!_.isArray(node)){if(!t.isStatement(node)){if(t.isFunction(parent)){node=t.returnStatement(node)}else{node=t.expressionStatement(node)}}node=[node]}return t.blockStatement(node)};t.getIds=function(node,map,ignoreTypes){ignoreTypes=ignoreTypes||[];var search=[].concat(node);var ids={};while(search.length){var id=search.shift();if(!id)continue;if(_.contains(ignoreTypes,id.type))continue;var nodeKey=t.getIds.nodes[id.type];var arrKey=t.getIds.arrays[id.type];if(t.isIdentifier(id)){ids[id.name]=id}else if(nodeKey){if(id[nodeKey])search.push(id[nodeKey])}else if(arrKey){search=search.concat(id[arrKey]||[])}}if(!map)ids=_.keys(ids);return ids};t.getIds.nodes={AssignmentExpression:"left",ImportSpecifier:"id",ExportSpecifier:"id",VariableDeclarator:"id",FunctionDeclaration:"id",ClassDeclaration:"id",ParenthesizedExpression:"expression",MemeberExpression:"object",SpreadElement:"argument",Property:"value"};t.getIds.arrays={ExportDeclaration:"specifiers",ImportDeclaration:"specifiers",VariableDeclaration:"declarations",ArrayPattern:"elements",ObjectPattern:"properties"};t.isLet=function(node){return t.isVariableDeclaration(node)&&(node.kind!=="var"||node._let)};t.isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!node._let};t.removeComments=function(child){delete child.leadingComments;delete child.trailingComments;return child};t.inheritsComments=function(child,parent){child.leadingComments=_.compact([].concat(child.leadingComments,parent.leadingComments));child.trailingComments=_.compact([].concat(child.trailingComments,parent.trailingComments));return child};t.removeComments=function(node){delete node.leadingComments;delete node.trailingComments};t.inherits=function(child,parent){child.loc=parent.loc;child.end=parent.end;child.range=parent.range;child.start=parent.start;t.inheritsComments(child,parent);return child};t.getSpecifierName=function(specifier){return specifier.name||specifier.id}},{"./alias-keys":74,"./builder-keys":75,"./visitor-keys":77,esutils:108,lodash:109}],77:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BindMemberExpression:["object","property","arguments"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportBatchSpecifier:["id"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],ParenthesizedExpression:["expression"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SpreadProperty:["argument"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],VirtualPropertyExpression:["object","property"],WhileStatement:["test","body"],WithStatement:["object","body"],XJSAttribute:["name","value"],XJSClosingElement:["name"],XJSElement:["openingElement","closingElement","children"],XJSEmptyExpression:[],XJSExpressionContainer:["expression"],XJSIdentifier:[],XJSMemberExpression:["object","property"],XJSNamespacedName:["namespace","name"],XJSOpeningElement:["name","attributes"],XJSSpreadAttribute:["argument"],YieldExpression:["argument"]}},{}],78:[function(require,module,exports){(function(Buffer,__dirname){require("./patch");var estraverse=require("estraverse");var traverse=require("./traverse");var acorn=require("acorn-6to5");var path=require("path");var util=require("util");var fs=require("fs");var t=require("./types");var _=require("lodash");exports.inherits=util.inherits;exports.canCompile=function(filename,altExts){var exts=altExts||[".js",".jsx",".es6"];var ext=path.extname(filename);return _.contains(exts,ext)};exports.isInteger=function(i){return _.isNumber(i)&&i%1===0};exports.resolve=function(loc){try{return require.resolve(loc)}catch(err){return null}};exports.trimRight=function(str){return str.replace(/[\n\s]+$/g,"")};exports.list=function(val){return val?val.split(","):[]};exports.regexify=function(val){if(!val)return new RegExp(/.^/);if(_.isArray(val))val=val.join("|");if(_.isString(val))return new RegExp(val);if(_.isRegExp(val))return val;throw new TypeError("illegal type for regexify")};exports.arrayify=function(val){if(!val)return[];if(_.isString(val))return exports.list(val);if(_.isArray(val))return val;throw new TypeError("illegal type for arrayify")};exports.getUid=function(parent,file){var node;if(t.isAssignmentExpression(parent)){node=parent.left}else if(t.isVariableDeclarator(parent)){node=parent.id}var id="ref";if(t.isIdentifier(node))id=node.name;return file.generateUidIdentifier(id)};exports.isAbsolute=function(loc){if(!loc)return false;if(loc[0]==="/")return true;if(loc[1]===":"&&loc[2]==="\\")return true;return false};exports.sourceMapToComment=function(map){var json=JSON.stringify(map);var base64=new Buffer(json).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+base64};exports.pushMutatorMap=function(mutatorMap,key,kind,method){var alias;if(t.isIdentifier(key)){alias=key.name;if(method.computed)alias="computed:"+alias}else if(t.isLiteral(key)){alias=String(key.value)}else{alias=JSON.stringify(traverse.removeProperties(_.cloneDeep(key)))}var map;if(_.has(mutatorMap,alias)){map=mutatorMap[alias]}else{map={}}mutatorMap[alias]=map;map._key=key;if(method.computed){map._computed=true}map[kind]=method};exports.buildDefineProperties=function(mutatorMap){var objExpr=t.objectExpression([]);_.each(mutatorMap,function(map){var mapNode=t.objectExpression([]);var propNode=t.property("init",map._key,mapNode,map._computed);_.each(map,function(node,key){if(key[0]==="_")return;node=_.clone(node);var inheritNode=node;if(t.isMethodDefinition(node))node=node.value;var prop=t.property("init",t.identifier(key),node);t.inheritsComments(prop,inheritNode);t.removeComments(inheritNode);mapNode.properties.push(prop)});objExpr.properties.push(propNode)});return objExpr};exports.template=function(name,nodes,keepExpression){var template=exports.templates[name];if(!template)throw new ReferenceError("unknown template "+name);if(nodes===true){keepExpression=true;nodes=null}template=_.cloneDeep(template);if(!_.isEmpty(nodes)){traverse(template,function(node){if(t.isIdentifier(node)&&_.has(nodes,node.name)){var newNode=nodes[node.name];if(_.isString(newNode)){node.name=newNode}else{return newNode}}})}var node=template.body[0];if(!keepExpression&&t.isExpressionStatement(node)){node=node.expression;if(t.isParenthesizedExpression(node))node=node.expression}return node};exports.codeFrame=function(lines,lineNumber,colNumber){colNumber=Math.max(colNumber,0);lines=lines.split("\n");var start=Math.max(lineNumber-3,0);var end=Math.min(lines.length,lineNumber+3);var width=(end+"").length;if(!lineNumber&&!colNumber){start=0;end=lines.length}return"\n"+lines.slice(start,end).map(function(line,i){var curr=i+start+1;var gutter=curr===lineNumber?"> ":" ";var sep=curr+exports.repeat(width+1);gutter+=sep+"| ";var str=gutter+line;if(colNumber&&curr===lineNumber){str+="\n";str+=exports.repeat(gutter.length-2);str+="|"+exports.repeat(colNumber)+"^"}return str}).join("\n")};exports.repeat=function(width,cha){cha=cha||" ";return new Array(width+1).join(cha)};exports.parse=function(opts,code,callback){try{var comments=[];var tokens=[];var ast=acorn.parse(code,{allowReturnOutsideFunction:true,preserveParens:true,ecmaVersion:opts.experimental?7:6,playground:opts.playground,strictMode:true,onComment:comments,locations:true,onToken:tokens,ranges:true});estraverse.attachComments(ast,comments,tokens);ast=t.file(ast,comments,tokens);traverse(ast,function(node,parent){node._parent=parent});if(callback){return callback(ast)}else{return ast}}catch(err){if(!err._6to5){err._6to5=true;var message=opts.filename+": "+err.message;var loc=err.loc;if(loc){var frame=exports.codeFrame(code,loc.line,loc.column);message+=frame}if(err.stack)err.stack=err.stack.replace(err.message,message);err.message=message}throw err}};exports.parseTemplate=function(loc,code){var ast=exports.parse({filename:loc},code).program;return traverse.removeProperties(ast)};var loadTemplates=function(){var templates={};var templatesLoc=__dirname+"/templates";if(!fs.existsSync(templatesLoc)){throw new Error("no templates directory - this is most likely the "+"result of a broken `npm publish`. Please report to "+"https://githut.com/6to5/6to5/issues")}_.each(fs.readdirSync(templatesLoc),function(name){if(name[0]===".")return;var key=path.basename(name,path.extname(name));var loc=templatesLoc+"/"+name;var code=fs.readFileSync(loc,"utf8");templates[key]=exports.parseTemplate(loc,code)});return templates};try{exports.templates=require("../../templates.json")}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err;exports.templates=loadTemplates()}}).call(this,require("buffer").Buffer,"/lib/6to5")},{"../../templates.json":127,"./patch":23,"./traverse":72,"./types":76,"acorn-6to5":1,buffer:95,estraverse:104,fs:93,lodash:109,path:100,util:103}],79:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var def=Type.def;var or=Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isNumber=builtin.number;var isBoolean=builtin.boolean;var isRegExp=builtin.RegExp;var shared=require("../lib/shared");var defaults=shared.defaults;var geq=shared.geq;def("Node").field("type",isString).field("loc",or(def("SourceLocation"),null),defaults["null"],true);def("SourceLocation").build("start","end","source").field("start",def("Position")).field("end",def("Position")).field("source",or(isString,null),defaults["null"]);def("Position").build("line","column").field("line",geq(1)).field("column",geq(0));def("Program").bases("Node").build("body").field("body",[def("Statement")]);def("Function").bases("Node").field("id",or(def("Identifier"),null),defaults["null"]).field("params",[def("Pattern")]).field("body",or(def("BlockStatement"),def("Expression")));def("Statement").bases("Node");def("EmptyStatement").bases("Statement").build();def("BlockStatement").bases("Statement").build("body").field("body",[def("Statement")]);def("ExpressionStatement").bases("Statement").build("expression").field("expression",def("Expression"));def("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Statement")).field("alternate",or(def("Statement"),null),defaults["null"]);def("LabeledStatement").bases("Statement").build("label","body").field("label",def("Identifier")).field("body",def("Statement"));def("BreakStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("ContinueStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("WithStatement").bases("Statement").build("object","body").field("object",def("Expression")).field("body",def("Statement"));def("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",def("Expression")).field("cases",[def("SwitchCase")]).field("lexical",isBoolean,defaults["false"]);def("ReturnStatement").bases("Statement").build("argument").field("argument",or(def("Expression"),null));def("ThrowStatement").bases("Statement").build("argument").field("argument",def("Expression"));def("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",def("BlockStatement")).field("handler",or(def("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[def("CatchClause")],function(){return this.handler?[this.handler]:[]},true).field("guardedHandlers",[def("CatchClause")],defaults.emptyArray).field("finalizer",or(def("BlockStatement"),null),defaults["null"]);def("CatchClause").bases("Node").build("param","guard","body").field("param",def("Pattern")).field("guard",or(def("Expression"),null),defaults["null"]).field("body",def("BlockStatement"));def("WhileStatement").bases("Statement").build("test","body").field("test",def("Expression")).field("body",def("Statement"));def("DoWhileStatement").bases("Statement").build("body","test").field("body",def("Statement")).field("test",def("Expression"));def("ForStatement").bases("Statement").build("init","test","update","body").field("init",or(def("VariableDeclaration"),def("Expression"),null)).field("test",or(def("Expression"),null)).field("update",or(def("Expression"),null)).field("body",def("Statement"));def("ForInStatement").bases("Statement").build("left","right","body","each").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement")).field("each",isBoolean);def("DebuggerStatement").bases("Statement").build();def("Declaration").bases("Statement");def("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",def("Identifier"));def("FunctionExpression").bases("Function","Expression").build("id","params","body");def("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",or("var","let","const")).field("declarations",[or(def("VariableDeclarator"),def("Identifier"))]);def("VariableDeclarator").bases("Node").build("id","init").field("id",def("Pattern")).field("init",or(def("Expression"),null));def("Expression").bases("Node","Pattern");def("ThisExpression").bases("Expression").build();def("ArrayExpression").bases("Expression").build("elements").field("elements",[or(def("Expression"),null)]);def("ObjectExpression").bases("Expression").build("properties").field("properties",[def("Property")]);def("Property").bases("Node").build("kind","key","value").field("kind",or("init","get","set")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Expression"));def("SequenceExpression").bases("Expression").build("expressions").field("expressions",[def("Expression")]);var UnaryOperator=or("-","+","!","~","typeof","void","delete");def("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",UnaryOperator).field("argument",def("Expression")).field("prefix",isBoolean,defaults["true"]);var BinaryOperator=or("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");def("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",BinaryOperator).field("left",def("Expression")).field("right",def("Expression"));var AssignmentOperator=or("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");def("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",AssignmentOperator).field("left",def("Pattern")).field("right",def("Expression"));var UpdateOperator=or("++","--");def("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",UpdateOperator).field("argument",def("Expression")).field("prefix",isBoolean);var LogicalOperator=or("||","&&");def("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",LogicalOperator).field("left",def("Expression")).field("right",def("Expression"));def("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Expression")).field("alternate",def("Expression"));def("NewExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("CallExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("MemberExpression").bases("Expression").build("object","property","computed").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("Pattern").bases("Node");def("ObjectPattern").bases("Pattern").build("properties").field("properties",[def("PropertyPattern")]);def("PropertyPattern").bases("Pattern").build("key","pattern").field("key",or(def("Literal"),def("Identifier"))).field("pattern",def("Pattern"));def("ArrayPattern").bases("Pattern").build("elements").field("elements",[or(def("Pattern"),null)]);def("SwitchCase").bases("Node").build("test","consequent").field("test",or(def("Expression"),null)).field("consequent",[def("Statement")]);def("Identifier").bases("Node","Expression","Pattern").build("name").field("name",isString);def("Literal").bases("Node","Expression").build("value").field("value",or(isString,isBoolean,null,isNumber,isRegExp))},{"../lib/shared":90,"../lib/types":91}],80:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;def("XMLDefaultDeclaration").bases("Declaration").field("namespace",def("Expression"));def("XMLAnyName").bases("Expression");def("XMLQualifiedIdentifier").bases("Expression").field("left",or(def("Identifier"),def("XMLAnyName"))).field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLAttributeSelector").bases("Expression").field("attribute",def("Expression"));def("XMLFilterExpression").bases("Expression").field("left",def("Expression")).field("right",def("Expression"));def("XMLElement").bases("XML","Expression").field("contents",[def("XML")]);def("XMLList").bases("XML","Expression").field("contents",[def("XML")]);def("XML").bases("Node");def("XMLEscape").bases("XML").field("expression",def("Expression"));def("XMLText").bases("XML").field("text",isString);def("XMLStartTag").bases("XML").field("contents",[def("XML")]);def("XMLEndTag").bases("XML").field("contents",[def("XML")]);def("XMLPointTag").bases("XML").field("contents",[def("XML")]);def("XMLName").bases("XML").field("contents",or(isString,[def("XML")]));def("XMLAttribute").bases("XML").field("value",isString);def("XMLCdata").bases("XML").field("contents",isString);def("XMLComment").bases("XML").field("contents",isString);def("XMLProcessingInstruction").bases("XML").field("target",isString).field("contents",or(isString,null))},{"../lib/types":91,"./core":79}],81:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var isObject=builtin.object;var isString=builtin.string;var defaults=require("../lib/shared").defaults;def("Function").field("generator",isBoolean,defaults["false"]).field("expression",isBoolean,defaults["false"]).field("defaults",[or(def("Expression"),null)],defaults.emptyArray).field("rest",or(def("Identifier"),null),defaults["null"]);def("FunctionDeclaration").build("id","params","body","generator","expression");def("FunctionExpression").build("id","params","body","generator","expression");def("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,defaults["null"]).field("generator",false);def("YieldExpression").bases("Expression").build("argument","delegate").field("argument",or(def("Expression"),null)).field("delegate",isBoolean,defaults["false"]);def("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionBlock").bases("Node").build("left","right","each").field("left",def("Pattern")).field("right",def("Expression")).field("each",isBoolean);def("ModuleSpecifier").bases("Literal").build("value").field("value",isString);def("Property").field("method",isBoolean,defaults["false"]).field("shorthand",isBoolean,defaults["false"]).field("computed",isBoolean,defaults["false"]);def("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",or("init","get","set","")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Function"));def("SpreadElement").bases("Node").build("argument").field("argument",def("Expression"));def("ArrayExpression").field("elements",[or(def("Expression"),def("SpreadElement"),null)]);def("NewExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("CallExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("SpreadElementPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));var ClassBodyElement=or(def("MethodDefinition"),def("VariableDeclarator"),def("ClassPropertyDefinition"),def("ClassProperty"));def("ClassProperty").bases("Declaration").build("id").field("id",def("Identifier"));def("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",ClassBodyElement);def("ClassBody").bases("Declaration").build("body").field("body",[ClassBodyElement]);def("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",def("Identifier")).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("ClassExpression").bases("Expression").build("id","body","superClass").field("id",or(def("Identifier"),null),defaults["null"]).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("Specifier").bases("Node");def("NamedSpecifier").bases("Specifier").field("id",def("Identifier")).field("name",or(def("Identifier"),null),defaults["null"]);def("ExportSpecifier").bases("NamedSpecifier").build("id","name");def("ExportBatchSpecifier").bases("Specifier").build();def("ImportSpecifier").bases("NamedSpecifier").build("id","name");def("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",isBoolean).field("declaration",or(def("Declaration"),def("Expression"),null)).field("specifiers",[or(def("ExportSpecifier"),def("ExportBatchSpecifier"))],defaults.emptyArray).field("source",or(def("ModuleSpecifier"),null),defaults["null"]);def("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[or(def("ImportSpecifier"),def("ImportNamespaceSpecifier"),def("ImportDefaultSpecifier"))],defaults.emptyArray).field("source",def("ModuleSpecifier"));def("TaggedTemplateExpression").bases("Expression").field("tag",def("Expression")).field("quasi",def("TemplateLiteral"));def("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[def("TemplateElement")]).field("expressions",[def("Expression")]);def("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:isString,raw:isString}).field("tail",isBoolean)},{"../lib/shared":90,"../lib/types":91,"./core":79}],82:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("Function").field("async",isBoolean,defaults["false"]);def("SpreadProperty").bases("Node").build("argument").field("argument",def("Expression"));def("ObjectExpression").field("properties",[or(def("Property"),def("SpreadProperty"))]);def("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));def("ObjectPattern").field("properties",[or(def("PropertyPattern"),def("SpreadPropertyPattern"))]);def("AwaitExpression").bases("Expression").build("argument","all").field("argument",or(def("Expression"),null)).field("all",isBoolean,defaults["false"])},{"../lib/shared":90,"../lib/types":91,"./core":79}],83:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("XJSAttribute").bases("Node").build("name","value").field("name",or(def("XJSIdentifier"),def("XJSNamespacedName"))).field("value",or(def("Literal"),def("XJSExpressionContainer"),null),defaults["null"]);def("XJSIdentifier").bases("Node").build("name").field("name",isString);def("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",def("XJSIdentifier")).field("name",def("XJSIdentifier"));def("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",or(def("XJSIdentifier"),def("XJSMemberExpression"))).field("property",def("XJSIdentifier")).field("computed",isBoolean,defaults.false);var XJSElementName=or(def("XJSIdentifier"),def("XJSNamespacedName"),def("XJSMemberExpression"));def("XJSSpreadAttribute").bases("Node").build("argument").field("argument",def("Expression"));var XJSAttributes=[or(def("XJSAttribute"),def("XJSSpreadAttribute"))];def("XJSExpressionContainer").bases("Expression").build("expression").field("expression",def("Expression"));def("XJSElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",def("XJSOpeningElement")).field("closingElement",or(def("XJSClosingElement"),null),defaults["null"]).field("children",[or(def("XJSElement"),def("XJSExpressionContainer"),def("XJSText"),def("Literal"))],defaults.emptyArray).field("name",XJSElementName,function(){return this.openingElement.name}).field("selfClosing",isBoolean,function(){return this.openingElement.selfClosing}).field("attributes",XJSAttributes,function(){return this.openingElement.attributes});def("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",XJSElementName).field("attributes",XJSAttributes,defaults.emptyArray).field("selfClosing",isBoolean,defaults["false"]);def("XJSClosingElement").bases("Node").build("name").field("name",XJSElementName);def("XJSText").bases("Literal").build("value").field("value",isString);def("XJSEmptyExpression").bases("Expression").build();def("TypeAnnotatedIdentifier").bases("Pattern").build("annotation","identifier").field("annotation",def("TypeAnnotation")).field("identifier",def("Identifier"));def("TypeAnnotation").bases("Pattern").build("annotatedType","templateTypes","paramTypes","returnType","unionType","nullable").field("annotatedType",def("Identifier")).field("templateTypes",or([def("TypeAnnotation")],null)).field("paramTypes",or([def("TypeAnnotation")],null)).field("returnType",or(def("TypeAnnotation"),null)).field("unionType",or(def("TypeAnnotation"),null)).field("nullable",isBoolean);def("ObjectTypeAnnotation").bases("Pattern").build("properties","nullable").field("properties",[def("Property")]).field("nullable",isBoolean); def("VoidTypeAnnotation").bases("Pattern");def("ParametricTypeAnnotation").bases("Pattern").build("params").field("params",[def("Identifier")]);def("OptionalParameter").bases("Pattern").build("identifier").field("identifier",def("Identifier"));def("Identifier").field("annotation",or(def("TypeAnnotation"),def("VoidTypeAnnotation"),def("ObjectTypeAnnotation"),null),defaults["null"]);def("Function").field("returnType",or(def("TypeAnnotation"),def("VoidTypeAnnotation"),def("ObjectTypeAnnotation"),null),defaults["null"]).field("parametricType",or(def("ParametricTypeAnnotation"),null),defaults["null"]);def("ClassProperty").field("id",or(def("Identifier"),def("TypeAnnotatedIdentifier")));def("ClassDeclaration").field("parametricType",or(def("ParametricTypeAnnotation"),null),defaults["null"])},{"../lib/shared":90,"../lib/types":91,"./core":79}],84:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var geq=require("../lib/shared").geq;def("ForOfStatement").bases("Statement").build("left","right","body").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement"));def("LetStatement").bases("Statement").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Statement"));def("LetExpression").bases("Expression").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Expression"));def("GraphExpression").bases("Expression").build("index","expression").field("index",geq(0)).field("expression",def("Literal"));def("GraphIndexExpression").bases("Expression").build("index").field("index",geq(0))},{"../lib/shared":90,"../lib/types":91,"./core":79}],85:[function(require,module,exports){var assert=require("assert");var types=require("../main");var getFieldNames=types.getFieldNames;var getFieldValue=types.getFieldValue;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isDate=types.builtInTypes.Date;var isRegExp=types.builtInTypes.RegExp;var hasOwn=Object.prototype.hasOwnProperty;function astNodesAreEquivalent(a,b,problemPath){if(isArray.check(problemPath)){problemPath.length=0}else{problemPath=null}return areEquivalent(a,b,problemPath)}astNodesAreEquivalent.assert=function(a,b){var problemPath=[];if(!astNodesAreEquivalent(a,b,problemPath)){if(problemPath.length===0){assert.strictEqual(a,b)}else{assert.ok(false,"Nodes differ in the following path: "+problemPath.map(subscriptForProperty).join(""))}}};function subscriptForProperty(property){if(/[_$a-z][_$a-z0-9]*/i.test(property)){return"."+property}return"["+JSON.stringify(property)+"]"}function areEquivalent(a,b,problemPath){if(a===b){return true}if(isArray.check(a)){return arraysAreEquivalent(a,b,problemPath)}if(isObject.check(a)){return objectsAreEquivalent(a,b,problemPath)}if(isDate.check(a)){return isDate.check(b)&&+a===+b}if(isRegExp.check(a)){return isRegExp.check(b)&&(a.source===b.source&&a.global===b.global&&a.multiline===b.multiline&&a.ignoreCase===b.ignoreCase)}return a==b}function arraysAreEquivalent(a,b,problemPath){isArray.assert(a);var aLength=a.length;if(!isArray.check(b)||b.length!==aLength){if(problemPath){problemPath.push("length")}return false}for(var i=0;i<aLength;++i){if(problemPath){problemPath.push(i)}if(i in a!==i in b){return false}if(!areEquivalent(a[i],b[i],problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),i)}}return true}function objectsAreEquivalent(a,b,problemPath){isObject.assert(a);if(!isObject.check(b)){return false}if(a.type!==b.type){if(problemPath){problemPath.push("type")}return false}var aNames=getFieldNames(a);var aNameCount=aNames.length;var bNames=getFieldNames(b);var bNameCount=bNames.length;if(aNameCount===bNameCount){for(var i=0;i<aNameCount;++i){var name=aNames[i];var aChild=getFieldValue(a,name);var bChild=getFieldValue(b,name);if(problemPath){problemPath.push(name)}if(!areEquivalent(aChild,bChild,problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),name)}}return true}if(!problemPath){return false}var seenNames=Object.create(null);for(i=0;i<aNameCount;++i){seenNames[aNames[i]]=true}for(i=0;i<bNameCount;++i){name=bNames[i];if(!hasOwn.call(seenNames,name)){problemPath.push(name);return false}delete seenNames[name]}for(name in seenNames){problemPath.push(name);break}return false}module.exports=astNodesAreEquivalent},{"../main":92,assert:94}],86:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var b=types.builders;var isNumber=types.builtInTypes.number;var isArray=types.builtInTypes.array;var Path=require("./path");var Scope=require("./scope");function NodePath(value,parentPath,name){assert.ok(this instanceof NodePath);Path.call(this,value,parentPath,name)}require("util").inherits(NodePath,Path);var NPp=NodePath.prototype;Object.defineProperties(NPp,{node:{get:function(){Object.defineProperty(this,"node",{configurable:true,value:this._computeNode()});return this.node}},parent:{get:function(){Object.defineProperty(this,"parent",{configurable:true,value:this._computeParent()});return this.parent}},scope:{get:function(){Object.defineProperty(this,"scope",{configurable:true,value:this._computeScope()});return this.scope}}});NPp.replace=function(){delete this.node;delete this.parent;delete this.scope;return Path.prototype.replace.apply(this,arguments)};NPp.prune=function(){var remainingNodePath=this.parent;this.replace();return cleanUpNodesAfterPrune(remainingNodePath)};NPp._computeNode=function(){var value=this.value;if(n.Node.check(value)){return value}var pp=this.parentPath;return pp&&pp.node||null};NPp._computeParent=function(){var value=this.value;var pp=this.parentPath;if(!n.Node.check(value)){while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}if(pp){pp=pp.parentPath}}while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}return pp||null};NPp._computeScope=function(){var value=this.value;var pp=this.parentPath;var scope=pp&&pp.scope;if(n.Node.check(value)&&Scope.isEstablishedBy(value)){scope=new Scope(this,scope)}return scope||null};NPp.getValueProperty=function(name){return types.getFieldValue(this.value,name)};NPp.needsParens=function(assumeExpressionContext){var pp=this.parentPath;if(!pp){return false}var node=this.value;if(!n.Expression.check(node)){return false}if(node.type==="Identifier"){return false}while(!n.Node.check(pp.value)){pp=pp.parentPath;if(!pp){return false}}var parent=pp.value;switch(node.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return parent.type==="MemberExpression"&&this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":switch(parent.type){case"CallExpression":return this.name==="callee"&&parent.callee===node;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return true;case"MemberExpression":return this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":var po=parent.operator;var pp=PRECEDENCE[po];var no=node.operator;var np=PRECEDENCE[no];if(pp>np){return true}if(pp===np&&this.name==="right"){assert.strictEqual(parent.right,node);return true}default:return false}case"SequenceExpression":switch(parent.type){case"ForStatement":return false;case"ExpressionStatement":return this.name!=="expression";default:return true}case"YieldExpression":switch(parent.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return true;default:return false}case"Literal":return parent.type==="MemberExpression"&&isNumber.check(node.value)&&this.name==="object"&&parent.object===node;case"AssignmentExpression":case"ConditionalExpression":switch(parent.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return true;case"CallExpression":return this.name==="callee"&&parent.callee===node;case"ConditionalExpression":return this.name==="test"&&parent.test===node;case"MemberExpression":return this.name==="object"&&parent.object===node;default:return false}default:if(parent.type==="NewExpression"&&this.name==="callee"&&parent.callee===node){return containsCallExpression(node)}}if(assumeExpressionContext!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function isBinary(node){return n.BinaryExpression.check(node)||n.LogicalExpression.check(node)}function isUnaryLike(node){return n.UnaryExpression.check(node)||n.SpreadElement&&n.SpreadElement.check(node)||n.SpreadProperty&&n.SpreadProperty.check(node)}var PRECEDENCE={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(tier,i){tier.forEach(function(op){PRECEDENCE[op]=i})});function containsCallExpression(node){if(n.CallExpression.check(node)){return true}if(isArray.check(node)){return node.some(containsCallExpression)}if(n.Node.check(node)){return types.someField(node,function(name,child){return containsCallExpression(child)})}return false}NPp.canBeFirstInStatement=function(){var node=this.node;return!n.FunctionExpression.check(node)&&!n.ObjectExpression.check(node)};NPp.firstInStatement=function(){return firstInStatement(this)};function firstInStatement(path){for(var node,parent;path.parent;path=path.parent){node=path.node;parent=path.parent.node;if(n.BlockStatement.check(parent)&&path.parent.name==="body"&&path.name===0){assert.strictEqual(parent.body[0],node);return true}if(n.ExpressionStatement.check(parent)&&path.name==="expression"){assert.strictEqual(parent.expression,node);return true}if(n.SequenceExpression.check(parent)&&path.parent.name==="expressions"&&path.name===0){assert.strictEqual(parent.expressions[0],node);continue}if(n.CallExpression.check(parent)&&path.name==="callee"){assert.strictEqual(parent.callee,node);continue}if(n.MemberExpression.check(parent)&&path.name==="object"){assert.strictEqual(parent.object,node);continue}if(n.ConditionalExpression.check(parent)&&path.name==="test"){assert.strictEqual(parent.test,node);continue}if(isBinary(parent)&&path.name==="left"){assert.strictEqual(parent.left,node);continue}if(n.UnaryExpression.check(parent)&&!parent.prefix&&path.name==="argument"){assert.strictEqual(parent.argument,node);continue}return false}return true}function cleanUpNodesAfterPrune(remainingNodePath){if(n.VariableDeclaration.check(remainingNodePath.node)){var declarations=remainingNodePath.get("declarations").value;if(!declarations||declarations.length===0){return remainingNodePath.prune()}}else if(n.ExpressionStatement.check(remainingNodePath.node)){if(!remainingNodePath.get("expression").value){return remainingNodePath.prune()}}else if(n.IfStatement.check(remainingNodePath.node)){cleanUpIfStatementAfterPrune(remainingNodePath)}return remainingNodePath}function cleanUpIfStatementAfterPrune(ifStatement){var testExpression=ifStatement.get("test").value;var alternate=ifStatement.get("alternate").value;var consequent=ifStatement.get("consequent").value;if(!consequent&&!alternate){var testExpressionStatement=b.expressionStatement(testExpression);ifStatement.replace(testExpressionStatement)}else if(!consequent&&alternate){var negatedTestExpression=b.unaryExpression("!",testExpression,true);if(n.UnaryExpression.check(testExpression)&&testExpression.operator==="!"){negatedTestExpression=testExpression.argument}ifStatement.get("test").replace(negatedTestExpression);ifStatement.get("consequent").replace(alternate);ifStatement.get("alternate").replace()}}module.exports=NodePath},{"./path":88,"./scope":89,"./types":91,assert:94,util:103}],87:[function(require,module,exports){var assert=require("assert");var types=require("./types");var NodePath=require("./node-path");var Node=types.namedTypes.Node;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isFunction=types.builtInTypes.function;var hasOwn=Object.prototype.hasOwnProperty;var undefined;function PathVisitor(){assert.ok(this instanceof PathVisitor);this._reusableContextStack=[];this._methodNameTable=computeMethodNameTable(this);this.Context=makeContextConstructor(this)}function computeMethodNameTable(visitor){var typeNames=Object.create(null);for(var methodName in visitor){if(/^visit[A-Z]/.test(methodName)){typeNames[methodName.slice("visit".length)]=true}}var supertypeTable=types.computeSupertypeLookupTable(typeNames);var methodNameTable=Object.create(null);var typeNames=Object.keys(supertypeTable);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];methodName="visit"+supertypeTable[typeName];if(isFunction.check(visitor[methodName])){methodNameTable[typeName]=methodName}}return methodNameTable}PathVisitor.fromMethodsObject=function fromMethodsObject(methods){if(methods instanceof PathVisitor){return methods}if(!isObject.check(methods)){return new PathVisitor}function Visitor(){assert.ok(this instanceof Visitor);PathVisitor.call(this)}var Vp=Visitor.prototype=Object.create(PVp);Vp.constructor=Visitor;extend(Vp,methods);extend(Visitor,PathVisitor);isFunction.assert(Visitor.fromMethodsObject);isFunction.assert(Visitor.visit);return new Visitor};function extend(target,source){for(var property in source){if(hasOwn.call(source,property)){target[property]=source[property]}}return target}PathVisitor.visit=function visit(node,methods){var visitor=PathVisitor.fromMethodsObject(methods);if(node instanceof NodePath){visitor.visit(node);return node.value}var rootPath=new NodePath({root:node});visitor.visit(rootPath.get("root"));return rootPath.value.root};var PVp=PathVisitor.prototype;PVp.visit=function(path){if(this instanceof this.Context){return this.visitor.visit(path)}assert.ok(path instanceof NodePath);var value=path.value;var methodName=Node.check(value)&&this._methodNameTable[value.type];if(methodName){var context=this.acquireContext(path);try{context.invokeVisitorMethod(methodName)}finally{this.releaseContext(context)}}else{visitChildren(path,this)}};function visitChildren(path,visitor){assert.ok(path instanceof NodePath);assert.ok(visitor instanceof PathVisitor);var value=path.value;if(isArray.check(value)){path.each(visitor.visit,visitor)}else if(!isObject.check(value)){}else{var childNames=types.getFieldNames(value);var childCount=childNames.length;var childPaths=[];for(var i=0;i<childCount;++i){var childName=childNames[i];if(!hasOwn.call(value,childName)){value[childName]=types.getFieldValue(value,childName)}childPaths.push(path.get(childName))}for(var i=0;i<childCount;++i){visitor.visit(childPaths[i])}}}PVp.acquireContext=function(path){if(this._reusableContextStack.length===0){return new this.Context(path)}return this._reusableContextStack.pop().reset(path)};PVp.releaseContext=function(context){assert.ok(context instanceof this.Context);this._reusableContextStack.push(context);context.currentPath=null};function makeContextConstructor(visitor){function Context(path){assert.ok(this instanceof Context);assert.ok(this instanceof PathVisitor);assert.ok(path instanceof NodePath);Object.defineProperty(this,"visitor",{value:visitor,writable:false,enumerable:true,configurable:false});this.currentPath=path;this.needToCallTraverse=true;Object.seal(this)}assert.ok(visitor instanceof PathVisitor);var Cp=Context.prototype=Object.create(visitor);Cp.constructor=Context;extend(Cp,sharedContextProtoMethods);return Context}var sharedContextProtoMethods=Object.create(null);sharedContextProtoMethods.reset=function reset(path){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);this.currentPath=path;this.needToCallTraverse=true;return this};sharedContextProtoMethods.invokeVisitorMethod=function invokeVisitorMethod(methodName){assert.ok(this instanceof this.Context);assert.ok(this.currentPath instanceof NodePath);var result=this.visitor[methodName].call(this,this.currentPath);if(result===false){this.needToCallTraverse=false}else if(result!==undefined){this.currentPath=this.currentPath.replace(result)[0];if(this.needToCallTraverse){this.traverse(this.currentPath)}}assert.strictEqual(this.needToCallTraverse,false,"Must either call this.traverse or return false in "+methodName)};sharedContextProtoMethods.traverse=function traverse(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;visitChildren(path,PathVisitor.fromMethodsObject(newVisitor||this.visitor))};module.exports=PathVisitor},{"./node-path":86,"./types":91,assert:94}],88:[function(require,module,exports){var assert=require("assert");var Op=Object.prototype;var hasOwn=Op.hasOwnProperty;var types=require("./types");var isArray=types.builtInTypes.array;var isNumber=types.builtInTypes.number;var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;function Path(value,parentPath,name){assert.ok(this instanceof Path);if(parentPath){assert.ok(parentPath instanceof Path)}else{parentPath=null;name=null}this.value=value;this.parentPath=parentPath;this.name=name;this.__childCache=null}var Pp=Path.prototype;function getChildCache(path){return path.__childCache||(path.__childCache=Object.create(null))}function getChildPath(path,name){var cache=getChildCache(path);var actualChildValue=path.getValueProperty(name);var childPath=cache[name];if(!hasOwn.call(cache,name)||childPath.value!==actualChildValue){childPath=cache[name]=new path.constructor(actualChildValue,path,name)}return childPath}Pp.getValueProperty=function getValueProperty(name){return this.value[name]};Pp.get=function get(name){var path=this;var names=arguments;var count=names.length;for(var i=0;i<count;++i){path=getChildPath(path,names[i])}return path};Pp.each=function each(callback,context){var childPaths=[];var len=this.value.length;var i=0;for(var i=0;i<len;++i){if(hasOwn.call(this.value,i)){childPaths[i]=this.get(i)}}context=context||this;for(i=0;i<len;++i){if(hasOwn.call(childPaths,i)){callback.call(context,childPaths[i])}}};Pp.map=function map(callback,context){var result=[];this.each(function(childPath){result.push(callback.call(this,childPath))},context);return result};Pp.filter=function filter(callback,context){var result=[];this.each(function(childPath){if(callback.call(this,childPath)){result.push(childPath)}},context);return result};function emptyMoves(){}function getMoves(path,offset,start,end){isArray.assert(path.value);if(offset===0){return emptyMoves}var length=path.value.length;if(length<1){return emptyMoves}var argc=arguments.length;if(argc===2){start=0;end=length}else if(argc===3){start=Math.max(start,0);end=length}else{start=Math.max(start,0);end=Math.min(end,length)}isNumber.assert(start);isNumber.assert(end);var moves=Object.create(null);var cache=getChildCache(path);for(var i=start;i<end;++i){if(hasOwn.call(path.value,i)){var childPath=path.get(i);assert.strictEqual(childPath.name,i);var newIndex=i+offset;childPath.name=newIndex;moves[newIndex]=childPath;delete cache[i]}}delete cache.length;return function(){for(var newIndex in moves){var childPath=moves[newIndex];assert.strictEqual(childPath.name,+newIndex);cache[newIndex]=childPath;path.value[newIndex]=childPath.value}}}Pp.shift=function shift(){var move=getMoves(this,-1);var result=this.value.shift();move();return result};Pp.unshift=function unshift(node){var move=getMoves(this,arguments.length);var result=this.value.unshift.apply(this.value,arguments);move();return result};Pp.push=function push(node){isArray.assert(this.value);delete getChildCache(this).length;return this.value.push.apply(this.value,arguments)};Pp.pop=function pop(){isArray.assert(this.value);var cache=getChildCache(this);delete cache[this.value.length-1];delete cache.length;return this.value.pop()};Pp.insertAt=function insertAt(index,node){var argc=arguments.length;var move=getMoves(this,argc-1,index);if(move===emptyMoves){return this}index=Math.max(index,0);for(var i=1;i<argc;++i){this.value[index+i-1]=arguments[i]}move();return this};Pp.insertBefore=function insertBefore(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};Pp.insertAfter=function insertAfter(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name+1];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};function repairRelationshipWithParent(path){assert.ok(path instanceof Path);var pp=path.parentPath;if(!pp){return path}var parentValue=pp.value;var parentCache=getChildCache(pp);if(parentValue[path.name]===path.value){parentCache[path.name]=path}else if(isArray.check(parentValue)){var i=parentValue.indexOf(path.value);if(i>=0){parentCache[path.name=i]=path}}else{parentValue[path.name]=path.value;parentCache[path.name]=path}assert.strictEqual(parentValue[path.name],path.value);assert.strictEqual(path.parentPath.get(path.name),path);return path}Pp.replace=function replace(replacement){var results=[];var parentValue=this.parentPath.value;var parentCache=getChildCache(this.parentPath);var count=arguments.length;repairRelationshipWithParent(this);if(isArray.check(parentValue)){var originalLength=parentValue.length;var move=getMoves(this.parentPath,count-1,this.name+1);var spliceArgs=[this.name,1];for(var i=0;i<count;++i){spliceArgs.push(arguments[i])}var splicedOut=parentValue.splice.apply(parentValue,spliceArgs);assert.strictEqual(splicedOut[0],this.value);assert.strictEqual(parentValue.length,originalLength-1+count);move();if(count===0){delete this.value;delete parentCache[this.name];this.__childCache=null}else{assert.strictEqual(parentValue[this.name],replacement);if(this.value!==replacement){this.value=replacement;this.__childCache=null}for(i=0;i<count;++i){results.push(this.parentPath.get(this.name+i))}assert.strictEqual(results[0],this)}}else if(count===1){if(this.value!==replacement){this.__childCache=null}this.value=parentValue[this.name]=replacement;results.push(this)}else if(count===0){delete parentValue[this.name];delete this.value;this.__childCache=null}else{assert.ok(false,"Could not replace path")}return results};module.exports=Path},{"./types":91,assert:94}],89:[function(require,module,exports){var assert=require("assert");var types=require("./types");var Type=types.Type;var namedTypes=types.namedTypes;var Node=namedTypes.Node;var Expression=namedTypes.Expression;var isArray=types.builtInTypes.array;var hasOwn=Object.prototype.hasOwnProperty;var b=types.builders;function Scope(path,parentScope){assert.ok(this instanceof Scope);assert.ok(path instanceof require("./node-path"));ScopeType.assert(path.value);var depth;if(parentScope){assert.ok(parentScope instanceof Scope);depth=parentScope.depth+1}else{parentScope=null;depth=0}Object.defineProperties(this,{path:{value:path},node:{value:path.value},isGlobal:{value:!parentScope,enumerable:true},depth:{value:depth},parent:{value:parentScope},bindings:{value:{}}})}var scopeTypes=[namedTypes.Program,namedTypes.Function,namedTypes.CatchClause];var ScopeType=Type.or.apply(Type,scopeTypes);Scope.isEstablishedBy=function(node){return ScopeType.check(node)};var Sp=Scope.prototype;Sp.didScan=false;Sp.declares=function(name){this.scan();return hasOwn.call(this.bindings,name)};Sp.declareTemporary=function(prefix){if(prefix){assert.ok(/^[a-z$_]/i.test(prefix),prefix)}else{prefix="t$"}prefix+=this.depth.toString(36)+"$";this.scan();var index=0;while(this.declares(prefix+index)){++index}var name=prefix+index;return this.bindings[name]=types.builders.identifier(name)};Sp.injectTemporary=function(identifier,init){identifier||(identifier=this.declareTemporary());var bodyPath=this.path.get("body");if(namedTypes.BlockStatement.check(bodyPath.value)){bodyPath=bodyPath.get("body")}bodyPath.unshift(b.variableDeclaration("var",[b.variableDeclarator(identifier,init||null)]));return identifier};Sp.scan=function(force){if(force||!this.didScan){for(var name in this.bindings){delete this.bindings[name]}scanScope(this.path,this.bindings);this.didScan=true}};Sp.getBindings=function(){this.scan();return this.bindings};function scanScope(path,bindings){var node=path.value;ScopeType.assert(node);if(namedTypes.CatchClause.check(node)){addPattern(path.get("param"),bindings)}else{recursiveScanScope(path,bindings)}}function recursiveScanScope(path,bindings){var node=path.value;if(path.parent&&namedTypes.FunctionExpression.check(path.parent.node)&&path.parent.node.id){addPattern(path.parent.get("id"),bindings)}if(!node){}else if(isArray.check(node)){path.each(function(childPath){recursiveScanChild(childPath,bindings)})}else if(namedTypes.Function.check(node)){path.get("params").each(function(paramPath){addPattern(paramPath,bindings)});recursiveScanChild(path.get("body"),bindings)}else if(namedTypes.VariableDeclarator.check(node)){addPattern(path.get("id"),bindings);recursiveScanChild(path.get("init"),bindings)}else if(node.type==="ImportSpecifier"||node.type==="ImportNamespaceSpecifier"||node.type==="ImportDefaultSpecifier"){addPattern(node.name?path.get("name"):path.get("id"),bindings)}else if(Node.check(node)&&!Expression.check(node)){types.eachField(node,function(name,child){var childPath=path.get(name);assert.strictEqual(childPath.value,child);recursiveScanChild(childPath,bindings)})}}function recursiveScanChild(path,bindings){var node=path.value;if(!node||Expression.check(node)){}else if(namedTypes.FunctionDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(namedTypes.ClassDeclaration&&namedTypes.ClassDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(ScopeType.check(node)){if(namedTypes.CatchClause.check(node)){var catchParamName=node.param.name;var hadBinding=hasOwn.call(bindings,catchParamName);recursiveScanScope(path.get("body"),bindings);if(!hadBinding){delete bindings[catchParamName]}}}else{recursiveScanScope(path,bindings)}}function addPattern(patternPath,bindings){var pattern=patternPath.value;namedTypes.Pattern.assert(pattern);if(namedTypes.Identifier.check(pattern)){if(hasOwn.call(bindings,pattern.name)){bindings[pattern.name].push(patternPath)}else{bindings[pattern.name]=[patternPath]}}else if(namedTypes.SpreadElement&&namedTypes.SpreadElement.check(pattern)){addPattern(patternPath.get("argument"),bindings)}}Sp.lookup=function(name){for(var scope=this;scope;scope=scope.parent)if(scope.declares(name))break;return scope};Sp.getGlobalScope=function(){var scope=this;while(!scope.isGlobal)scope=scope.parent;return scope};module.exports=Scope},{"./node-path":86,"./types":91,assert:94}],90:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var builtin=types.builtInTypes;var isNumber=builtin.number;exports.geq=function(than){return new Type(function(value){return isNumber.check(value)&&value>=than},isNumber+" >= "+than)};exports.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return false},"true":function(){return true},undefined:function(){}};var naiveIsPrimitive=Type.or(builtin.string,builtin.number,builtin.boolean,builtin.null,builtin.undefined);exports.isPrimitive=new Type(function(value){if(value===null)return true;var type=typeof value;return!(type==="object"||type==="function")},naiveIsPrimitive.toString())},{"../lib/types":91}],91:[function(require,module,exports){var assert=require("assert");var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;var each=Ap.forEach;var Op=Object.prototype;var objToStr=Op.toString;var funObjStr=objToStr.call(function(){});var strObjStr=objToStr.call("");var hasOwn=Op.hasOwnProperty;function Type(check,name){var self=this;assert.ok(self instanceof Type,self);assert.strictEqual(objToStr.call(check),funObjStr,check+" is not a function");var nameObjStr=objToStr.call(name);assert.ok(nameObjStr===funObjStr||nameObjStr===strObjStr,name+" is neither a function nor a string");Object.defineProperties(self,{name:{value:name},check:{value:function(value,deep){var result=check.call(self,value,deep);if(!result&&deep&&objToStr.call(deep)===funObjStr)deep(self,value);return result}}})}var Tp=Type.prototype;exports.Type=Type;Tp.assert=function(value,deep){if(!this.check(value,deep)){var str=shallowStringify(value);assert.ok(false,str+" does not match type "+this);return false}return true};function shallowStringify(value){if(isObject.check(value))return"{"+Object.keys(value).map(function(key){return key+": "+value[key]}).join(", ")+"}";if(isArray.check(value))return"["+value.map(shallowStringify).join(", ")+"]";return JSON.stringify(value)}Tp.toString=function(){var name=this.name;if(isString.check(name))return name;if(isFunction.check(name))return name.call(this)+"";return name+" type"};var builtInTypes={};exports.builtInTypes=builtInTypes;function defBuiltInType(example,name){var objStr=objToStr.call(example);Object.defineProperty(builtInTypes,name,{enumerable:true,value:new Type(function(value){return objToStr.call(value)===objStr},name)});return builtInTypes[name]}var isString=defBuiltInType("","string");var isFunction=defBuiltInType(function(){},"function");var isArray=defBuiltInType([],"array");var isObject=defBuiltInType({},"object");var isRegExp=defBuiltInType(/./,"RegExp");var isDate=defBuiltInType(new Date,"Date");var isNumber=defBuiltInType(3,"number");var isBoolean=defBuiltInType(true,"boolean");var isNull=defBuiltInType(null,"null");var isUndefined=defBuiltInType(void 0,"undefined");function toType(from,name){if(from instanceof Type)return from;if(from instanceof Def)return from.type;if(isArray.check(from))return Type.fromArray(from);if(isObject.check(from))return Type.fromObject(from);if(isFunction.check(from))return new Type(from,name);return new Type(function(value){return value===from},isUndefined.check(name)?function(){return from+""}:name)}Type.or=function(){var types=[];var len=arguments.length;for(var i=0;i<len;++i)types.push(toType(arguments[i]));return new Type(function(value,deep){for(var i=0;i<len;++i)if(types[i].check(value,deep))return true;return false},function(){return types.join(" | ")})};Type.fromArray=function(arr){assert.ok(isArray.check(arr));assert.strictEqual(arr.length,1,"only one element type is permitted for typed arrays");return toType(arr[0]).arrayOf()};Tp.arrayOf=function(){var elemType=this;return new Type(function(value,deep){return isArray.check(value)&&value.every(function(elem){return elemType.check(elem,deep)})},function(){return"["+elemType+"]"})};Type.fromObject=function(obj){var fields=Object.keys(obj).map(function(name){return new Field(name,obj[name])});return new Type(function(value,deep){return isObject.check(value)&&fields.every(function(field){return field.type.check(value[field.name],deep)})},function(){return"{ "+fields.join(", ")+" }"})};function Field(name,type,defaultFn,hidden){var self=this;assert.ok(self instanceof Field);isString.assert(name);type=toType(type);var properties={name:{value:name},type:{value:type},hidden:{value:!!hidden}};if(isFunction.check(defaultFn)){properties.defaultFn={value:defaultFn}}Object.defineProperties(self,properties)}var Fp=Field.prototype;Fp.toString=function(){return JSON.stringify(this.name)+": "+this.type};Fp.getValue=function(obj){var value=obj[this.name];if(!isUndefined.check(value))return value;if(this.defaultFn)value=this.defaultFn.call(obj);return value};Type.def=function(typeName){isString.assert(typeName);return hasOwn.call(defCache,typeName)?defCache[typeName]:defCache[typeName]=new Def(typeName)};var defCache=Object.create(null);function Def(typeName){var self=this;assert.ok(self instanceof Def);Object.defineProperties(self,{typeName:{value:typeName},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new Type(function(value,deep){return self.check(value,deep) },typeName)}})}Def.fromValue=function(value){if(value&&typeof value==="object"){var type=value.type;if(typeof type==="string"&&hasOwn.call(defCache,type)){var d=defCache[type];if(d.finalized){return d}}}return null};var Dp=Def.prototype;Dp.isSupertypeOf=function(that){if(that instanceof Def){assert.strictEqual(this.finalized,true);assert.strictEqual(that.finalized,true);return hasOwn.call(that.allSupertypes,this.typeName)}else{assert.ok(false,that+" is not a Def")}};exports.getSupertypeNames=function(typeName){assert.ok(hasOwn.call(defCache,typeName));var d=defCache[typeName];assert.strictEqual(d.finalized,true);return d.supertypeList.slice(1)};exports.computeSupertypeLookupTable=function(candidates){var table={};var typeNames=Object.keys(defCache);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];var d=defCache[typeName];assert.strictEqual(d.finalized,true);for(var j=0;j<d.supertypeList.length;++j){var superTypeName=d.supertypeList[j];if(hasOwn.call(candidates,superTypeName)){table[typeName]=superTypeName;break}}}return table};Dp.checkAllFields=function(value,deep){var allFields=this.allFields;assert.strictEqual(this.finalized,true);function checkFieldByName(name){var field=allFields[name];var type=field.type;var child=field.getValue(value);return type.check(child,deep)}return isObject.check(value)&&Object.keys(allFields).every(checkFieldByName)};Dp.check=function(value,deep){assert.strictEqual(this.finalized,true,"prematurely checking unfinalized type "+this.typeName);if(!isObject.check(value))return false;var vDef=Def.fromValue(value);if(!vDef){if(this.typeName==="SourceLocation"||this.typeName==="Position"){return this.checkAllFields(value,deep)}return false}if(deep&&vDef===this)return this.checkAllFields(value,deep);if(!this.isSupertypeOf(vDef))return false;if(!deep)return true;return vDef.checkAllFields(value,deep)&&this.checkAllFields(value,false)};Dp.bases=function(){var bases=this.baseNames;assert.strictEqual(this.finalized,false);each.call(arguments,function(baseName){isString.assert(baseName);if(bases.indexOf(baseName)<0)bases.push(baseName)});return this};Object.defineProperty(Dp,"buildable",{value:false});var builders={};exports.builders=builders;var nodePrototype={};exports.defineMethod=function(name,func){var old=nodePrototype[name];if(isUndefined.check(func)){delete nodePrototype[name]}else{isFunction.assert(func);Object.defineProperty(nodePrototype,name,{enumerable:true,configurable:true,value:func})}return old};Dp.build=function(){var self=this;Object.defineProperty(self,"buildParams",{value:slice.call(arguments),writable:false,enumerable:false,configurable:true});assert.strictEqual(self.finalized,false);isString.arrayOf().assert(self.buildParams);if(self.buildable){return self}self.field("type",self.typeName,function(){return self.typeName});Object.defineProperty(self,"buildable",{value:true});Object.defineProperty(builders,getBuilderName(self.typeName),{enumerable:true,value:function(){var args=arguments;var argc=args.length;var built=Object.create(nodePrototype);assert.ok(self.finalized,"attempting to instantiate unfinalized type "+self.typeName);function add(param,i){if(hasOwn.call(built,param))return;var all=self.allFields;assert.ok(hasOwn.call(all,param),param);var field=all[param];var type=field.type;var value;if(isNumber.check(i)&&i<argc){value=args[i]}else if(field.defaultFn){value=field.defaultFn.call(built)}else{var message="no value or default function given for field "+JSON.stringify(param)+" of "+self.typeName+"("+self.buildParams.map(function(name){return all[name]}).join(", ")+")";assert.ok(false,message)}if(!type.check(value)){assert.ok(false,shallowStringify(value)+" does not match field "+field+" of type "+self.typeName)}built[param]=value}self.buildParams.forEach(function(param,i){add(param,i)});Object.keys(self.allFields).forEach(function(param){add(param)});assert.strictEqual(built.type,self.typeName);return built}});return self};function getBuilderName(typeName){return typeName.replace(/^[A-Z]+/,function(upperCasePrefix){var len=upperCasePrefix.length;switch(len){case 0:return"";case 1:return upperCasePrefix.toLowerCase();default:return upperCasePrefix.slice(0,len-1).toLowerCase()+upperCasePrefix.charAt(len-1)}})}Dp.field=function(name,type,defaultFn,hidden){assert.strictEqual(this.finalized,false);this.ownFields[name]=new Field(name,type,defaultFn,hidden);return this};var namedTypes={};exports.namedTypes=namedTypes;function getFieldNames(object){var d=Def.fromValue(object);if(d){return d.fieldNames.slice(0)}if("type"in object){assert.ok(false,"did not recognize object of type "+JSON.stringify(object.type))}return Object.keys(object)}exports.getFieldNames=getFieldNames;function getFieldValue(object,fieldName){var d=Def.fromValue(object);if(d){var field=d.allFields[fieldName];if(field){return field.getValue(object)}}return object[fieldName]}exports.getFieldValue=getFieldValue;exports.eachField=function(object,callback,context){getFieldNames(object).forEach(function(name){callback.call(this,name,getFieldValue(object,name))},context)};exports.someField=function(object,callback,context){return getFieldNames(object).some(function(name){return callback.call(this,name,getFieldValue(object,name))},context)};Object.defineProperty(Dp,"finalized",{value:false});Dp.finalize=function(){if(!this.finalized){var allFields=this.allFields;var allSupertypes=this.allSupertypes;this.baseNames.forEach(function(name){var def=defCache[name];def.finalize();extend(allFields,def.allFields);extend(allSupertypes,def.allSupertypes)});extend(allFields,this.ownFields);allSupertypes[this.typeName]=this;this.fieldNames.length=0;for(var fieldName in allFields){if(hasOwn.call(allFields,fieldName)&&!allFields[fieldName].hidden){this.fieldNames.push(fieldName)}}Object.defineProperty(namedTypes,this.typeName,{enumerable:true,value:this.type});Object.defineProperty(this,"finalized",{value:true});populateSupertypeList(this.typeName,this.supertypeList)}};function populateSupertypeList(typeName,list){list.length=0;list.push(typeName);var lastSeen=Object.create(null);for(var pos=0;pos<list.length;++pos){typeName=list[pos];var d=defCache[typeName];assert.strictEqual(d.finalized,true);if(hasOwn.call(lastSeen,typeName)){delete list[lastSeen[typeName]]}lastSeen[typeName]=pos;list.push.apply(list,d.baseNames)}for(var to=0,from=to,len=list.length;from<len;++from){if(hasOwn.call(list,from)){list[to++]=list[from]}}list.length=to}function extend(into,from){Object.keys(from).forEach(function(name){into[name]=from[name]});return into}exports.finalize=function(){Object.keys(defCache).forEach(function(name){defCache[name].finalize()})}},{assert:94}],92:[function(require,module,exports){var types=require("./lib/types");require("./def/core");require("./def/es6");require("./def/es7");require("./def/mozilla");require("./def/e4x");require("./def/fb-harmony");types.finalize();exports.Type=types.Type;exports.builtInTypes=types.builtInTypes;exports.namedTypes=types.namedTypes;exports.builders=types.builders;exports.defineMethod=types.defineMethod;exports.getFieldNames=types.getFieldNames;exports.getFieldValue=types.getFieldValue;exports.eachField=types.eachField;exports.someField=types.someField;exports.getSupertypeNames=types.getSupertypeNames;exports.astNodesAreEquivalent=require("./lib/equiv");exports.finalize=types.finalize;exports.NodePath=require("./lib/node-path");exports.PathVisitor=require("./lib/path-visitor");exports.visit=exports.PathVisitor.visit},{"./def/core":79,"./def/e4x":80,"./def/es6":81,"./def/es7":82,"./def/fb-harmony":83,"./def/mozilla":84,"./lib/equiv":85,"./lib/node-path":86,"./lib/path-visitor":87,"./lib/types":91}],93:[function(require,module,exports){},{}],94:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&(isNaN(value)||!isFinite(value))){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(isArguments(a)){if(!isArguments(b)){return false}a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}try{var ka=objectKeys(a),kb=objectKeys(b),key,i}catch(e){return false}if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":103}],95:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("is-array");exports.Buffer=Buffer;exports.SlowBuffer=Buffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var kMaxLength=1073741823;Buffer.TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){if(encoding==="base64")subject=base64clean(subject);length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new TypeError("must start with number, buffer, array or string");if(this.length>kMaxLength)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength.toString(16)+" bytes");var buf;if(Buffer.TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!Buffer.TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}return buf}Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function(list,totalLength){if(!isArray(list))throw new TypeError("Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.byteLength=function(str,encoding){var ret;str=str+"";switch(encoding||"utf8"){case"ascii":case"binary":case"raw":ret=str.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;case"hex":ret=str.length>>>1;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"base64":ret=base64ToBytes(str).length;break;default:ret=str.length}return ret};Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined;Buffer.prototype.toString=function(encoding,start,end){var loweredCase=false;start=start>>>0;end=end===undefined||end===Infinity?this.length:end>>>0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}};Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);if(isNaN(byte))throw new Error("Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string),buf,offset,length);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new TypeError("Unknown encoding: "+encoding)}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function binarySlice(buf,start,end){return asciiSlice(buf,start,end)}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;if(Buffer.TYPED_ARRAY_SUPPORT){return Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;var newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}return newBuf}};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||value<min)throw new TypeError("value is out of bounds");if(offset+ext>buf.length)throw new TypeError("index out of range")}Buffer.prototype.writeUInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};Buffer.prototype.writeInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value;return offset+1};Buffer.prototype.writeInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};Buffer.prototype.writeInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||value<min)throw new TypeError("value is out of bounds");if(offset+ext>buf.length)throw new TypeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38);ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308);ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(!target_start)target_start=0;if(end===start)return;if(target.length===0||source.length===0)return;if(end<start)throw new TypeError("sourceEnd < sourceStart");if(target_start<0||target_start>=target.length)throw new TypeError("targetStart out of bounds");if(start<0||start>=source.length)throw new TypeError("sourceStart out of bounds");if(end<0||end>source.length)throw new TypeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new TypeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new TypeError("start out of bounds");if(end<0||end>this.length)throw new TypeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(Buffer.TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr.constructor=Buffer;arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16) }function utf8ToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){var b=str.charCodeAt(i);if(b<=127){byteArray.push(b)}else{var start=i;if(b>=55296&&b<=57343)i++;var h=encodeURIComponent(str.slice(start,i+1)).substr(1).split("%");for(var j=0;j<h.length;j++){byteArray.push(parseInt(h[j],16))}}}return byteArray}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(str)}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}},{"base64-js":96,ieee754:97,"is-array":98}],96:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS)return 62;if(code===SLASH)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],97:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],98:[function(require,module,exports){var isArray=Array.isArray;var str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],99:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],100:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1)};exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")};exports.sep="/";exports.delimiter=":";exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir};exports.basename=function(path,ext){var f=splitPath(path)[2];if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){return splitPath(path)[3]};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i])}return res}var substr="ab".substr(-1)==="b"?function(str,start,len){return str.substr(start,len)}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len)}}).call(this,require("_process"))},{_process:101}],101:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],102:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],103:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":102,_process:101,inherits:99}],104:[function(require,module,exports){(function(root,factory){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],factory)}else if(typeof exports!=="undefined"){factory(exports)}else{factory(root.estraverse={})}})(this,function(exports){"use strict";var Syntax,isArray,VisitorOption,VisitorKeys,objectCreate,objectKeys,BREAK,SKIP,REMOVE;function ignoreJSHintError(){}isArray=Array.isArray;if(!isArray){isArray=function isArray(array){return Object.prototype.toString.call(array)==="[object Array]"}}function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==="object"&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function shallowCopy(obj){var ret={},key;for(key in obj){if(obj.hasOwnProperty(key)){ret[key]=obj[key]}}return ret}ignoreJSHintError(shallowCopy);function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}function lowerBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){i=current+1;len-=diff+1}else{len=diff}}return i}ignoreJSHintError(lowerBound);objectCreate=Object.create||function(){function F(){}return function(o){F.prototype=o;return new F}}();objectKeys=Object.keys||function(o){var keys=[],key;for(key in o){keys.push(key)}return keys};function extend(to,from){objectKeys(from).forEach(function(key){to[key]=from[key]});return to}Syntax={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"};VisitorKeys={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype["break"]=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=visitor.fallback==="iteration";this.__keys=VisitorKeys;if(visitor.keys){this.__keys=extend(objectCreate(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==="object"&&typeof node.type==="string"}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&"properties"===key}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){function removeElem(element){var i,key,nextElem,parent;if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,"root"));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0] }target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error("attachComments needs range information")}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.version="1.8.0";exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller})},{}],105:[function(require,module,exports){(function(){"use strict";function isExpression(node){if(node==null){return false}switch(node.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return true}return false}function isIterationStatement(node){if(node==null){return false}switch(node.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return true}return false}function isStatement(node){if(node==null){return false}switch(node.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return true}return false}function isSourceElement(node){return isStatement(node)||node!=null&&node.type==="FunctionDeclaration"}function trailingStatement(node){switch(node.type){case"IfStatement":if(node.alternate!=null){return node.alternate}return node.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return node.body}return null}function isProblematicIfStatement(node){var current;if(node.type!=="IfStatement"){return false}if(node.alternate==null){return false}current=node.consequent;do{if(current.type==="IfStatement"){if(current.alternate==null){return true}}current=trailingStatement(current)}while(current);return false}module.exports={isExpression:isExpression,isStatement:isStatement,isIterationStatement:isIterationStatement,isSourceElement:isSourceElement,isProblematicIfStatement:isProblematicIfStatement,trailingStatement:trailingStatement}})()},{}],106:[function(require,module,exports){(function(){"use strict";var Regex;Regex={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")};function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return isDecimalDigit(ch)||97<=ch&&ch<=102||65<=ch&&ch<=70}function isOctalDigit(ch){return ch>=48&&ch<=55}function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(ch)>=0}function isLineTerminator(ch){return ch===10||ch===13||ch===8232||ch===8233}function isIdentifierStart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch===92||ch>=128&&Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))}function isIdentifierPart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))}module.exports={isDecimalDigit:isDecimalDigit,isHexDigit:isHexDigit,isOctalDigit:isOctalDigit,isWhiteSpace:isWhiteSpace,isLineTerminator:isLineTerminator,isIdentifierStart:isIdentifierStart,isIdentifierPart:isIdentifierPart}})()},{}],107:[function(require,module,exports){(function(){"use strict";var code=require("./code");function isStrictModeReservedWordES6(id){switch(id){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return true;default:return false}}function isKeywordES5(id,strict){if(!strict&&id==="yield"){return false}return isKeywordES6(id,strict)}function isKeywordES6(id,strict){if(strict&&isStrictModeReservedWordES6(id)){return true}switch(id.length){case 2:return id==="if"||id==="in"||id==="do";case 3:return id==="var"||id==="for"||id==="new"||id==="try";case 4:return id==="this"||id==="else"||id==="case"||id==="void"||id==="with"||id==="enum";case 5:return id==="while"||id==="break"||id==="catch"||id==="throw"||id==="const"||id==="yield"||id==="class"||id==="super";case 6:return id==="return"||id==="typeof"||id==="delete"||id==="switch"||id==="export"||id==="import";case 7:return id==="default"||id==="finally"||id==="extends";case 8:return id==="function"||id==="continue"||id==="debugger";case 10:return id==="instanceof";default:return false}}function isReservedWordES5(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES5(id,strict)}function isReservedWordES6(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES6(id,strict)}function isRestrictedWord(id){return id==="eval"||id==="arguments"}function isIdentifierName(id){var i,iz,ch;if(id.length===0){return false}ch=id.charCodeAt(0);if(!code.isIdentifierStart(ch)||ch===92){return false}for(i=1,iz=id.length;i<iz;++i){ch=id.charCodeAt(i);if(!code.isIdentifierPart(ch)||ch===92){return false}}return true}function isIdentifierES5(id,strict){return isIdentifierName(id)&&!isReservedWordES5(id,strict)}function isIdentifierES6(id,strict){return isIdentifierName(id)&&!isReservedWordES6(id,strict)}module.exports={isKeywordES5:isKeywordES5,isKeywordES6:isKeywordES6,isReservedWordES5:isReservedWordES5,isReservedWordES6:isReservedWordES6,isRestrictedWord:isRestrictedWord,isIdentifierName:isIdentifierName,isIdentifierES5:isIdentifierES5,isIdentifierES6:isIdentifierES6}})()},{"./code":106}],108:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":105,"./code":106,"./keyword":107}],109:[function(require,module,exports){(function(global){(function(){var undefined;var arrayPool=[],objectPool=[];var idCounter=0;var keyPrefix=+new Date+"";var largeArraySize=75;var maxPoolSize=40;var whitespace=" \f "+"\n\r\u2028\u2029"+" ᠎              ";var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;var reFlags=/\w*$/;var reFuncName=/^\s*function[ \n\r\t]+\w/;var reInterpolate=/<%=([\s\S]+?)%>/g;var reLeadingSpacesAndZeros=RegExp("^["+whitespace+"]*0+(?=.$)");var reNoMatch=/($^)/;var reThis=/\bthis\b/;var reUnescapedString=/['\n\r\t\u2028\u2029\\]/g;var contextProps=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"];var templateCounter=0;var argsClass="[object Arguments]",arrayClass="[object Array]",boolClass="[object Boolean]",dateClass="[object Date]",funcClass="[object Function]",numberClass="[object Number]",objectClass="[object Object]",regexpClass="[object RegExp]",stringClass="[object String]";var cloneableClasses={};cloneableClasses[funcClass]=false;cloneableClasses[argsClass]=cloneableClasses[arrayClass]=cloneableClasses[boolClass]=cloneableClasses[dateClass]=cloneableClasses[numberClass]=cloneableClasses[objectClass]=cloneableClasses[regexpClass]=cloneableClasses[stringClass]=true;var debounceOptions={leading:false,maxWait:0,trailing:false};var descriptor={configurable:false,enumerable:false,value:null,writable:false};var objectTypes={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};var stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};var root=objectTypes[typeof window]&&window||this;var freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports;var freeGlobal=objectTypes[typeof global]&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal)){root=freeGlobal}function baseIndexOf(array,value,fromIndex){var index=(fromIndex||0)-1,length=array?array.length:0;while(++index<length){if(array[index]===value){return index}}return-1}function cacheIndexOf(cache,value){var type=typeof value;cache=cache.cache;if(type=="boolean"||value==null){return cache[value]?0:-1}if(type!="number"&&type!="string"){type="object"}var key=type=="number"?value:keyPrefix+value;cache=(cache=cache[type])&&cache[key];return type=="object"?cache&&baseIndexOf(cache,value)>-1?0:-1:cache?0:-1}function cachePush(value){var cache=this.cache,type=typeof value;if(type=="boolean"||value==null){cache[value]=true}else{if(type!="number"&&type!="string"){type="object"}var key=type=="number"?value:keyPrefix+value,typeCache=cache[type]||(cache[type]={});if(type=="object"){(typeCache[key]||(typeCache[key]=[])).push(value)}else{typeCache[key]=true}}}function charAtCallback(value){return value.charCodeAt(0)}function compareAscending(a,b){var ac=a.criteria,bc=b.criteria,index=-1,length=ac.length;while(++index<length){var value=ac[index],other=bc[index];if(value!==other){if(value>other||typeof value=="undefined"){return 1}if(value<other||typeof other=="undefined"){return-1}}}return a.index-b.index}function createCache(array){var index=-1,length=array.length,first=array[0],mid=array[length/2|0],last=array[length-1];if(first&&typeof first=="object"&&mid&&typeof mid=="object"&&last&&typeof last=="object"){return false}var cache=getObject();cache["false"]=cache["null"]=cache["true"]=cache["undefined"]=false;var result=getObject();result.array=array;result.cache=cache;result.push=cachePush;while(++index<length){result.push(array[index])}return result}function escapeStringChar(match){return"\\"+stringEscapes[match]}function getArray(){return arrayPool.pop()||[]}function getObject(){return objectPool.pop()||{array:null,cache:null,criteria:null,"false":false,index:0,"null":false,number:null,object:null,push:null,string:null,"true":false,undefined:false,value:null}}function releaseArray(array){array.length=0;if(arrayPool.length<maxPoolSize){arrayPool.push(array)}}function releaseObject(object){var cache=object.cache;if(cache){releaseObject(cache)}object.array=object.cache=object.criteria=object.object=object.number=object.string=object.value=null;if(objectPool.length<maxPoolSize){objectPool.push(object)}}function slice(array,start,end){start||(start=0);if(typeof end=="undefined"){end=array?array.length:0}var index=-1,length=end-start||0,result=Array(length<0?0:length);while(++index<length){result[index]=array[start+index]}return result}function runInContext(context){context=context?_.defaults(root.Object(),context,_.pick(root,contextProps)):root;var Array=context.Array,Boolean=context.Boolean,Date=context.Date,Function=context.Function,Math=context.Math,Number=context.Number,Object=context.Object,RegExp=context.RegExp,String=context.String,TypeError=context.TypeError;var arrayRef=[];var objectProto=Object.prototype;var oldDash=context._;var toString=objectProto.toString;var reNative=RegExp("^"+String(toString).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var ceil=Math.ceil,clearTimeout=context.clearTimeout,floor=Math.floor,fnToString=Function.prototype.toString,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,hasOwnProperty=objectProto.hasOwnProperty,push=arrayRef.push,setTimeout=context.setTimeout,splice=arrayRef.splice,unshift=arrayRef.unshift;var defineProperty=function(){try{var o={},func=isNative(func=Object.defineProperty)&&func,result=func(o,o,o)&&func}catch(e){}return result}();var nativeCreate=isNative(nativeCreate=Object.create)&&nativeCreate,nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeIsFinite=context.isFinite,nativeIsNaN=context.isNaN,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,nativeParseInt=context.parseInt,nativeRandom=Math.random;var ctorByClass={};ctorByClass[arrayClass]=Array;ctorByClass[boolClass]=Boolean;ctorByClass[dateClass]=Date;ctorByClass[funcClass]=Function;ctorByClass[objectClass]=Object;ctorByClass[numberClass]=Number;ctorByClass[regexpClass]=RegExp;ctorByClass[stringClass]=String;function lodash(value){return value&&typeof value=="object"&&!isArray(value)&&hasOwnProperty.call(value,"__wrapped__")?value:new lodashWrapper(value)}function lodashWrapper(value,chainAll){this.__chain__=!!chainAll;this.__wrapped__=value}lodashWrapper.prototype=lodash.prototype;var support=lodash.support={};support.funcDecomp=!isNative(context.WinRTError)&&reThis.test(runInContext);support.funcNames=typeof Function.name=="string";lodash.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:reInterpolate,variable:"",imports:{_:lodash}};function baseBind(bindData){var func=bindData[0],partialArgs=bindData[2],thisArg=bindData[4];function bound(){if(partialArgs){var args=slice(partialArgs);push.apply(args,arguments)}if(this instanceof bound){var thisBinding=baseCreate(func.prototype),result=func.apply(thisBinding,args||arguments);return isObject(result)?result:thisBinding}return func.apply(thisArg,args||arguments)}setBindData(bound,bindData);return bound}function baseClone(value,isDeep,callback,stackA,stackB){if(callback){var result=callback(value);if(typeof result!="undefined"){return result}}var isObj=isObject(value);if(isObj){var className=toString.call(value);if(!cloneableClasses[className]){return value}var ctor=ctorByClass[className];switch(className){case boolClass:case dateClass:return new ctor(+value);case numberClass:case stringClass:return new ctor(value);case regexpClass:result=ctor(value.source,reFlags.exec(value));result.lastIndex=value.lastIndex;return result}}else{return value}var isArr=isArray(value);if(isDeep){var initedStack=!stackA;stackA||(stackA=getArray());stackB||(stackB=getArray());var length=stackA.length;while(length--){if(stackA[length]==value){return stackB[length]}}result=isArr?ctor(value.length):{}}else{result=isArr?slice(value):assign({},value)}if(isArr){if(hasOwnProperty.call(value,"index")){result.index=value.index}if(hasOwnProperty.call(value,"input")){result.input=value.input}}if(!isDeep){return result}stackA.push(value);stackB.push(result);(isArr?forEach:forOwn)(value,function(objValue,key){result[key]=baseClone(objValue,isDeep,callback,stackA,stackB)});if(initedStack){releaseArray(stackA);releaseArray(stackB)}return result}function baseCreate(prototype,properties){return isObject(prototype)?nativeCreate(prototype):{}}if(!nativeCreate){baseCreate=function(){function Object(){}return function(prototype){if(isObject(prototype)){Object.prototype=prototype;var result=new Object;Object.prototype=null}return result||context.Object()}}()}function baseCreateCallback(func,thisArg,argCount){if(typeof func!="function"){return identity}if(typeof thisArg=="undefined"||!("prototype"in func)){return func}var bindData=func.__bindData__;if(typeof bindData=="undefined"){if(support.funcNames){bindData=!func.name}bindData=bindData||!support.funcDecomp;if(!bindData){var source=fnToString.call(func);if(!support.funcNames){bindData=!reFuncName.test(source)}if(!bindData){bindData=reThis.test(source);setBindData(func,bindData)}}}if(bindData===false||bindData!==true&&bindData[1]&1){return func}switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 2:return function(a,b){return func.call(thisArg,a,b)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)}}return bind(func,thisArg)}function baseCreateWrapper(bindData){var func=bindData[0],bitmask=bindData[1],partialArgs=bindData[2],partialRightArgs=bindData[3],thisArg=bindData[4],arity=bindData[5];var isBind=bitmask&1,isBindKey=bitmask&2,isCurry=bitmask&4,isCurryBound=bitmask&8,key=func;function bound(){var thisBinding=isBind?thisArg:this;if(partialArgs){var args=slice(partialArgs);push.apply(args,arguments)}if(partialRightArgs||isCurry){args||(args=slice(arguments));if(partialRightArgs){push.apply(args,partialRightArgs)}if(isCurry&&args.length<arity){bitmask|=16&~32;return baseCreateWrapper([func,isCurryBound?bitmask:bitmask&~3,args,null,thisArg,arity])}}args||(args=arguments);if(isBindKey){func=thisBinding[key]}if(this instanceof bound){thisBinding=baseCreate(func.prototype);var result=func.apply(thisBinding,args);return isObject(result)?result:thisBinding}return func.apply(thisBinding,args)}setBindData(bound,bindData);return bound}function baseDifference(array,values){var index=-1,indexOf=getIndexOf(),length=array?array.length:0,isLarge=length>=largeArraySize&&indexOf===baseIndexOf,result=[];if(isLarge){var cache=createCache(values);if(cache){indexOf=cacheIndexOf;values=cache}else{isLarge=false}}while(++index<length){var value=array[index];if(indexOf(values,value)<0){result.push(value)}}if(isLarge){releaseObject(values)}return result}function baseFlatten(array,isShallow,isStrict,fromIndex){var index=(fromIndex||0)-1,length=array?array.length:0,result=[];while(++index<length){var value=array[index];if(value&&typeof value=="object"&&typeof value.length=="number"&&(isArray(value)||isArguments(value))){if(!isShallow){value=baseFlatten(value,isShallow,isStrict)}var valIndex=-1,valLength=value.length,resIndex=result.length;result.length+=valLength;while(++valIndex<valLength){result[resIndex++]=value[valIndex]}}else if(!isStrict){result.push(value)}}return result}function baseIsEqual(a,b,callback,isWhere,stackA,stackB){if(callback){var result=callback(a,b);if(typeof result!="undefined"){return!!result}}if(a===b){return a!==0||1/a==1/b}var type=typeof a,otherType=typeof b;if(a===a&&!(a&&objectTypes[type])&&!(b&&objectTypes[otherType])){return false}if(a==null||b==null){return a===b}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:return+a==+b;case numberClass:return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case regexpClass:case stringClass:return a==String(b)}var isArr=className==arrayClass;if(!isArr){var aWrapped=hasOwnProperty.call(a,"__wrapped__"),bWrapped=hasOwnProperty.call(b,"__wrapped__");if(aWrapped||bWrapped){return baseIsEqual(aWrapped?a.__wrapped__:a,bWrapped?b.__wrapped__:b,callback,isWhere,stackA,stackB)}if(className!=objectClass){return false}var ctorA=a.constructor,ctorB=b.constructor;if(ctorA!=ctorB&&!(isFunction(ctorA)&&ctorA instanceof ctorA&&isFunction(ctorB)&&ctorB instanceof ctorB)&&("constructor"in a&&"constructor"in b)){return false}}var initedStack=!stackA;stackA||(stackA=getArray());stackB||(stackB=getArray());var length=stackA.length;while(length--){if(stackA[length]==a){return stackB[length]==b}}var size=0;result=true;stackA.push(a);stackB.push(b);if(isArr){length=a.length;size=b.length;result=size==length;if(result||isWhere){while(size--){var index=length,value=b[size];if(isWhere){while(index--){if(result=baseIsEqual(a[index],value,callback,isWhere,stackA,stackB)){break}}}else if(!(result=baseIsEqual(a[size],value,callback,isWhere,stackA,stackB))){break}}}}else{forIn(b,function(value,key,b){if(hasOwnProperty.call(b,key)){size++;return result=hasOwnProperty.call(a,key)&&baseIsEqual(a[key],value,callback,isWhere,stackA,stackB)}});if(result&&!isWhere){forIn(a,function(value,key,a){if(hasOwnProperty.call(a,key)){return result=--size>-1}})}}stackA.pop();stackB.pop();if(initedStack){releaseArray(stackA);releaseArray(stackB)}return result}function baseMerge(object,source,callback,stackA,stackB){(isArray(source)?forEach:forOwn)(source,function(source,key){var found,isArr,result=source,value=object[key];if(source&&((isArr=isArray(source))||isPlainObject(source))){var stackLength=stackA.length;while(stackLength--){if(found=stackA[stackLength]==source){value=stackB[stackLength];break}}if(!found){var isShallow;if(callback){result=callback(value,source);if(isShallow=typeof result!="undefined"){value=result}}if(!isShallow){value=isArr?isArray(value)?value:[]:isPlainObject(value)?value:{}}stackA.push(source);stackB.push(value);if(!isShallow){baseMerge(value,source,callback,stackA,stackB)}}}else{if(callback){result=callback(value,source);if(typeof result=="undefined"){result=source}}if(typeof result!="undefined"){value=result}}object[key]=value})}function baseRandom(min,max){return min+floor(nativeRandom()*(max-min+1))}function baseUniq(array,isSorted,callback){var index=-1,indexOf=getIndexOf(),length=array?array.length:0,result=[];var isLarge=!isSorted&&length>=largeArraySize&&indexOf===baseIndexOf,seen=callback||isLarge?getArray():result;if(isLarge){var cache=createCache(seen);indexOf=cacheIndexOf;seen=cache}while(++index<length){var value=array[index],computed=callback?callback(value,index,array):value;if(isSorted?!index||seen[seen.length-1]!==computed:indexOf(seen,computed)<0){if(callback||isLarge){seen.push(computed)}result.push(value)}}if(isLarge){releaseArray(seen.array);releaseObject(seen)}else if(callback){releaseArray(seen)}return result}function createAggregator(setter){return function(collection,callback,thisArg){var result={};callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];setter(result,value,callback(value,index,collection),collection)}}else{forOwn(collection,function(value,key,collection){setter(result,value,callback(value,key,collection),collection)})}return result}}function createWrapper(func,bitmask,partialArgs,partialRightArgs,thisArg,arity){var isBind=bitmask&1,isBindKey=bitmask&2,isCurry=bitmask&4,isCurryBound=bitmask&8,isPartial=bitmask&16,isPartialRight=bitmask&32;if(!isBindKey&&!isFunction(func)){throw new TypeError}if(isPartial&&!partialArgs.length){bitmask&=~16;isPartial=partialArgs=false}if(isPartialRight&&!partialRightArgs.length){bitmask&=~32;isPartialRight=partialRightArgs=false}var bindData=func&&func.__bindData__;if(bindData&&bindData!==true){bindData=slice(bindData);if(bindData[2]){bindData[2]=slice(bindData[2])}if(bindData[3]){bindData[3]=slice(bindData[3])}if(isBind&&!(bindData[1]&1)){bindData[4]=thisArg}if(!isBind&&bindData[1]&1){bitmask|=8}if(isCurry&&!(bindData[1]&4)){bindData[5]=arity}if(isPartial){push.apply(bindData[2]||(bindData[2]=[]),partialArgs)}if(isPartialRight){unshift.apply(bindData[3]||(bindData[3]=[]),partialRightArgs)}bindData[1]|=bitmask;return createWrapper.apply(null,bindData)}var creater=bitmask==1||bitmask===17?baseBind:baseCreateWrapper;return creater([func,bitmask,partialArgs,partialRightArgs,thisArg,arity])}function escapeHtmlChar(match){return htmlEscapes[match]}function getIndexOf(){var result=(result=lodash.indexOf)===indexOf?baseIndexOf:result;return result}function isNative(value){return typeof value=="function"&&reNative.test(value)}var setBindData=!defineProperty?noop:function(func,value){descriptor.value=value;defineProperty(func,"__bindData__",descriptor)};function shimIsPlainObject(value){var ctor,result;if(!(value&&toString.call(value)==objectClass)||(ctor=value.constructor,isFunction(ctor)&&!(ctor instanceof ctor))){return false}forIn(value,function(value,key){result=key});return typeof result=="undefined"||hasOwnProperty.call(value,result)}function unescapeHtmlChar(match){return htmlUnescapes[match]}function isArguments(value){return value&&typeof value=="object"&&typeof value.length=="number"&&toString.call(value)==argsClass||false}var isArray=nativeIsArray||function(value){return value&&typeof value=="object"&&typeof value.length=="number"&&toString.call(value)==arrayClass||false};var shimKeys=function(object){var index,iterable=object,result=[];if(!iterable)return result;if(!objectTypes[typeof object])return result;for(index in iterable){if(hasOwnProperty.call(iterable,index)){result.push(index)}}return result};var keys=!nativeKeys?shimKeys:function(object){if(!isObject(object)){return[]}return nativeKeys(object)};var htmlEscapes={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};var htmlUnescapes=invert(htmlEscapes);var reEscapedHtml=RegExp("("+keys(htmlUnescapes).join("|")+")","g"),reUnescapedHtml=RegExp("["+keys(htmlEscapes).join("")+"]","g");var assign=function(object,source,guard){var index,iterable=object,result=iterable;if(!iterable)return result;var args=arguments,argsIndex=0,argsLength=typeof guard=="number"?2:args.length;if(argsLength>3&&typeof args[argsLength-2]=="function"){var callback=baseCreateCallback(args[--argsLength-1],args[argsLength--],2)}else if(argsLength>2&&typeof args[argsLength-1]=="function"){callback=args[--argsLength]}while(++argsIndex<argsLength){iterable=args[argsIndex];if(iterable&&objectTypes[typeof iterable]){var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];result[index]=callback?callback(result[index],iterable[index]):iterable[index]}}}return result};function clone(value,isDeep,callback,thisArg){if(typeof isDeep!="boolean"&&isDeep!=null){thisArg=callback;callback=isDeep;isDeep=false}return baseClone(value,isDeep,typeof callback=="function"&&baseCreateCallback(callback,thisArg,1))}function cloneDeep(value,callback,thisArg){return baseClone(value,true,typeof callback=="function"&&baseCreateCallback(callback,thisArg,1))}function create(prototype,properties){var result=baseCreate(prototype);return properties?assign(result,properties):result}var defaults=function(object,source,guard){var index,iterable=object,result=iterable;if(!iterable)return result;var args=arguments,argsIndex=0,argsLength=typeof guard=="number"?2:args.length;while(++argsIndex<argsLength){iterable=args[argsIndex];if(iterable&&objectTypes[typeof iterable]){var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];if(typeof result[index]=="undefined")result[index]=iterable[index]}}}return result};function findKey(object,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forOwn(object,function(value,key,object){if(callback(value,key,object)){result=key;return false}});return result}function findLastKey(object,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forOwnRight(object,function(value,key,object){if(callback(value,key,object)){result=key;return false}});return result}var forIn=function(collection,callback,thisArg){var index,iterable=collection,result=iterable;if(!iterable)return result;if(!objectTypes[typeof iterable])return result;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);for(index in iterable){if(callback(iterable[index],index,collection)===false)return result}return result};function forInRight(object,callback,thisArg){var pairs=[];forIn(object,function(value,key){pairs.push(key,value)});var length=pairs.length;callback=baseCreateCallback(callback,thisArg,3);while(length--){if(callback(pairs[length--],pairs[length],object)===false){break}}return object}var forOwn=function(collection,callback,thisArg){var index,iterable=collection,result=iterable;if(!iterable)return result;if(!objectTypes[typeof iterable])return result;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];if(callback(iterable[index],index,collection)===false)return result}return result};function forOwnRight(object,callback,thisArg){var props=keys(object),length=props.length;callback=baseCreateCallback(callback,thisArg,3);while(length--){var key=props[length];if(callback(object[key],key,object)===false){break}}return object}function functions(object){var result=[];forIn(object,function(value,key){if(isFunction(value)){result.push(key)}});return result.sort()}function has(object,key){return object?hasOwnProperty.call(object,key):false}function invert(object){var index=-1,props=keys(object),length=props.length,result={};while(++index<length){var key=props[index]; result[object[key]]=key}return result}function isBoolean(value){return value===true||value===false||value&&typeof value=="object"&&toString.call(value)==boolClass||false}function isDate(value){return value&&typeof value=="object"&&toString.call(value)==dateClass||false}function isElement(value){return value&&value.nodeType===1||false}function isEmpty(value){var result=true;if(!value){return result}var className=toString.call(value),length=value.length;if(className==arrayClass||className==stringClass||className==argsClass||className==objectClass&&typeof length=="number"&&isFunction(value.splice)){return!length}forOwn(value,function(){return result=false});return result}function isEqual(a,b,callback,thisArg){return baseIsEqual(a,b,typeof callback=="function"&&baseCreateCallback(callback,thisArg,2))}function isFinite(value){return nativeIsFinite(value)&&!nativeIsNaN(parseFloat(value))}function isFunction(value){return typeof value=="function"}function isObject(value){return!!(value&&objectTypes[typeof value])}function isNaN(value){return isNumber(value)&&value!=+value}function isNull(value){return value===null}function isNumber(value){return typeof value=="number"||value&&typeof value=="object"&&toString.call(value)==numberClass||false}var isPlainObject=!getPrototypeOf?shimIsPlainObject:function(value){if(!(value&&toString.call(value)==objectClass)){return false}var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)};function isRegExp(value){return value&&typeof value=="object"&&toString.call(value)==regexpClass||false}function isString(value){return typeof value=="string"||value&&typeof value=="object"&&toString.call(value)==stringClass||false}function isUndefined(value){return typeof value=="undefined"}function mapValues(object,callback,thisArg){var result={};callback=lodash.createCallback(callback,thisArg,3);forOwn(object,function(value,key,object){result[key]=callback(value,key,object)});return result}function merge(object){var args=arguments,length=2;if(!isObject(object)){return object}if(typeof args[2]!="number"){length=args.length}if(length>3&&typeof args[length-2]=="function"){var callback=baseCreateCallback(args[--length-1],args[length--],2)}else if(length>2&&typeof args[length-1]=="function"){callback=args[--length]}var sources=slice(arguments,1,length),index=-1,stackA=getArray(),stackB=getArray();while(++index<length){baseMerge(object,sources[index],callback,stackA,stackB)}releaseArray(stackA);releaseArray(stackB);return object}function omit(object,callback,thisArg){var result={};if(typeof callback!="function"){var props=[];forIn(object,function(value,key){props.push(key)});props=baseDifference(props,baseFlatten(arguments,true,false,1));var index=-1,length=props.length;while(++index<length){var key=props[index];result[key]=object[key]}}else{callback=lodash.createCallback(callback,thisArg,3);forIn(object,function(value,key,object){if(!callback(value,key,object)){result[key]=value}})}return result}function pairs(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){var key=props[index];result[index]=[key,object[key]]}return result}function pick(object,callback,thisArg){var result={};if(typeof callback!="function"){var index=-1,props=baseFlatten(arguments,true,false,1),length=isObject(object)?props.length:0;while(++index<length){var key=props[index];if(key in object){result[key]=object[key]}}}else{callback=lodash.createCallback(callback,thisArg,3);forIn(object,function(value,key,object){if(callback(value,key,object)){result[key]=value}})}return result}function transform(object,callback,accumulator,thisArg){var isArr=isArray(object);if(accumulator==null){if(isArr){accumulator=[]}else{var ctor=object&&object.constructor,proto=ctor&&ctor.prototype;accumulator=baseCreate(proto)}}if(callback){callback=lodash.createCallback(callback,thisArg,4);(isArr?forEach:forOwn)(object,function(value,index,object){return callback(accumulator,value,index,object)})}return accumulator}function values(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){result[index]=object[props[index]]}return result}function at(collection){var args=arguments,index=-1,props=baseFlatten(args,true,false,1),length=args[2]&&args[2][args[1]]===collection?1:props.length,result=Array(length);while(++index<length){result[index]=collection[props[index]]}return result}function contains(collection,target,fromIndex){var index=-1,indexOf=getIndexOf(),length=collection?collection.length:0,result=false;fromIndex=(fromIndex<0?nativeMax(0,length+fromIndex):fromIndex)||0;if(isArray(collection)){result=indexOf(collection,target,fromIndex)>-1}else if(typeof length=="number"){result=(isString(collection)?collection.indexOf(target,fromIndex):indexOf(collection,target,fromIndex))>-1}else{forOwn(collection,function(value){if(++index>=fromIndex){return!(result=value===target)}})}return result}var countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key]++:result[key]=1});function every(collection,callback,thisArg){var result=true;callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){if(!(result=!!callback(collection[index],index,collection))){break}}}else{forOwn(collection,function(value,index,collection){return result=!!callback(value,index,collection)})}return result}function filter(collection,callback,thisArg){var result=[];callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];if(callback(value,index,collection)){result.push(value)}}}else{forOwn(collection,function(value,index,collection){if(callback(value,index,collection)){result.push(value)}})}return result}function find(collection,callback,thisArg){callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];if(callback(value,index,collection)){return value}}}else{var result;forOwn(collection,function(value,index,collection){if(callback(value,index,collection)){result=value;return false}});return result}}function findLast(collection,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forEachRight(collection,function(value,index,collection){if(callback(value,index,collection)){result=value;return false}});return result}function forEach(collection,callback,thisArg){var index=-1,length=collection?collection.length:0;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);if(typeof length=="number"){while(++index<length){if(callback(collection[index],index,collection)===false){break}}}else{forOwn(collection,callback)}return collection}function forEachRight(collection,callback,thisArg){var length=collection?collection.length:0;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);if(typeof length=="number"){while(length--){if(callback(collection[length],length,collection)===false){break}}}else{var props=keys(collection);length=props.length;forOwn(collection,function(value,key,collection){key=props?props[--length]:--length;return callback(collection[key],key,collection)})}return collection}var groupBy=createAggregator(function(result,value,key){(hasOwnProperty.call(result,key)?result[key]:result[key]=[]).push(value)});var indexBy=createAggregator(function(result,value,key){result[key]=value});function invoke(collection,methodName){var args=slice(arguments,2),index=-1,isFunc=typeof methodName=="function",length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);forEach(collection,function(value){result[++index]=(isFunc?methodName:value[methodName]).apply(value,args)});return result}function map(collection,callback,thisArg){var index=-1,length=collection?collection.length:0;callback=lodash.createCallback(callback,thisArg,3);if(typeof length=="number"){var result=Array(length);while(++index<length){result[index]=callback(collection[index],index,collection)}}else{result=[];forOwn(collection,function(value,key,collection){result[++index]=callback(value,key,collection)})}return result}function max(collection,callback,thisArg){var computed=-Infinity,result=computed;if(typeof callback!="function"&&thisArg&&thisArg[callback]===collection){callback=null}if(callback==null&&isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];if(value>result){result=value}}}else{callback=callback==null&&isString(collection)?charAtCallback:lodash.createCallback(callback,thisArg,3);forEach(collection,function(value,index,collection){var current=callback(value,index,collection);if(current>computed){computed=current;result=value}})}return result}function min(collection,callback,thisArg){var computed=Infinity,result=computed;if(typeof callback!="function"&&thisArg&&thisArg[callback]===collection){callback=null}if(callback==null&&isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];if(value<result){result=value}}}else{callback=callback==null&&isString(collection)?charAtCallback:lodash.createCallback(callback,thisArg,3);forEach(collection,function(value,index,collection){var current=callback(value,index,collection);if(current<computed){computed=current;result=value}})}return result}var pluck=map;function reduce(collection,callback,accumulator,thisArg){if(!collection)return accumulator;var noaccum=arguments.length<3;callback=lodash.createCallback(callback,thisArg,4);var index=-1,length=collection.length;if(typeof length=="number"){if(noaccum){accumulator=collection[++index]}while(++index<length){accumulator=callback(accumulator,collection[index],index,collection)}}else{forOwn(collection,function(value,index,collection){accumulator=noaccum?(noaccum=false,value):callback(accumulator,value,index,collection)})}return accumulator}function reduceRight(collection,callback,accumulator,thisArg){var noaccum=arguments.length<3;callback=lodash.createCallback(callback,thisArg,4);forEachRight(collection,function(value,index,collection){accumulator=noaccum?(noaccum=false,value):callback(accumulator,value,index,collection)});return accumulator}function reject(collection,callback,thisArg){callback=lodash.createCallback(callback,thisArg,3);return filter(collection,function(value,index,collection){return!callback(value,index,collection)})}function sample(collection,n,guard){if(collection&&typeof collection.length!="number"){collection=values(collection)}if(n==null||guard){return collection?collection[baseRandom(0,collection.length-1)]:undefined}var result=shuffle(collection);result.length=nativeMin(nativeMax(0,n),result.length);return result}function shuffle(collection){var index=-1,length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);forEach(collection,function(value){var rand=baseRandom(0,++index);result[index]=result[rand];result[rand]=value});return result}function size(collection){var length=collection?collection.length:0;return typeof length=="number"?length:keys(collection).length}function some(collection,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){if(result=callback(collection[index],index,collection)){break}}}else{forOwn(collection,function(value,index,collection){return!(result=callback(value,index,collection))})}return!!result}function sortBy(collection,callback,thisArg){var index=-1,isArr=isArray(callback),length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);if(!isArr){callback=lodash.createCallback(callback,thisArg,3)}forEach(collection,function(value,key,collection){var object=result[++index]=getObject();if(isArr){object.criteria=map(callback,function(key){return value[key]})}else{(object.criteria=getArray())[0]=callback(value,key,collection)}object.index=index;object.value=value});length=result.length;result.sort(compareAscending);while(length--){var object=result[length];result[length]=object.value;if(!isArr){releaseArray(object.criteria)}releaseObject(object)}return result}function toArray(collection){if(collection&&typeof collection.length=="number"){return slice(collection)}return values(collection)}var where=filter;function compact(array){var index=-1,length=array?array.length:0,result=[];while(++index<length){var value=array[index];if(value){result.push(value)}}return result}function difference(array){return baseDifference(array,baseFlatten(arguments,true,true,1))}function findIndex(array,callback,thisArg){var index=-1,length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(++index<length){if(callback(array[index],index,array)){return index}}return-1}function findLastIndex(array,callback,thisArg){var length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(length--){if(callback(array[length],length,array)){return length}}return-1}function first(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=-1;callback=lodash.createCallback(callback,thisArg,3);while(++index<length&&callback(array[index],index,array)){n++}}else{n=callback;if(n==null||thisArg){return array?array[0]:undefined}}return slice(array,0,nativeMin(nativeMax(0,n),length))}function flatten(array,isShallow,callback,thisArg){if(typeof isShallow!="boolean"&&isShallow!=null){thisArg=callback;callback=typeof isShallow!="function"&&thisArg&&thisArg[isShallow]===array?null:isShallow;isShallow=false}if(callback!=null){array=map(array,callback,thisArg)}return baseFlatten(array,isShallow)}function indexOf(array,value,fromIndex){if(typeof fromIndex=="number"){var length=array?array.length:0;fromIndex=fromIndex<0?nativeMax(0,length+fromIndex):fromIndex||0}else if(fromIndex){var index=sortedIndex(array,value);return array[index]===value?index:-1}return baseIndexOf(array,value,fromIndex)}function initial(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=length;callback=lodash.createCallback(callback,thisArg,3);while(index--&&callback(array[index],index,array)){n++}}else{n=callback==null||thisArg?1:callback||n}return slice(array,0,nativeMin(nativeMax(0,length-n),length))}function intersection(){var args=[],argsIndex=-1,argsLength=arguments.length,caches=getArray(),indexOf=getIndexOf(),trustIndexOf=indexOf===baseIndexOf,seen=getArray();while(++argsIndex<argsLength){var value=arguments[argsIndex];if(isArray(value)||isArguments(value)){args.push(value);caches.push(trustIndexOf&&value.length>=largeArraySize&&createCache(argsIndex?args[argsIndex]:seen))}}var array=args[0],index=-1,length=array?array.length:0,result=[];outer:while(++index<length){var cache=caches[0];value=array[index];if((cache?cacheIndexOf(cache,value):indexOf(seen,value))<0){argsIndex=argsLength;(cache||seen).push(value);while(--argsIndex){cache=caches[argsIndex];if((cache?cacheIndexOf(cache,value):indexOf(args[argsIndex],value))<0){continue outer}}result.push(value)}}while(argsLength--){cache=caches[argsLength];if(cache){releaseObject(cache)}}releaseArray(caches);releaseArray(seen);return result}function last(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=length;callback=lodash.createCallback(callback,thisArg,3);while(index--&&callback(array[index],index,array)){n++}}else{n=callback;if(n==null||thisArg){return array?array[length-1]:undefined}}return slice(array,nativeMax(0,length-n))}function lastIndexOf(array,value,fromIndex){var index=array?array.length:0;if(typeof fromIndex=="number"){index=(fromIndex<0?nativeMax(0,index+fromIndex):nativeMin(fromIndex,index-1))+1}while(index--){if(array[index]===value){return index}}return-1}function pull(array){var args=arguments,argsIndex=0,argsLength=args.length,length=array?array.length:0;while(++argsIndex<argsLength){var index=-1,value=args[argsIndex];while(++index<length){if(array[index]===value){splice.call(array,index--,1);length--}}}return array}function range(start,end,step){start=+start||0;step=typeof step=="number"?step:+step||1;if(end==null){end=start;start=0}var index=-1,length=nativeMax(0,ceil((end-start)/(step||1))),result=Array(length);while(++index<length){result[index]=start;start+=step}return result}function remove(array,callback,thisArg){var index=-1,length=array?array.length:0,result=[];callback=lodash.createCallback(callback,thisArg,3);while(++index<length){var value=array[index];if(callback(value,index,array)){result.push(value);splice.call(array,index--,1);length--}}return result}function rest(array,callback,thisArg){if(typeof callback!="number"&&callback!=null){var n=0,index=-1,length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(++index<length&&callback(array[index],index,array)){n++}}else{n=callback==null||thisArg?1:nativeMax(0,callback)}return slice(array,n)}function sortedIndex(array,value,callback,thisArg){var low=0,high=array?array.length:low;callback=callback?lodash.createCallback(callback,thisArg,1):identity;value=callback(value);while(low<high){var mid=low+high>>>1;callback(array[mid])<value?low=mid+1:high=mid}return low}function union(){return baseUniq(baseFlatten(arguments,true,true))}function uniq(array,isSorted,callback,thisArg){if(typeof isSorted!="boolean"&&isSorted!=null){thisArg=callback;callback=typeof isSorted!="function"&&thisArg&&thisArg[isSorted]===array?null:isSorted;isSorted=false}if(callback!=null){callback=lodash.createCallback(callback,thisArg,3)}return baseUniq(array,isSorted,callback)}function without(array){return baseDifference(array,slice(arguments,1))}function xor(){var index=-1,length=arguments.length;while(++index<length){var array=arguments[index];if(isArray(array)||isArguments(array)){var result=result?baseUniq(baseDifference(result,array).concat(baseDifference(array,result))):array}}return result||[]}function zip(){var array=arguments.length>1?arguments:arguments[0],index=-1,length=array?max(pluck(array,"length")):0,result=Array(length<0?0:length);while(++index<length){result[index]=pluck(array,index)}return result}function zipObject(keys,values){var index=-1,length=keys?keys.length:0,result={};if(!values&&length&&!isArray(keys[0])){values=[]}while(++index<length){var key=keys[index];if(values){result[key]=values[index]}else if(key){result[key[0]]=key[1]}}return result}function after(n,func){if(!isFunction(func)){throw new TypeError}return function(){if(--n<1){return func.apply(this,arguments)}}}function bind(func,thisArg){return arguments.length>2?createWrapper(func,17,slice(arguments,2),null,thisArg):createWrapper(func,1,null,null,thisArg)}function bindAll(object){var funcs=arguments.length>1?baseFlatten(arguments,true,false,1):functions(object),index=-1,length=funcs.length;while(++index<length){var key=funcs[index];object[key]=createWrapper(object[key],1,null,null,object)}return object}function bindKey(object,key){return arguments.length>2?createWrapper(key,19,slice(arguments,2),null,object):createWrapper(key,3,null,null,object)}function compose(){var funcs=arguments,length=funcs.length;while(length--){if(!isFunction(funcs[length])){throw new TypeError}}return function(){var args=arguments,length=funcs.length;while(length--){args=[funcs[length].apply(this,args)]}return args[0]}}function curry(func,arity){arity=typeof arity=="number"?arity:+arity||func.length;return createWrapper(func,4,null,null,null,arity)}function debounce(func,wait,options){var args,maxTimeoutId,result,stamp,thisArg,timeoutId,trailingCall,lastCalled=0,maxWait=false,trailing=true;if(!isFunction(func)){throw new TypeError}wait=nativeMax(0,wait)||0;if(options===true){var leading=true;trailing=false}else if(isObject(options)){leading=options.leading;maxWait="maxWait"in options&&(nativeMax(wait,options.maxWait)||0);trailing="trailing"in options?options.trailing:trailing}var delayed=function(){var remaining=wait-(now()-stamp);if(remaining<=0){if(maxTimeoutId){clearTimeout(maxTimeoutId)}var isCalled=trailingCall;maxTimeoutId=timeoutId=trailingCall=undefined;if(isCalled){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}}else{timeoutId=setTimeout(delayed,remaining)}};var maxDelayed=function(){if(timeoutId){clearTimeout(timeoutId)}maxTimeoutId=timeoutId=trailingCall=undefined;if(trailing||maxWait!==wait){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}};return function(){args=arguments;stamp=now();thisArg=this;trailingCall=trailing&&(timeoutId||!leading);if(maxWait===false){var leadingCall=leading&&!timeoutId}else{if(!maxTimeoutId&&!leading){lastCalled=stamp}var remaining=maxWait-(stamp-lastCalled),isCalled=remaining<=0;if(isCalled){if(maxTimeoutId){maxTimeoutId=clearTimeout(maxTimeoutId)}lastCalled=stamp;result=func.apply(thisArg,args)}else if(!maxTimeoutId){maxTimeoutId=setTimeout(maxDelayed,remaining)}}if(isCalled&&timeoutId){timeoutId=clearTimeout(timeoutId)}else if(!timeoutId&&wait!==maxWait){timeoutId=setTimeout(delayed,wait)}if(leadingCall){isCalled=true;result=func.apply(thisArg,args)}if(isCalled&&!timeoutId&&!maxTimeoutId){args=thisArg=null}return result}}function defer(func){if(!isFunction(func)){throw new TypeError}var args=slice(arguments,1);return setTimeout(function(){func.apply(undefined,args)},1)}function delay(func,wait){if(!isFunction(func)){throw new TypeError}var args=slice(arguments,2);return setTimeout(function(){func.apply(undefined,args)},wait)}function memoize(func,resolver){if(!isFunction(func)){throw new TypeError}var memoized=function(){var cache=memoized.cache,key=resolver?resolver.apply(this,arguments):keyPrefix+arguments[0];return hasOwnProperty.call(cache,key)?cache[key]:cache[key]=func.apply(this,arguments)};memoized.cache={};return memoized}function once(func){var ran,result;if(!isFunction(func)){throw new TypeError}return function(){if(ran){return result}ran=true;result=func.apply(this,arguments);func=null;return result}}function partial(func){return createWrapper(func,16,slice(arguments,1))}function partialRight(func){return createWrapper(func,32,null,slice(arguments,1))}function throttle(func,wait,options){var leading=true,trailing=true;if(!isFunction(func)){throw new TypeError}if(options===false){leading=false}else if(isObject(options)){leading="leading"in options?options.leading:leading;trailing="trailing"in options?options.trailing:trailing}debounceOptions.leading=leading;debounceOptions.maxWait=wait;debounceOptions.trailing=trailing;return debounce(func,wait,debounceOptions)}function wrap(value,wrapper){return createWrapper(wrapper,16,[value])}function constant(value){return function(){return value}}function createCallback(func,thisArg,argCount){var type=typeof func;if(func==null||type=="function"){return baseCreateCallback(func,thisArg,argCount)}if(type!="object"){return property(func)}var props=keys(func),key=props[0],a=func[key];if(props.length==1&&a===a&&!isObject(a)){return function(object){var b=object[key];return a===b&&(a!==0||1/a==1/b)}}return function(object){var length=props.length,result=false;while(length--){if(!(result=baseIsEqual(object[props[length]],func[props[length]],null,true))){break}}return result}}function escape(string){return string==null?"":String(string).replace(reUnescapedHtml,escapeHtmlChar)}function identity(value){return value}function mixin(object,source,options){var chain=true,methodNames=source&&functions(source);if(!source||!options&&!methodNames.length){if(options==null){options=source}ctor=lodashWrapper;source=object;object=lodash;methodNames=functions(source)}if(options===false){chain=false}else if(isObject(options)&&"chain"in options){chain=options.chain}var ctor=object,isFunc=isFunction(ctor);forEach(methodNames,function(methodName){var func=object[methodName]=source[methodName];if(isFunc){ctor.prototype[methodName]=function(){var chainAll=this.__chain__,value=this.__wrapped__,args=[value];push.apply(args,arguments);var result=func.apply(object,args);if(chain||chainAll){if(value===result&&isObject(result)){return this}result=new ctor(result);result.__chain__=chainAll}return result}}})}function noConflict(){context._=oldDash;return this}function noop(){}var now=isNative(now=Date.now)&&now||function(){return(new Date).getTime()};var parseInt=nativeParseInt(whitespace+"08")==8?nativeParseInt:function(value,radix){return nativeParseInt(isString(value)?value.replace(reLeadingSpacesAndZeros,""):value,radix||0)};function property(key){return function(object){return object[key]}}function random(min,max,floating){var noMin=min==null,noMax=max==null;if(floating==null){if(typeof min=="boolean"&&noMax){floating=min;min=1}else if(!noMax&&typeof max=="boolean"){floating=max;noMax=true}}if(noMin&&noMax){max=1}min=+min||0;if(noMax){max=min;min=0}else{max=+max||0}if(floating||min%1||max%1){var rand=nativeRandom();return nativeMin(min+rand*(max-min+parseFloat("1e-"+((rand+"").length-1))),max)}return baseRandom(min,max)}function result(object,key){if(object){var value=object[key];return isFunction(value)?object[key]():value}}function template(text,data,options){var settings=lodash.templateSettings;text=String(text||"");options=defaults({},options,settings);var imports=defaults({},options.imports,settings.imports),importsKeys=keys(imports),importsValues=values(imports);var isEvaluating,index=0,interpolate=options.interpolate||reNoMatch,source="__p += '";var reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g");text.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){interpolateValue||(interpolateValue=esTemplateValue);source+=text.slice(index,offset).replace(reUnescapedString,escapeStringChar);if(escapeValue){source+="' +\n__e("+escapeValue+") +\n'"}if(evaluateValue){isEvaluating=true;source+="';\n"+evaluateValue+";\n__p += '"}if(interpolateValue){source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"}index=offset+match.length;return match});source+="';\n";var variable=options.variable,hasVariable=variable;if(!hasVariable){variable="obj";source="with ("+variable+") {\n"+source+"\n}\n"}source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;");source="function("+variable+") {\n"+(hasVariable?"":variable+" || ("+variable+" = {});\n")+"var __t, __p = '', __e = _.escape"+(isEvaluating?", __j = Array.prototype.join;\n"+"function print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var sourceURL="\n/*\n//# sourceURL="+(options.sourceURL||"/lodash/template/source["+templateCounter++ +"]")+"\n*/";try{var result=Function(importsKeys,"return "+source+sourceURL).apply(undefined,importsValues)}catch(e){e.source=source;throw e}if(data){return result(data)}result.source=source;return result}function times(n,callback,thisArg){n=(n=+n)>-1?n:0;var index=-1,result=Array(n);callback=baseCreateCallback(callback,thisArg,1);while(++index<n){result[index]=callback(index)}return result}function unescape(string){return string==null?"":String(string).replace(reEscapedHtml,unescapeHtmlChar)}function uniqueId(prefix){var id=++idCounter;return String(prefix==null?"":prefix)+id}function chain(value){value=new lodashWrapper(value);value.__chain__=true;return value}function tap(value,interceptor){interceptor(value);return value}function wrapperChain(){this.__chain__=true;return this}function wrapperToString(){return String(this.__wrapped__)}function wrapperValueOf(){return this.__wrapped__}lodash.after=after;lodash.assign=assign;lodash.at=at;lodash.bind=bind;lodash.bindAll=bindAll;lodash.bindKey=bindKey;lodash.chain=chain;lodash.compact=compact;lodash.compose=compose;lodash.constant=constant;lodash.countBy=countBy;lodash.create=create;lodash.createCallback=createCallback;lodash.curry=curry;lodash.debounce=debounce;lodash.defaults=defaults;lodash.defer=defer;lodash.delay=delay;lodash.difference=difference;lodash.filter=filter;lodash.flatten=flatten;lodash.forEach=forEach;lodash.forEachRight=forEachRight;lodash.forIn=forIn;lodash.forInRight=forInRight;lodash.forOwn=forOwn;lodash.forOwnRight=forOwnRight;lodash.functions=functions;lodash.groupBy=groupBy;lodash.indexBy=indexBy;lodash.initial=initial;lodash.intersection=intersection;lodash.invert=invert;lodash.invoke=invoke;lodash.keys=keys;lodash.map=map;lodash.mapValues=mapValues;lodash.max=max;lodash.memoize=memoize;lodash.merge=merge;lodash.min=min;lodash.omit=omit;lodash.once=once;lodash.pairs=pairs;lodash.partial=partial;lodash.partialRight=partialRight;lodash.pick=pick;lodash.pluck=pluck;lodash.property=property;lodash.pull=pull;lodash.range=range;lodash.reject=reject;lodash.remove=remove;lodash.rest=rest;lodash.shuffle=shuffle;lodash.sortBy=sortBy;lodash.tap=tap;lodash.throttle=throttle;lodash.times=times;lodash.toArray=toArray;lodash.transform=transform;lodash.union=union;lodash.uniq=uniq;lodash.values=values;lodash.where=where;lodash.without=without;lodash.wrap=wrap;lodash.xor=xor;lodash.zip=zip;lodash.zipObject=zipObject;lodash.collect=map;lodash.drop=rest;lodash.each=forEach;lodash.eachRight=forEachRight;lodash.extend=assign;lodash.methods=functions;lodash.object=zipObject;lodash.select=filter;lodash.tail=rest;lodash.unique=uniq;lodash.unzip=zip;mixin(lodash);lodash.clone=clone;lodash.cloneDeep=cloneDeep;lodash.contains=contains;lodash.escape=escape;lodash.every=every;lodash.find=find;lodash.findIndex=findIndex;lodash.findKey=findKey;lodash.findLast=findLast;lodash.findLastIndex=findLastIndex;lodash.findLastKey=findLastKey;lodash.has=has;lodash.identity=identity;lodash.indexOf=indexOf;lodash.isArguments=isArguments;lodash.isArray=isArray;lodash.isBoolean=isBoolean;lodash.isDate=isDate;lodash.isElement=isElement;lodash.isEmpty=isEmpty;lodash.isEqual=isEqual;lodash.isFinite=isFinite;lodash.isFunction=isFunction;lodash.isNaN=isNaN;lodash.isNull=isNull;lodash.isNumber=isNumber;lodash.isObject=isObject;lodash.isPlainObject=isPlainObject;lodash.isRegExp=isRegExp;lodash.isString=isString;lodash.isUndefined=isUndefined;lodash.lastIndexOf=lastIndexOf;lodash.mixin=mixin;lodash.noConflict=noConflict;lodash.noop=noop;lodash.now=now;lodash.parseInt=parseInt;lodash.random=random;lodash.reduce=reduce;lodash.reduceRight=reduceRight;lodash.result=result;lodash.runInContext=runInContext;lodash.size=size;lodash.some=some;lodash.sortedIndex=sortedIndex;lodash.template=template;lodash.unescape=unescape;lodash.uniqueId=uniqueId;lodash.all=every;lodash.any=some;lodash.detect=find;lodash.findWhere=find;lodash.foldl=reduce;lodash.foldr=reduceRight;lodash.include=contains;lodash.inject=reduce;mixin(function(){var source={};forOwn(lodash,function(func,methodName){if(!lodash.prototype[methodName]){source[methodName]=func}});return source}(),false);lodash.first=first;lodash.last=last;lodash.sample=sample;lodash.take=first;lodash.head=first;forOwn(lodash,function(func,methodName){var callbackable=methodName!=="sample";if(!lodash.prototype[methodName]){lodash.prototype[methodName]=function(n,guard){var chainAll=this.__chain__,result=func(this.__wrapped__,n,guard);return!chainAll&&(n==null||guard&&!(callbackable&&typeof n=="function"))?result:new lodashWrapper(result,chainAll)}}});lodash.VERSION="2.4.1";lodash.prototype.chain=wrapperChain;lodash.prototype.toString=wrapperToString;lodash.prototype.value=wrapperValueOf;lodash.prototype.valueOf=wrapperValueOf; forEach(["join","pop","shift"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){var chainAll=this.__chain__,result=func.apply(this.__wrapped__,arguments);return chainAll?new lodashWrapper(result,chainAll):result}});forEach(["push","reverse","sort","unshift"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){func.apply(this.__wrapped__,arguments);return this}});forEach(["concat","slice","splice"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){return new lodashWrapper(func.apply(this.__wrapped__,arguments),this.__chain__)}});return lodash}var _=runInContext();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root._=_;define(function(){return _})}else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=_)._=_}else{freeExports._=_}}else{root._=_}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],110:[function(require,module,exports){"use strict";var originalObject=Object;var originalDefProp=Object.defineProperty;var originalCreate=Object.create;function defProp(obj,name,value){if(originalDefProp)try{originalDefProp.call(originalObject,obj,name,{value:value})}catch(definePropertyIsBrokenInIE8){obj[name]=value}else{obj[name]=value}}function makeSafeToCall(fun){if(fun){defProp(fun,"call",fun.call);defProp(fun,"apply",fun.apply)}return fun}makeSafeToCall(originalDefProp);makeSafeToCall(originalCreate);var hasOwn=makeSafeToCall(Object.prototype.hasOwnProperty);var numToStr=makeSafeToCall(Number.prototype.toString);var strSlice=makeSafeToCall(String.prototype.slice);var cloner=function(){};function create(prototype){if(originalCreate){return originalCreate.call(originalObject,prototype)}cloner.prototype=prototype||null;return new cloner}var rand=Math.random;var uniqueKeys=create(null);function makeUniqueKey(){do var uniqueKey=internString(strSlice.call(numToStr.call(rand(),36),2));while(hasOwn.call(uniqueKeys,uniqueKey));return uniqueKeys[uniqueKey]=uniqueKey}function internString(str){var obj={};obj[str]=true;return Object.keys(obj)[0]}defProp(exports,"makeUniqueKey",makeUniqueKey);var originalGetOPNs=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function getOwnPropertyNames(object){for(var names=originalGetOPNs(object),src=0,dst=0,len=names.length;src<len;++src){if(!hasOwn.call(uniqueKeys,names[src])){if(src>dst){names[dst]=names[src]}++dst}}names.length=dst;return names};function defaultCreatorFn(object){return create(null)}function makeAccessor(secretCreatorFn){var brand=makeUniqueKey();var passkey=create(null);secretCreatorFn=secretCreatorFn||defaultCreatorFn;function register(object){var secret;function vault(key,forget){if(key===passkey){return forget?secret=null:secret||(secret=secretCreatorFn(object))}}defProp(object,brand,vault)}function accessor(object){if(!hasOwn.call(object,brand))register(object);return object[brand](passkey)}accessor.forget=function(object){if(hasOwn.call(object,brand))object[brand](passkey,true)};return accessor}defProp(exports,"makeAccessor",makeAccessor)},{}],111:[function(require,module,exports){var regenerate=require("regenerate");exports.REGULAR={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,65535),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,65535),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)};exports.UNICODE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)};exports.UNICODE_IGNORE_CASE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:113}],112:[function(require,module,exports){module.exports={75:8490,83:383,107:8490,115:383,181:924,197:8491,383:83,452:453,453:452,455:456,456:455,458:459,459:458,497:498,498:497,837:8126,914:976,917:1013,920:1012,921:8126,922:1008,924:181,928:982,929:1009,931:962,934:981,937:8486,962:931,976:914,977:1012,981:934,982:928,1008:922,1009:929,1012:[920,977],1013:917,7776:7835,7835:7776,8126:[837,921],8486:937,8490:75,8491:197,66560:66600,66561:66601,66562:66602,66563:66603,66564:66604,66565:66605,66566:66606,66567:66607,66568:66608,66569:66609,66570:66610,66571:66611,66572:66612,66573:66613,66574:66614,66575:66615,66576:66616,66577:66617,66578:66618,66579:66619,66580:66620,66581:66621,66582:66622,66583:66623,66584:66624,66585:66625,66586:66626,66587:66627,66588:66628,66589:66629,66590:66630,66591:66631,66592:66632,66593:66633,66594:66634,66595:66635,66596:66636,66597:66637,66598:66638,66599:66639,66600:66560,66601:66561,66602:66562,66603:66563,66604:66564,66605:66565,66606:66566,66607:66567,66608:66568,66609:66569,66610:66570,66611:66571,66612:66572,66613:66573,66614:66574,66615:66575,66616:66576,66617:66577,66618:66578,66619:66579,66620:66580,66621:66581,66622:66582,66623:66583,66624:66584,66625:66585,66626:66586,66627:66587,66628:66588,66629:66589,66630:66590,66631:66591,66632:66592,66633:66593,66634:66594,66635:66595,66636:66596,66637:66597,66638:66598,66639:66599,71840:71872,71841:71873,71842:71874,71843:71875,71844:71876,71845:71877,71846:71878,71847:71879,71848:71880,71849:71881,71850:71882,71851:71883,71852:71884,71853:71885,71854:71886,71855:71887,71856:71888,71857:71889,71858:71890,71859:71891,71860:71892,71861:71893,71862:71894,71863:71895,71864:71896,71865:71897,71866:71898,71867:71899,71868:71900,71869:71901,71870:71902,71871:71903,71872:71840,71873:71841,71874:71842,71875:71843,71876:71844,71877:71845,71878:71846,71879:71847,71880:71848,71881:71849,71882:71850,71883:71851,71884:71852,71885:71853,71886:71854,71887:71855,71888:71856,71889:71857,71890:71858,71891:71859,71892:71860,71893:71861,71894:71862,71895:71863,71896:71864,71897:71865,71898:71866,71899:71867,71900:71868,71901:71869,71902:71870,71903:71871}},{}],113:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var ERRORS={rangeOrder:"A range’s `stop` value must be greater than or equal "+"to the `start` value.",codePointRange:"Invalid code point value. Code points range from "+"U+000000 to U+10FFFF."};var HIGH_SURROGATE_MIN=55296;var HIGH_SURROGATE_MAX=56319;var LOW_SURROGATE_MIN=56320;var LOW_SURROGATE_MAX=57343;var regexNull=/\\x00([^0123456789]|$)/g;var object={};var hasOwnProperty=object.hasOwnProperty;var extend=function(destination,source){var key;for(key in source){if(hasOwnProperty.call(source,key)){destination[key]=source[key]}}return destination};var forEach=function(array,callback){var index=-1;var length=array.length;while(++index<length){callback(array[index],index)}};var toString=object.toString;var isArray=function(value){return toString.call(value)=="[object Array]"};var isNumber=function(value){return typeof value=="number"||toString.call(value)=="[object Number]"};var zeroes="0000";var pad=function(number,totalCharacters){var string=String(number);return string.length<totalCharacters?(zeroes+string).slice(-totalCharacters):string};var hex=function(number){return Number(number).toString(16).toUpperCase()};var slice=[].slice;var dataFromCodePoints=function(codePoints){var index=-1;var length=codePoints.length;var max=length-1;var result=[];var isStart=true;var tmp;var previous=0;while(++index<length){tmp=codePoints[index];if(isStart){result.push(tmp);previous=tmp;isStart=false}else{if(tmp==previous+1){if(index!=max){previous=tmp;continue}else{isStart=true;result.push(tmp+1)}}else{result.push(previous+1,tmp);previous=tmp}}}if(!isStart){result.push(tmp+1)}return result};var dataRemove=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){if(codePoint==start){if(end==start+1){data.splice(index,2);return data}else{data[index]=codePoint+1;return data}}else if(codePoint==end-1){data[index+1]=codePoint;return data}else{data.splice(index,2,start,codePoint,codePoint+1,end);return data}}index+=2}return data};var dataRemoveRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}var index=0;var start;var end;while(index<data.length){start=data[index];end=data[index+1]-1;if(start>rangeEnd){return data}if(rangeStart<=start&&rangeEnd>=end){data.splice(index,2);continue}if(rangeStart>=start&&rangeEnd<end){if(rangeStart==start){data[index]=rangeEnd+1;data[index+1]=end+1;return data}data.splice(index,2,start,rangeStart,rangeEnd+1,end+1);return data}if(rangeStart>=start&&rangeStart<=end){data[index+1]=rangeStart}else if(rangeEnd>=start&&rangeEnd<=end){data[index]=rangeEnd+1;return data}index+=2}return data};var dataAdd=function(data,codePoint){var index=0;var start;var end;var lastIndex=null;var length=data.length;if(codePoint<0||codePoint>1114111){throw RangeError(ERRORS.codePointRange)}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return data}if(codePoint==start-1){data[index]=codePoint;return data}if(start>codePoint){data.splice(lastIndex!=null?lastIndex+2:0,0,codePoint,codePoint+1);return data}if(codePoint==end){if(codePoint+1==data[index+2]){data.splice(index,4,start,data[index+3]);return data}data[index+1]=codePoint+1;return data}lastIndex=index;index+=2}data.push(codePoint,codePoint+1);return data};var dataAddData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataAdd(data,start)}else{data=dataAddRange(data,start,end)}index+=2}return data};var dataRemoveData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataRemove(data,start)}else{data=dataRemoveRange(data,start,end)}index+=2}return data};var dataAddRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}if(rangeStart<0||rangeStart>1114111||rangeEnd<0||rangeEnd>1114111){throw RangeError(ERRORS.codePointRange)}var index=0;var start;var end;var added=false;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(added){if(start==rangeEnd+1){data.splice(index-1,2);return data}if(start>rangeEnd){return data}if(start>=rangeStart&&start<=rangeEnd){if(end>rangeStart&&end-1<=rangeEnd){data.splice(index,2);index-=2}else{data.splice(index-1,2);index-=2}}}else if(start==rangeEnd+1){data[index]=rangeStart;return data}else if(start>rangeEnd){data.splice(index,0,rangeStart,rangeEnd+1);return data}else if(rangeStart>=start&&rangeStart<end&&rangeEnd+1<=end){return data}else if(rangeStart>=start&&rangeStart<end||end==rangeStart){data[index+1]=rangeEnd+1;added=true}else if(rangeStart<=start&&rangeEnd+1>=end){data[index]=rangeStart;data[index+1]=rangeEnd+1;added=true}index+=2}if(!added){data.push(rangeStart,rangeEnd+1)}return data};var dataContains=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return true}index+=2}return false};var dataIntersection=function(data,codePoints){var index=0;var length=codePoints.length;var codePoint;var result=[];while(index<length){codePoint=codePoints[index];if(dataContains(data,codePoint)){result.push(codePoint)}++index}return dataFromCodePoints(result)};var dataIsEmpty=function(data){return!data.length};var dataIsSingleton=function(data){return data.length==2&&data[0]+1==data[1]};var dataToArray=function(data){var index=0;var start;var end;var result=[];var length=data.length;while(index<length){start=data[index];end=data[index+1];while(start<end){result.push(start);++start}index+=2}return result};var floor=Math.floor;var highSurrogate=function(codePoint){return parseInt(floor((codePoint-65536)/1024)+HIGH_SURROGATE_MIN,10)};var lowSurrogate=function(codePoint){return parseInt((codePoint-65536)%1024+LOW_SURROGATE_MIN,10)};var stringFromCharCode=String.fromCharCode;var codePointToString=function(codePoint){var string;if(codePoint==9){string="\\t"}else if(codePoint==10){string="\\n"}else if(codePoint==12){string="\\f"}else if(codePoint==13){string="\\r"}else if(codePoint==92){string="\\\\"}else if(codePoint==36||codePoint>=40&&codePoint<=43||codePoint==45||codePoint==46||codePoint==63||codePoint>=91&&codePoint<=94||codePoint>=123&&codePoint<=125){string="\\"+stringFromCharCode(codePoint)}else if(codePoint>=32&&codePoint<=126){string=stringFromCharCode(codePoint)}else if(codePoint<=255){string="\\x"+pad(hex(codePoint),2)}else{string="\\u"+pad(hex(codePoint),4)}return string};var symbolToCodePoint=function(symbol){var length=symbol.length;var first=symbol.charCodeAt(0);var second;if(first>=HIGH_SURROGATE_MIN&&first<=HIGH_SURROGATE_MAX&&length>1){second=symbol.charCodeAt(1);return(first-HIGH_SURROGATE_MIN)*1024+second-LOW_SURROGATE_MIN+65536}return first};var createBMPCharacterClasses=function(data){var result="";var index=0;var start;var end;var length=data.length;if(dataIsSingleton(data)){return codePointToString(data[0])}while(index<length){start=data[index];end=data[index+1]-1;if(start==end){result+=codePointToString(start)}else if(start+1==end){result+=codePointToString(start)+codePointToString(end)}else{result+=codePointToString(start)+"-"+codePointToString(end)}index+=2}return"["+result+"]"};var splitAtBMP=function(data){var loneHighSurrogates=[];var bmp=[];var astral=[];var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1]-1;if(start<=65535&&end<=65535){if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){if(end<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,end+1)}else{loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);bmp.push(HIGH_SURROGATE_MAX+1,end+1)}}else if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,end+1)}else if(start<HIGH_SURROGATE_MIN&&end>HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1,end+1);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1)}else{bmp.push(start,end+1)}}else if(start<=65535&&end>65535){if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);bmp.push(HIGH_SURROGATE_MAX+1,65535+1)}else if(start<HIGH_SURROGATE_MIN){bmp.push(start,HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1,65535+1);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1)}else{bmp.push(start,65535+1)}astral.push(65535+1,end+1)}else{astral.push(start,end+1)}index+=2}return{loneHighSurrogates:loneHighSurrogates,bmp:bmp,astral:astral}};var optimizeSurrogateMappings=function(surrogateMappings){var result=[];var tmpLow=[];var addLow=false;var mapping;var nextMapping;var highSurrogates;var lowSurrogates;var nextHighSurrogates;var nextLowSurrogates;var index=-1;var length=surrogateMappings.length;while(++index<length){mapping=surrogateMappings[index];nextMapping=surrogateMappings[index+1];if(!nextMapping){result.push(mapping);continue}highSurrogates=mapping[0];lowSurrogates=mapping[1];nextHighSurrogates=nextMapping[0];nextLowSurrogates=nextMapping[1];tmpLow=lowSurrogates;while(nextHighSurrogates&&highSurrogates[0]==nextHighSurrogates[0]&&highSurrogates[1]==nextHighSurrogates[1]){if(dataIsSingleton(nextLowSurrogates)){tmpLow=dataAdd(tmpLow,nextLowSurrogates[0])}else{tmpLow=dataAddRange(tmpLow,nextLowSurrogates[0],nextLowSurrogates[1]-1)}++index;mapping=surrogateMappings[index];highSurrogates=mapping[0];lowSurrogates=mapping[1];nextMapping=surrogateMappings[index+1];nextHighSurrogates=nextMapping&&nextMapping[0];nextLowSurrogates=nextMapping&&nextMapping[1];addLow=true}result.push([highSurrogates,addLow?tmpLow:lowSurrogates]);addLow=false}return optimizeByLowSurrogates(result)};var optimizeByLowSurrogates=function(surrogateMappings){if(surrogateMappings.length==1){return surrogateMappings}var index=-1;var innerIndex=-1;while(++index<surrogateMappings.length){var mapping=surrogateMappings[index];var lowSurrogates=mapping[1];var lowSurrogateStart=lowSurrogates[0];var lowSurrogateEnd=lowSurrogates[1];innerIndex=index;while(++innerIndex<surrogateMappings.length){var otherMapping=surrogateMappings[innerIndex];var otherLowSurrogates=otherMapping[1];var otherLowSurrogateStart=otherLowSurrogates[0];var otherLowSurrogateEnd=otherLowSurrogates[1];if(lowSurrogateStart==otherLowSurrogateStart&&lowSurrogateEnd==otherLowSurrogateEnd){if(dataIsSingleton(otherMapping[0])){mapping[0]=dataAdd(mapping[0],otherMapping[0][0])}else{mapping[0]=dataAddRange(mapping[0],otherMapping[0][0],otherMapping[0][1]-1)}surrogateMappings.splice(innerIndex,1);--innerIndex}}}return surrogateMappings};var surrogateSet=function(data){if(!data.length){return[]}var index=0;var start;var end;var startHigh;var startLow;var prevStartHigh=0;var prevEndHigh=0;var tmpLow=[];var endHigh;var endLow;var surrogateMappings=[];var length=data.length;var dataHigh=[];while(index<length){start=data[index];end=data[index+1]-1;startHigh=highSurrogate(start);startLow=lowSurrogate(start);endHigh=highSurrogate(end);endLow=lowSurrogate(end);var startsWithLowestLowSurrogate=startLow==LOW_SURROGATE_MIN;var endsWithHighestLowSurrogate=endLow==LOW_SURROGATE_MAX;var complete=false;if(startHigh==endHigh||startsWithLowestLowSurrogate&&endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh,endHigh+1],[startLow,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh,startHigh+1],[startLow,LOW_SURROGATE_MAX+1]])}if(!complete&&startHigh+1<endHigh){if(endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh+1,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh+1,endHigh],[LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1]])}}if(!complete){surrogateMappings.push([[endHigh,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]])}prevStartHigh=startHigh;prevEndHigh=endHigh;index+=2}return optimizeSurrogateMappings(surrogateMappings)};var createSurrogateCharacterClasses=function(surrogateMappings){var result=[];forEach(surrogateMappings,function(surrogateMapping){var highSurrogates=surrogateMapping[0];var lowSurrogates=surrogateMapping[1];result.push(createBMPCharacterClasses(highSurrogates)+createBMPCharacterClasses(lowSurrogates))});return result.join("|")};var createCharacterClassesFromData=function(data){var result=[];var parts=splitAtBMP(data);var loneHighSurrogates=parts.loneHighSurrogates;var bmp=parts.bmp;var astral=parts.astral;var hasAstral=!dataIsEmpty(parts.astral);var hasLoneSurrogates=!dataIsEmpty(loneHighSurrogates);var surrogateMappings=surrogateSet(astral);if(!hasAstral&&hasLoneSurrogates){bmp=dataAddData(bmp,loneHighSurrogates)}if(!dataIsEmpty(bmp)){result.push(createBMPCharacterClasses(bmp))}if(surrogateMappings.length){result.push(createSurrogateCharacterClasses(surrogateMappings))}if(hasAstral&&hasLoneSurrogates){result.push(createBMPCharacterClasses(loneHighSurrogates))}return result.join("|")};var regenerate=function(value){if(arguments.length>1){value=slice.call(arguments)}if(this instanceof regenerate){this.data=[];return value?this.add(value):this}return(new regenerate).add(value)};regenerate.version="1.0.1";var proto=regenerate.prototype;extend(proto,{add:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataAddData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.add(item)});return $this}$this.data=dataAdd($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},remove:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataRemoveData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.remove(item)});return $this}$this.data=dataRemove($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},addRange:function(start,end){var $this=this;$this.data=dataAddRange($this.data,isNumber(start)?start:symbolToCodePoint(start),isNumber(end)?end:symbolToCodePoint(end));return $this},removeRange:function(start,end){var $this=this;var startCodePoint=isNumber(start)?start:symbolToCodePoint(start);var endCodePoint=isNumber(end)?end:symbolToCodePoint(end);$this.data=dataRemoveRange($this.data,startCodePoint,endCodePoint);return $this},intersection:function(argument){var $this=this;var array=argument instanceof regenerate?dataToArray(argument.data):argument;$this.data=dataIntersection($this.data,array);return $this},contains:function(codePoint){return dataContains(this.data,isNumber(codePoint)?codePoint:symbolToCodePoint(codePoint))},clone:function(){var set=new regenerate;set.data=this.data.slice(0);return set},toString:function(){var result=createCharacterClassesFromData(this.data);return result.replace(regexNull,"\\0$1")},toRegExp:function(flags){return RegExp(this.toString(),flags||"")},valueOf:function(){return dataToArray(this.data)}});proto.toArray=proto.valueOf;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return regenerate})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=regenerate}else{freeExports.regenerate=regenerate}}else{root.regenerate=regenerate}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],114:[function(require,module,exports){(function(global){(function(){"use strict";var objectTypes={"function":true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var stringFromCharCode=String.fromCharCode;var floor=Math.floor;function fromCodePoint(){var MAX_SIZE=16384;var codeUnits=[];var highSurrogate;var lowSurrogate;var index=-1;var length=arguments.length;if(!length){return""}var result="";while(++index<length){var codePoint=Number(arguments[index]);if(!isFinite(codePoint)||codePoint<0||codePoint>1114111||floor(codePoint)!=codePoint){throw RangeError("Invalid code point: "+codePoint)}if(codePoint<=65535){codeUnits.push(codePoint)}else{codePoint-=65536;highSurrogate=(codePoint>>10)+55296;lowSurrogate=codePoint%1024+56320;codeUnits.push(highSurrogate,lowSurrogate)}if(index+1==length||codeUnits.length>MAX_SIZE){result+=stringFromCharCode.apply(null,codeUnits);codeUnits.length=0}}return result}function assertType(type,expected){if(expected.indexOf("|")==-1){if(type==expected){return}throw Error("Invalid node type: "+type)}expected=assertType.hasOwnProperty(expected)?assertType[expected]:assertType[expected]=RegExp("^(?:"+expected+")$");if(expected.test(type)){return}throw Error("Invalid node type: "+type)}function generate(node){var type=node.type;if(generate.hasOwnProperty(type)&&typeof generate[type]=="function"){return generate[type](node)}throw Error("Invalid node type: "+type)}function generateAlternative(node){assertType(node.type,"alternative");var terms=node.body,length=terms?terms.length:0;if(length==1){return generateTerm(terms[0])}else{var i=-1,result="";while(++i<length){result+=generateTerm(terms[i])}return result}}function generateAnchor(node){assertType(node.type,"anchor");switch(node.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function generateAtom(node){assertType(node.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value");return generate(node)}function generateCharacterClass(node){assertType(node.type,"characterClass");var classRanges=node.body,length=classRanges?classRanges.length:0;var i=-1,result="[";if(node.negative){result+="^"}while(++i<length){result+=generateClassAtom(classRanges[i])}result+="]";return result}function generateCharacterClassEscape(node){assertType(node.type,"characterClassEscape");return"\\"+node.value}function generateCharacterClassRange(node){assertType(node.type,"characterClassRange");var min=node.min,max=node.max;if(min.type=="characterClassRange"||max.type=="characterClassRange"){throw Error("Invalid character class range")}return generateClassAtom(min)+"-"+generateClassAtom(max)}function generateClassAtom(node){assertType(node.type,"anchor|characterClassEscape|characterClassRange|dot|value");return generate(node)}function generateDisjunction(node){assertType(node.type,"disjunction");var body=node.body,length=body?body.length:0;if(length==0){throw Error("No body")}else if(length==1){return generate(body[0])}else{var i=-1,result="";while(++i<length){if(i!=0){result+="|"}result+=generate(body[i])}return result}}function generateDot(node){assertType(node.type,"dot");return"."}function generateGroup(node){assertType(node.type,"group");var result="(";switch(node.behavior){case"normal":break;case"ignore":result+="?:";break;case"lookahead":result+="?=";break;case"negativeLookahead":result+="?!";break;default:throw Error("Invalid behaviour: "+node.behaviour)}var body=node.body,length=body?body.length:0;if(length==1){result+=generate(body[0])}else{var i=-1;while(++i<length){result+=generate(body[i])}}result+=")";return result}function generateQuantifier(node){assertType(node.type,"quantifier");var quantifier="",min=node.min,max=node.max;switch(max){case undefined:case null:switch(min){case 0:quantifier="*";break;case 1:quantifier="+";break;default:quantifier="{"+min+",}";break}break;default:if(min==max){quantifier="{"+min+"}"}else if(min==0&&max==1){quantifier="?"}else{quantifier="{"+min+","+max+"}"}break}if(!node.greedy){quantifier+="?"}return generateAtom(node.body[0])+quantifier}function generateReference(node){assertType(node.type,"reference");return"\\"+node.matchIndex}function generateTerm(node){assertType(node.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value");return generate(node)}function generateValue(node){assertType(node.type,"value");var kind=node.kind,codePoint=node.codePoint;switch(kind){case"controlLetter":return"\\c"+fromCodePoint(codePoint+64);case"hexadecimalEscape":return"\\x"+("00"+codePoint.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+fromCodePoint(codePoint);case"null":return"\\"+codePoint;case"octal":return"\\"+codePoint.toString(8);case"singleEscape":switch(codePoint){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 11:return"\\v";case 12:return"\\f";case 13:return"\\r";default:throw Error("Invalid codepoint: "+codePoint)}case"symbol":return fromCodePoint(codePoint);case"unicodeEscape":return"\\u"+("0000"+codePoint.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+codePoint.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+kind)}}generate.alternative=generateAlternative;generate.anchor=generateAnchor;generate.characterClass=generateCharacterClass;generate.characterClassEscape=generateCharacterClassEscape;generate.characterClassRange=generateCharacterClassRange;generate.disjunction=generateDisjunction;generate.dot=generateDot;generate.group=generateGroup;generate.quantifier=generateQuantifier;generate.reference=generateReference;generate.value=generateValue;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return{generate:generate}})}else if(freeExports&&freeModule){freeExports.generate=generate}else{root.regjsgen={generate:generate}}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],115:[function(require,module,exports){(function(){function parse(str,flags){var hasUnicodeFlag=(flags||"").indexOf("u")!==-1;var pos=0;var closedCaptureCounter=0;function addRaw(node){node.raw=str.substring(node.range[0],node.range[1]);return node}function updateRawStart(node,start){node.range[0]=start;return addRaw(node)}function createAnchor(kind,rawLength){return addRaw({type:"anchor",kind:kind,range:[pos-rawLength,pos]})}function createValue(kind,codePoint,from,to){return addRaw({type:"value",kind:kind,codePoint:codePoint,range:[from,to]})}function createEscaped(kind,codePoint,value,fromOffset){fromOffset=fromOffset||0;return createValue(kind,codePoint,pos-(value.length+fromOffset),pos)}function createCharacter(matches){var _char=matches[0];var first=_char.charCodeAt(0);if(hasUnicodeFlag){var second;if(_char.length===1&&first>=55296&&first<=56319){second=lookahead().charCodeAt(0);if(second>=56320&&second<=57343){pos++;return createValue("symbol",(first-55296)*1024+second-56320+65536,pos-2,pos)}}}return createValue("symbol",first,pos-1,pos)}function createDisjunction(alternatives,from,to){return addRaw({type:"disjunction",body:alternatives,range:[from,to]})}function createDot(){return addRaw({type:"dot",range:[pos-1,pos]})}function createCharacterClassEscape(value){return addRaw({type:"characterClassEscape",value:value,range:[pos-2,pos]})}function createReference(matchIndex){return addRaw({type:"reference",matchIndex:parseInt(matchIndex,10),range:[pos-1-matchIndex.length,pos]})}function createGroup(behavior,disjunction,from,to){return addRaw({type:"group",behavior:behavior,body:disjunction,range:[from,to]})}function createQuantifier(min,max,from,to){if(to==null){from=pos-1;to=pos}return addRaw({type:"quantifier",min:min,max:max,greedy:true,body:null,range:[from,to]})}function createAlternative(terms,from,to){return addRaw({type:"alternative",body:terms,range:[from,to]})}function createCharacterClass(classRanges,negative,from,to){return addRaw({type:"characterClass",body:classRanges,negative:negative,range:[from,to]})}function createClassRange(min,max,from,to){if(min.codePoint>max.codePoint){throw SyntaxError("invalid range in character class")}return addRaw({type:"characterClassRange",min:min,max:max,range:[from,to]})}function flattenBody(body){if(body.type==="alternative"){return body.body}else{return[body]}}function isEmpty(obj){return obj.type==="empty"}function incr(amount){amount=amount||1; var res=str.substring(pos,pos+amount);pos+=amount||1;return res}function skip(value){if(!match(value)){throw SyntaxError("character: "+value)}}function match(value){if(str.indexOf(value,pos)===pos){return incr(value.length)}}function lookahead(){return str[pos]}function current(value){return str.indexOf(value,pos)===pos}function next(value){return str[pos+1]===value}function matchReg(regExp){var subStr=str.substring(pos);var res=subStr.match(regExp);if(res){res.range=[];res.range[0]=pos;incr(res[0].length);res.range[1]=pos}return res}function parseDisjunction(){var res=[],from=pos;res.push(parseAlternative());while(match("|")){res.push(parseAlternative())}if(res.length===1){return res[0]}return createDisjunction(res,from,pos)}function parseAlternative(){var res=[],from=pos;var term;while(term=parseTerm()){res.push(term)}if(res.length===1){return res[0]}return createAlternative(res,from,pos)}function parseTerm(){if(pos>=str.length||current("|")||current(")")){return null}var anchor=parseAnchor();if(anchor){return anchor}var atom=parseAtom();if(!atom){throw SyntaxError("Expected atom")}var quantifier=parseQuantifier()||false;if(quantifier){quantifier.body=flattenBody(atom);updateRawStart(quantifier,atom.range[0]);return quantifier}return atom}function parseGroup(matchA,typeA,matchB,typeB){var type=null,from=pos;if(match(matchA)){type=typeA}else if(match(matchB)){type=typeB}else{return false}var body=parseDisjunction();if(!body){throw SyntaxError("Expected disjunction")}skip(")");var group=createGroup(type,flattenBody(body),from,pos);if(type=="normal"){closedCaptureCounter++}return group}function parseAnchor(){var res,from=pos;if(match("^")){return createAnchor("start",1)}else if(match("$")){return createAnchor("end",1)}else if(match("\\b")){return createAnchor("boundary",2)}else if(match("\\B")){return createAnchor("not-boundary",2)}else{return parseGroup("(?=","lookahead","(?!","negativeLookahead")}}function parseQuantifier(){var res;var quantifier;var min,max;if(match("*")){quantifier=createQuantifier(0)}else if(match("+")){quantifier=createQuantifier(1)}else if(match("?")){quantifier=createQuantifier(0,1)}else if(res=matchReg(/^\{([0-9]+)\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,min,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,undefined,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),([0-9]+)\}/)){min=parseInt(res[1],10);max=parseInt(res[2],10);if(min>max){throw SyntaxError("numbers out of order in {} quantifier")}quantifier=createQuantifier(min,max,res.range[0],res.range[1])}if(quantifier){if(match("?")){quantifier.greedy=false;quantifier.range[1]+=1}}return quantifier}function parseAtom(){var res;if(res=matchReg(/^[^^$\\.*+?(){[|]/)){return createCharacter(res)}else if(match(".")){return createDot()}else if(match("\\")){res=parseAtomEscape();if(!res){throw SyntaxError("atomEscape")}return res}else if(res=parseCharacterClass()){return res}else{return parseGroup("(?:","ignore","(","normal")}}function parseUnicodeSurrogatePairEscape(firstEscape){if(hasUnicodeFlag){var first,second;if(firstEscape.kind=="unicodeEscape"&&(first=firstEscape.codePoint)>=55296&&first<=56319&&current("\\")&&next("u")){var prevPos=pos;pos++;var secondEscape=parseClassEscape();if(secondEscape.kind=="unicodeEscape"&&(second=secondEscape.codePoint)>=56320&&second<=57343){firstEscape.range[1]=secondEscape.range[1];firstEscape.codePoint=(first-55296)*1024+second-56320+65536;firstEscape.type="value";firstEscape.kind="unicodeCodePointEscape";addRaw(firstEscape)}else{pos=prevPos}}}return firstEscape}function parseClassEscape(){return parseAtomEscape(true)}function parseAtomEscape(insideCharacterClass){var res;res=parseDecimalEscape();if(res){return res}if(insideCharacterClass){if(match("b")){return createEscaped("singleEscape",8,"\\b")}else if(match("B")){throw SyntaxError("\\B not possible inside of CharacterClass")}}res=parseCharacterEscape();return res}function parseDecimalEscape(){var res,match;if(res=matchReg(/^(?!0)\d+/)){match=res[0];var refIdx=parseInt(res[0],10);if(refIdx<=closedCaptureCounter){return createReference(res[0])}else{incr(-res[0].length);if(res=matchReg(/^[0-7]{1,3}/)){return createEscaped("octal",parseInt(res[0],8),res[0],1)}else{res=createCharacter(matchReg(/^[89]/));return updateRawStart(res,res.range[0]-1)}}}else if(res=matchReg(/^[0-7]{1,3}/)){match=res[0];if(/^0{1,3}$/.test(match)){return createEscaped("null",0,"0",match.length+1)}else{return createEscaped("octal",parseInt(match,8),match,1)}}else if(res=matchReg(/^[dDsSwW]/)){return createCharacterClassEscape(res[0])}return false}function parseCharacterEscape(){var res;if(res=matchReg(/^[fnrtv]/)){var codePoint=0;switch(res[0]){case"t":codePoint=9;break;case"n":codePoint=10;break;case"v":codePoint=11;break;case"f":codePoint=12;break;case"r":codePoint=13;break}return createEscaped("singleEscape",codePoint,"\\"+res[0])}else if(res=matchReg(/^c([a-zA-Z])/)){return createEscaped("controlLetter",res[1].charCodeAt(0)%32,res[1],2)}else if(res=matchReg(/^x([0-9a-fA-F]{2})/)){return createEscaped("hexadecimalEscape",parseInt(res[1],16),res[1],2)}else if(res=matchReg(/^u([0-9a-fA-F]{4})/)){return parseUnicodeSurrogatePairEscape(createEscaped("unicodeEscape",parseInt(res[1],16),res[1],2))}else if(hasUnicodeFlag&&(res=matchReg(/^u\{([0-9a-fA-F]{1,6})\}/))){return createEscaped("unicodeCodePointEscape",parseInt(res[1],16),res[1],4)}else{return parseIdentityEscape()}}function isIdentifierPart(ch){var NonAsciiIdentifierPart=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&NonAsciiIdentifierPart.test(String.fromCharCode(ch))}function parseIdentityEscape(){var ZWJ="‌";var ZWNJ="‍";var res;var tmp;if(!isIdentifierPart(lookahead())){tmp=incr();return createEscaped("identifier",tmp.charCodeAt(0),tmp,1)}if(match(ZWJ)){return createEscaped("identifier",8204,ZWJ)}else if(match(ZWNJ)){return createEscaped("identifier",8205,ZWNJ)}return null}function parseCharacterClass(){var res,from=pos;if(res=matchReg(/^\[\^/)){res=parseClassRanges();skip("]");return createCharacterClass(res,true,from,pos)}else if(match("[")){res=parseClassRanges();skip("]");return createCharacterClass(res,false,from,pos)}return null}function parseClassRanges(){var res;if(current("]")){return[]}else{res=parseNonemptyClassRanges();if(!res){throw SyntaxError("nonEmptyClassRanges")}return res}}function parseHelperClassRanges(atom){var from,to,res;if(current("-")&&!next("]")){skip("-");res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}to=pos;var classRanges=parseClassRanges();if(!classRanges){throw SyntaxError("classRanges")}from=atom.range[0];if(classRanges.type==="empty"){return[createClassRange(atom,res,from,to)]}return[createClassRange(atom,res,from,to)].concat(classRanges)}res=parseNonemptyClassRangesNoDash();if(!res){throw SyntaxError("nonEmptyClassRangesNoDash")}return[atom].concat(res)}function parseNonemptyClassRanges(){var atom=parseClassAtom();if(!atom){throw SyntaxError("classAtom")}if(current("]")){return[atom]}return parseHelperClassRanges(atom)}function parseNonemptyClassRangesNoDash(){var res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}if(current("]")){return res}return parseHelperClassRanges(res)}function parseClassAtom(){if(match("-")){return createCharacter("-")}else{return parseClassAtomNoDash()}}function parseClassAtomNoDash(){var res;if(res=matchReg(/^[^\\\]-]/)){return createCharacter(res[0])}else if(match("\\")){res=parseClassEscape();if(!res){throw SyntaxError("classEscape")}return parseUnicodeSurrogatePairEscape(res)}}str=String(str);if(str===""){str="(?:)"}var result=parseDisjunction();if(result.range[1]!==str.length){throw SyntaxError("Could not parse entire input - got stuck: "+str)}return result}var regjsparser={parse:parse};if(typeof module!=="undefined"&&module.exports){module.exports=regjsparser}else{window.regjsparser=regjsparser}})()},{}],116:[function(require,module,exports){var generate=require("regjsgen").generate;var parse=require("regjsparser").parse;var regenerate=require("regenerate");var iuMappings=require("./data/iu-mappings.json");var ESCAPE_SETS=require("./data/character-class-escape-sets.js");function getCharacterClassEscapeSet(character){if(unicode){if(ignoreCase){return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]}return ESCAPE_SETS.UNICODE[character]}return ESCAPE_SETS.REGULAR[character]}var object={};var hasOwnProperty=object.hasOwnProperty;function has(object,property){return hasOwnProperty.call(object,property)}var UNICODE_SET=regenerate().addRange(0,1114111);var BMP_SET=regenerate().addRange(0,65535);var DOT_SET_UNICODE=UNICODE_SET.clone().remove(10,13,8232,8233);var DOT_SET=DOT_SET_UNICODE.clone().intersection(BMP_SET);regenerate.prototype.iuAddRange=function(min,max){var $this=this;do{var folded=caseFold(min);if(folded){$this.add(folded)}}while(++min<=max);return $this};function assign(target,source){for(var key in source){target[key]=source[key]}}function update(item,pattern){var tree=parse(pattern,"");switch(tree.type){case"characterClass":case"group":case"value":break;default:tree=wrap(tree,pattern)}assign(item,tree)}function wrap(tree,pattern){return{type:"group",behavior:"ignore",body:[tree],raw:"(?:"+pattern+")"}}function caseFold(codePoint){return has(iuMappings,codePoint)?iuMappings[codePoint]:false}var ignoreCase=false;var unicode=false;function processCharacterClass(characterClassItem){var set=regenerate();var body=characterClassItem.body.forEach(function(item){switch(item.type){case"value":set.add(item.codePoint);if(ignoreCase&&unicode){var folded=caseFold(item.codePoint);if(folded){set.add(folded)}}break;case"characterClassRange":var min=item.min.codePoint;var max=item.max.codePoint;set.addRange(min,max);if(ignoreCase&&unicode){set.iuAddRange(min,max)}break;case"characterClassEscape":set.add(getCharacterClassEscapeSet(item.value));break;default:throw Error("Unknown term type: "+item.type)}});if(characterClassItem.negative){set=(unicode?UNICODE_SET:BMP_SET).clone().remove(set)}update(characterClassItem,set.toString());return characterClassItem}function processTerm(item){switch(item.type){case"dot":update(item,(unicode?DOT_SET_UNICODE:DOT_SET).toString());break;case"characterClass":item=processCharacterClass(item);break;case"characterClassEscape":update(item,getCharacterClassEscapeSet(item.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":item.body=item.body.map(processTerm);break;case"value":var codePoint=item.codePoint;var set=regenerate(codePoint);if(ignoreCase&&unicode){var folded=caseFold(codePoint);if(folded){set.add(folded)}}update(item,set.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+item.type)}return item}module.exports=function(pattern,flags){var tree=parse(pattern,flags);ignoreCase=flags?flags.indexOf("i")>-1:false;unicode=flags?flags.indexOf("u")>-1:false;assign(tree,processTerm(tree));return generate(tree)}},{"./data/character-class-escape-sets.js":111,"./data/iu-mappings.json":112,regenerate:113,regjsgen:114,regjsparser:115}],117:[function(require,module,exports){exports.SourceMapGenerator=require("./source-map/source-map-generator").SourceMapGenerator;exports.SourceMapConsumer=require("./source-map/source-map-consumer").SourceMapConsumer;exports.SourceNode=require("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":122,"./source-map/source-map-generator":123,"./source-map/source-node":124}],118:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function ArraySet(){this._array=[];this._set={}}ArraySet.fromArray=function ArraySet_fromArray(aArray,aAllowDuplicates){var set=new ArraySet;for(var i=0,len=aArray.length;i<len;i++){set.add(aArray[i],aAllowDuplicates)}return set};ArraySet.prototype.add=function ArraySet_add(aStr,aAllowDuplicates){var isDuplicate=this.has(aStr);var idx=this._array.length;if(!isDuplicate||aAllowDuplicates){this._array.push(aStr)}if(!isDuplicate){this._set[util.toSetString(aStr)]=idx}};ArraySet.prototype.has=function ArraySet_has(aStr){return Object.prototype.hasOwnProperty.call(this._set,util.toSetString(aStr))};ArraySet.prototype.indexOf=function ArraySet_indexOf(aStr){if(this.has(aStr)){return this._set[util.toSetString(aStr)]}throw new Error('"'+aStr+'" is not in the set.')};ArraySet.prototype.at=function ArraySet_at(aIdx){if(aIdx>=0&&aIdx<this._array.length){return this._array[aIdx]}throw new Error("No element indexed by "+aIdx)};ArraySet.prototype.toArray=function ArraySet_toArray(){return this._array.slice()};exports.ArraySet=ArraySet})},{"./util":125,amdefine:126}],119:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64=require("./base64");var VLQ_BASE_SHIFT=5;var VLQ_BASE=1<<VLQ_BASE_SHIFT;var VLQ_BASE_MASK=VLQ_BASE-1;var VLQ_CONTINUATION_BIT=VLQ_BASE;function toVLQSigned(aValue){return aValue<0?(-aValue<<1)+1:(aValue<<1)+0}function fromVLQSigned(aValue){var isNegative=(aValue&1)===1;var shifted=aValue>>1;return isNegative?-shifted:shifted}exports.encode=function base64VLQ_encode(aValue){var encoded="";var digit;var vlq=toVLQSigned(aValue);do{digit=vlq&VLQ_BASE_MASK;vlq>>>=VLQ_BASE_SHIFT;if(vlq>0){digit|=VLQ_CONTINUATION_BIT}encoded+=base64.encode(digit)}while(vlq>0);return encoded};exports.decode=function base64VLQ_decode(aStr,aOutParam){var i=0;var strLen=aStr.length;var result=0;var shift=0;var continuation,digit;do{if(i>=strLen){throw new Error("Expected more digits in base 64 VLQ value.")}digit=base64.decode(aStr.charAt(i++));continuation=!!(digit&VLQ_CONTINUATION_BIT);digit&=VLQ_BASE_MASK;result=result+(digit<<shift);shift+=VLQ_BASE_SHIFT}while(continuation);aOutParam.value=fromVLQSigned(result);aOutParam.rest=aStr.slice(i)}})},{"./base64":120,amdefine:126}],120:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var charToIntMap={};var intToCharMap={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(ch,index){charToIntMap[ch]=index;intToCharMap[index]=ch});exports.encode=function base64_encode(aNumber){if(aNumber in intToCharMap){return intToCharMap[aNumber]}throw new TypeError("Must be between 0 and 63: "+aNumber)};exports.decode=function base64_decode(aChar){if(aChar in charToIntMap){return charToIntMap[aChar]}throw new TypeError("Not a valid base 64 digit: "+aChar)}})},{amdefine:126}],121:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare){var mid=Math.floor((aHigh-aLow)/2)+aLow;var cmp=aCompare(aNeedle,aHaystack[mid],true);if(cmp===0){return aHaystack[mid]}else if(cmp>0){if(aHigh-mid>1){return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare)}return aHaystack[mid]}else{if(mid-aLow>1){return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare)}return aLow<0?null:aHaystack[aLow]}}exports.search=function search(aNeedle,aHaystack,aCompare){return aHaystack.length>0?recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare):null}})},{amdefine:126}],122:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");var binarySearch=require("./binary-search");var ArraySet=require("./array-set").ArraySet;var base64VLQ=require("./base64-vlq");function SourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sources=util.getArg(sourceMap,"sources");var names=util.getArg(sourceMap,"names",[]);var sourceRoot=util.getArg(sourceMap,"sourceRoot",null);var sourcesContent=util.getArg(sourceMap,"sourcesContent",null);var mappings=util.getArg(sourceMap,"mappings");var file=util.getArg(sourceMap,"file",null);if(version!=this._version){throw new Error("Unsupported version: "+version)}this._names=ArraySet.fromArray(names,true);this._sources=ArraySet.fromArray(sources,true);this.sourceRoot=sourceRoot;this.sourcesContent=sourcesContent;this._mappings=mappings;this.file=file}SourceMapConsumer.fromSourceMap=function SourceMapConsumer_fromSourceMap(aSourceMap){var smc=Object.create(SourceMapConsumer.prototype);smc._names=ArraySet.fromArray(aSourceMap._names.toArray(),true);smc._sources=ArraySet.fromArray(aSourceMap._sources.toArray(),true);smc.sourceRoot=aSourceMap._sourceRoot;smc.sourcesContent=aSourceMap._generateSourcesContent(smc._sources.toArray(),smc.sourceRoot);smc.file=aSourceMap._file;smc.__generatedMappings=aSourceMap._mappings.slice().sort(util.compareByGeneratedPositions);smc.__originalMappings=aSourceMap._mappings.slice().sort(util.compareByOriginalPositions);return smc};SourceMapConsumer.prototype._version=3;Object.defineProperty(SourceMapConsumer.prototype,"sources",{get:function(){return this._sources.toArray().map(function(s){return this.sourceRoot!=null?util.join(this.sourceRoot,s):s},this)}});SourceMapConsumer.prototype.__generatedMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});SourceMapConsumer.prototype.__originalMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});SourceMapConsumer.prototype._nextCharIsMappingSeparator=function SourceMapConsumer_nextCharIsMappingSeparator(aStr){var c=aStr.charAt(0);return c===";"||c===","};SourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){var generatedLine=1;var previousGeneratedColumn=0;var previousOriginalLine=0;var previousOriginalColumn=0;var previousSource=0;var previousName=0;var str=aStr;var temp={};var mapping;while(str.length>0){if(str.charAt(0)===";"){generatedLine++;str=str.slice(1);previousGeneratedColumn=0}else if(str.charAt(0)===","){str=str.slice(1)}else{mapping={};mapping.generatedLine=generatedLine;base64VLQ.decode(str,temp);mapping.generatedColumn=previousGeneratedColumn+temp.value;previousGeneratedColumn=mapping.generatedColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.source=this._sources.at(previousSource+temp.value);previousSource+=temp.value;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source, but no line and column")}base64VLQ.decode(str,temp);mapping.originalLine=previousOriginalLine+temp.value;previousOriginalLine=mapping.originalLine;mapping.originalLine+=1;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source and line, but no column")}base64VLQ.decode(str,temp);mapping.originalColumn=previousOriginalColumn+temp.value;previousOriginalColumn=mapping.originalColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.name=this._names.at(previousName+temp.value);previousName+=temp.value;str=temp.rest}}this.__generatedMappings.push(mapping);if(typeof mapping.originalLine==="number"){this.__originalMappings.push(mapping)}}}this.__generatedMappings.sort(util.compareByGeneratedPositions);this.__originalMappings.sort(util.compareByOriginalPositions)};SourceMapConsumer.prototype._findMapping=function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName,aColumnName,aComparator){if(aNeedle[aLineName]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+aNeedle[aLineName])}if(aNeedle[aColumnName]<0){throw new TypeError("Column must be greater than or equal to 0, got "+aNeedle[aColumnName])}return binarySearch.search(aNeedle,aMappings,aComparator)};SourceMapConsumer.prototype.originalPositionFor=function SourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var mapping=this._findMapping(needle,this._generatedMappings,"generatedLine","generatedColumn",util.compareByGeneratedPositions);if(mapping&&mapping.generatedLine===needle.generatedLine){var source=util.getArg(mapping,"source",null);if(source!=null&&this.sourceRoot!=null){source=util.join(this.sourceRoot,source)}return{source:source,line:util.getArg(mapping,"originalLine",null),column:util.getArg(mapping,"originalColumn",null),name:util.getArg(mapping,"name",null)}}return{source:null,line:null,column:null,name:null}};SourceMapConsumer.prototype.sourceContentFor=function SourceMapConsumer_sourceContentFor(aSource){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){aSource=util.relative(this.sourceRoot,aSource)}if(this._sources.has(aSource)){return this.sourcesContent[this._sources.indexOf(aSource)]}var url;if(this.sourceRoot!=null&&(url=util.urlParse(this.sourceRoot))){var fileUriAbsPath=aSource.replace(/^file:\/\//,"");if(url.scheme=="file"&&this._sources.has(fileUriAbsPath)){return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]}if((!url.path||url.path=="/")&&this._sources.has("/"+aSource)){return this.sourcesContent[this._sources.indexOf("/"+aSource)]}}throw new Error('"'+aSource+'" is not in the SourceMap.')};SourceMapConsumer.prototype.generatedPositionFor=function SourceMapConsumer_generatedPositionFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:util.getArg(aArgs,"column")};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var mapping=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(mapping){return{line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null)}}return{line:null,column:null}};SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;SourceMapConsumer.prototype.eachMapping=function SourceMapConsumer_eachMapping(aCallback,aContext,aOrder){var context=aContext||null;var order=aOrder||SourceMapConsumer.GENERATED_ORDER;var mappings;switch(order){case SourceMapConsumer.GENERATED_ORDER:mappings=this._generatedMappings;break;case SourceMapConsumer.ORIGINAL_ORDER:mappings=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var sourceRoot=this.sourceRoot;mappings.map(function(mapping){var source=mapping.source;if(source!=null&&sourceRoot!=null){source=util.join(sourceRoot,source)}return{source:source,generatedLine:mapping.generatedLine,generatedColumn:mapping.generatedColumn,originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:mapping.name}}).forEach(aCallback,context)};exports.SourceMapConsumer=SourceMapConsumer})},{"./array-set":118,"./base64-vlq":119,"./binary-search":121,"./util":125,amdefine:126}],123:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64VLQ=require("./base64-vlq");var util=require("./util");var ArraySet=require("./array-set").ArraySet;function SourceMapGenerator(aArgs){if(!aArgs){aArgs={}}this._file=util.getArg(aArgs,"file",null);this._sourceRoot=util.getArg(aArgs,"sourceRoot",null);this._sources=new ArraySet;this._names=new ArraySet;this._mappings=[];this._sourcesContents=null}SourceMapGenerator.prototype._version=3;SourceMapGenerator.fromSourceMap=function SourceMapGenerator_fromSourceMap(aSourceMapConsumer){var sourceRoot=aSourceMapConsumer.sourceRoot;var generator=new SourceMapGenerator({file:aSourceMapConsumer.file,sourceRoot:sourceRoot});aSourceMapConsumer.eachMapping(function(mapping){var newMapping={generated:{line:mapping.generatedLine,column:mapping.generatedColumn}};if(mapping.source!=null){newMapping.source=mapping.source;if(sourceRoot!=null){newMapping.source=util.relative(sourceRoot,newMapping.source)}newMapping.original={line:mapping.originalLine,column:mapping.originalColumn};if(mapping.name!=null){newMapping.name=mapping.name}}generator.addMapping(newMapping)});aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){generator.setSourceContent(sourceFile,content)}});return generator};SourceMapGenerator.prototype.addMapping=function SourceMapGenerator_addMapping(aArgs){var generated=util.getArg(aArgs,"generated");var original=util.getArg(aArgs,"original",null);var source=util.getArg(aArgs,"source",null);var name=util.getArg(aArgs,"name",null);this._validateMapping(generated,original,source,name);if(source!=null&&!this._sources.has(source)){this._sources.add(source)}if(name!=null&&!this._names.has(name)){this._names.add(name)}this._mappings.push({generatedLine:generated.line,generatedColumn:generated.column,originalLine:original!=null&&original.line,originalColumn:original!=null&&original.column,source:source,name:name})};SourceMapGenerator.prototype.setSourceContent=function SourceMapGenerator_setSourceContent(aSourceFile,aSourceContent){var source=aSourceFile;if(this._sourceRoot!=null){source=util.relative(this._sourceRoot,source)}if(aSourceContent!=null){if(!this._sourcesContents){this._sourcesContents={}}this._sourcesContents[util.toSetString(source)]=aSourceContent}else if(this._sourcesContents){delete this._sourcesContents[util.toSetString(source)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};SourceMapGenerator.prototype.applySourceMap=function SourceMapGenerator_applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath){var sourceFile=aSourceFile;if(aSourceFile==null){if(aSourceMapConsumer.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}sourceFile=aSourceMapConsumer.file}var sourceRoot=this._sourceRoot;if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}var newSources=new ArraySet;var newNames=new ArraySet;this._mappings.forEach(function(mapping){if(mapping.source===sourceFile&&mapping.originalLine!=null){var original=aSourceMapConsumer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});if(original.source!=null){mapping.source=original.source;if(aSourceMapPath!=null){mapping.source=util.join(aSourceMapPath,mapping.source)}if(sourceRoot!=null){mapping.source=util.relative(sourceRoot,mapping.source)}mapping.originalLine=original.line;mapping.originalColumn=original.column;if(original.name!=null){mapping.name=original.name}}}var source=mapping.source;if(source!=null&&!newSources.has(source)){newSources.add(source)}var name=mapping.name;if(name!=null&&!newNames.has(name)){newNames.add(name)}},this);this._sources=newSources;this._names=newNames;aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aSourceMapPath!=null){sourceFile=util.join(aSourceMapPath,sourceFile)}if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}this.setSourceContent(sourceFile,content)}},this)};SourceMapGenerator.prototype._validateMapping=function SourceMapGenerator_validateMapping(aGenerated,aOriginal,aSource,aName){if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aGenerated.line>0&&aGenerated.column>=0&&!aOriginal&&!aSource&&!aName){return}else if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aOriginal&&"line"in aOriginal&&"column"in aOriginal&&aGenerated.line>0&&aGenerated.column>=0&&aOriginal.line>0&&aOriginal.column>=0&&aSource){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:aGenerated,source:aSource,original:aOriginal,name:aName}))}};SourceMapGenerator.prototype._serializeMappings=function SourceMapGenerator_serializeMappings(){var previousGeneratedColumn=0;var previousGeneratedLine=1;var previousOriginalColumn=0;var previousOriginalLine=0;var previousName=0;var previousSource=0;var result="";var mapping;this._mappings.sort(util.compareByGeneratedPositions);for(var i=0,len=this._mappings.length;i<len;i++){mapping=this._mappings[i];if(mapping.generatedLine!==previousGeneratedLine){previousGeneratedColumn=0;while(mapping.generatedLine!==previousGeneratedLine){result+=";";previousGeneratedLine++}}else{if(i>0){if(!util.compareByGeneratedPositions(mapping,this._mappings[i-1])){continue}result+=","}}result+=base64VLQ.encode(mapping.generatedColumn-previousGeneratedColumn);previousGeneratedColumn=mapping.generatedColumn;if(mapping.source!=null){result+=base64VLQ.encode(this._sources.indexOf(mapping.source)-previousSource);previousSource=this._sources.indexOf(mapping.source);result+=base64VLQ.encode(mapping.originalLine-1-previousOriginalLine);previousOriginalLine=mapping.originalLine-1;result+=base64VLQ.encode(mapping.originalColumn-previousOriginalColumn);previousOriginalColumn=mapping.originalColumn;if(mapping.name!=null){result+=base64VLQ.encode(this._names.indexOf(mapping.name)-previousName);previousName=this._names.indexOf(mapping.name)}}}return result};SourceMapGenerator.prototype._generateSourcesContent=function SourceMapGenerator_generateSourcesContent(aSources,aSourceRoot){return aSources.map(function(source){if(!this._sourcesContents){return null}if(aSourceRoot!=null){source=util.relative(aSourceRoot,source)}var key=util.toSetString(source);return Object.prototype.hasOwnProperty.call(this._sourcesContents,key)?this._sourcesContents[key]:null},this)};SourceMapGenerator.prototype.toJSON=function SourceMapGenerator_toJSON(){var map={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){map.file=this._file}if(this._sourceRoot!=null){map.sourceRoot=this._sourceRoot}if(this._sourcesContents){map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot)}return map};SourceMapGenerator.prototype.toString=function SourceMapGenerator_toString(){return JSON.stringify(this)};exports.SourceMapGenerator=SourceMapGenerator})},{"./array-set":118,"./base64-vlq":119,"./util":125,amdefine:126}],124:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var SourceMapGenerator=require("./source-map-generator").SourceMapGenerator; var util=require("./util");var REGEX_NEWLINE=/(\r?\n)/;var REGEX_CHARACTER=/\r\n|[\s\S]/g;function SourceNode(aLine,aColumn,aSource,aChunks,aName){this.children=[];this.sourceContents={};this.line=aLine==null?null:aLine;this.column=aColumn==null?null:aColumn;this.source=aSource==null?null:aSource;this.name=aName==null?null:aName;if(aChunks!=null)this.add(aChunks)}SourceNode.fromStringWithSourceMap=function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath){var node=new SourceNode;var remainingLines=aGeneratedCode.split(REGEX_NEWLINE);var shiftNextLine=function(){var lineContents=remainingLines.shift();var newLine=remainingLines.shift()||"";return lineContents+newLine};var lastGeneratedLine=1,lastGeneratedColumn=0;var lastMapping=null;aSourceMapConsumer.eachMapping(function(mapping){if(lastMapping!==null){if(lastGeneratedLine<mapping.generatedLine){var code="";addMappingWithCode(lastMapping,shiftNextLine());lastGeneratedLine++;lastGeneratedColumn=0}else{var nextLine=remainingLines[0];var code=nextLine.substr(0,mapping.generatedColumn-lastGeneratedColumn);remainingLines[0]=nextLine.substr(mapping.generatedColumn-lastGeneratedColumn);lastGeneratedColumn=mapping.generatedColumn;addMappingWithCode(lastMapping,code);lastMapping=mapping;return}}while(lastGeneratedLine<mapping.generatedLine){node.add(shiftNextLine());lastGeneratedLine++}if(lastGeneratedColumn<mapping.generatedColumn){var nextLine=remainingLines[0];node.add(nextLine.substr(0,mapping.generatedColumn));remainingLines[0]=nextLine.substr(mapping.generatedColumn);lastGeneratedColumn=mapping.generatedColumn}lastMapping=mapping},this);if(remainingLines.length>0){if(lastMapping){addMappingWithCode(lastMapping,shiftNextLine())}node.add(remainingLines.join(""))}aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aRelativePath!=null){sourceFile=util.join(aRelativePath,sourceFile)}node.setSourceContent(sourceFile,content)}});return node;function addMappingWithCode(mapping,code){if(mapping===null||mapping.source===undefined){node.add(code)}else{var source=aRelativePath?util.join(aRelativePath,mapping.source):mapping.source;node.add(new SourceNode(mapping.originalLine,mapping.originalColumn,source,code,mapping.name))}}};SourceNode.prototype.add=function SourceNode_add(aChunk){if(Array.isArray(aChunk)){aChunk.forEach(function(chunk){this.add(chunk)},this)}else if(aChunk instanceof SourceNode||typeof aChunk==="string"){if(aChunk){this.children.push(aChunk)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.prepend=function SourceNode_prepend(aChunk){if(Array.isArray(aChunk)){for(var i=aChunk.length-1;i>=0;i--){this.prepend(aChunk[i])}}else if(aChunk instanceof SourceNode||typeof aChunk==="string"){this.children.unshift(aChunk)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.walk=function SourceNode_walk(aFn){var chunk;for(var i=0,len=this.children.length;i<len;i++){chunk=this.children[i];if(chunk instanceof SourceNode){chunk.walk(aFn)}else{if(chunk!==""){aFn(chunk,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};SourceNode.prototype.join=function SourceNode_join(aSep){var newChildren;var i;var len=this.children.length;if(len>0){newChildren=[];for(i=0;i<len-1;i++){newChildren.push(this.children[i]);newChildren.push(aSep)}newChildren.push(this.children[i]);this.children=newChildren}return this};SourceNode.prototype.replaceRight=function SourceNode_replaceRight(aPattern,aReplacement){var lastChild=this.children[this.children.length-1];if(lastChild instanceof SourceNode){lastChild.replaceRight(aPattern,aReplacement)}else if(typeof lastChild==="string"){this.children[this.children.length-1]=lastChild.replace(aPattern,aReplacement)}else{this.children.push("".replace(aPattern,aReplacement))}return this};SourceNode.prototype.setSourceContent=function SourceNode_setSourceContent(aSourceFile,aSourceContent){this.sourceContents[util.toSetString(aSourceFile)]=aSourceContent};SourceNode.prototype.walkSourceContents=function SourceNode_walkSourceContents(aFn){for(var i=0,len=this.children.length;i<len;i++){if(this.children[i]instanceof SourceNode){this.children[i].walkSourceContents(aFn)}}var sources=Object.keys(this.sourceContents);for(var i=0,len=sources.length;i<len;i++){aFn(util.fromSetString(sources[i]),this.sourceContents[sources[i]])}};SourceNode.prototype.toString=function SourceNode_toString(){var str="";this.walk(function(chunk){str+=chunk});return str};SourceNode.prototype.toStringWithSourceMap=function SourceNode_toStringWithSourceMap(aArgs){var generated={code:"",line:1,column:0};var map=new SourceMapGenerator(aArgs);var sourceMappingActive=false;var lastOriginalSource=null;var lastOriginalLine=null;var lastOriginalColumn=null;var lastOriginalName=null;this.walk(function(chunk,original){generated.code+=chunk;if(original.source!==null&&original.line!==null&&original.column!==null){if(lastOriginalSource!==original.source||lastOriginalLine!==original.line||lastOriginalColumn!==original.column||lastOriginalName!==original.name){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}lastOriginalSource=original.source;lastOriginalLine=original.line;lastOriginalColumn=original.column;lastOriginalName=original.name;sourceMappingActive=true}else if(sourceMappingActive){map.addMapping({generated:{line:generated.line,column:generated.column}});lastOriginalSource=null;sourceMappingActive=false}chunk.match(REGEX_CHARACTER).forEach(function(ch,idx,array){if(REGEX_NEWLINE.test(ch)){generated.line++;generated.column=0;if(idx+1===array.length){lastOriginalSource=null;sourceMappingActive=false}else if(sourceMappingActive){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}}else{generated.column+=ch.length}})});this.walkSourceContents(function(sourceFile,sourceContent){map.setSourceContent(sourceFile,sourceContent)});return{code:generated.code,map:map}};exports.SourceNode=SourceNode})},{"./source-map-generator":123,"./util":125,amdefine:126}],125:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function getArg(aArgs,aName,aDefaultValue){if(aName in aArgs){return aArgs[aName]}else if(arguments.length===3){return aDefaultValue}else{throw new Error('"'+aName+'" is a required argument.')}}exports.getArg=getArg;var urlRegexp=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var dataUrlRegexp=/^data:.+\,.+$/;function urlParse(aUrl){var match=aUrl.match(urlRegexp);if(!match){return null}return{scheme:match[1],auth:match[2],host:match[3],port:match[4],path:match[5]}}exports.urlParse=urlParse;function urlGenerate(aParsedUrl){var url="";if(aParsedUrl.scheme){url+=aParsedUrl.scheme+":"}url+="//";if(aParsedUrl.auth){url+=aParsedUrl.auth+"@"}if(aParsedUrl.host){url+=aParsedUrl.host}if(aParsedUrl.port){url+=":"+aParsedUrl.port}if(aParsedUrl.path){url+=aParsedUrl.path}return url}exports.urlGenerate=urlGenerate;function normalize(aPath){var path=aPath;var url=urlParse(aPath);if(url){if(!url.path){return aPath}path=url.path}var isAbsolute=path.charAt(0)==="/";var parts=path.split(/\/+/);for(var part,up=0,i=parts.length-1;i>=0;i--){part=parts[i];if(part==="."){parts.splice(i,1)}else if(part===".."){up++}else if(up>0){if(part===""){parts.splice(i+1,up);up=0}else{parts.splice(i,2);up--}}}path=parts.join("/");if(path===""){path=isAbsolute?"/":"."}if(url){url.path=path;return urlGenerate(url)}return path}exports.normalize=normalize;function join(aRoot,aPath){if(aRoot===""){aRoot="."}if(aPath===""){aPath="."}var aPathUrl=urlParse(aPath);var aRootUrl=urlParse(aRoot);if(aRootUrl){aRoot=aRootUrl.path||"/"}if(aPathUrl&&!aPathUrl.scheme){if(aRootUrl){aPathUrl.scheme=aRootUrl.scheme}return urlGenerate(aPathUrl)}if(aPathUrl||aPath.match(dataUrlRegexp)){return aPath}if(aRootUrl&&!aRootUrl.host&&!aRootUrl.path){aRootUrl.host=aPath;return urlGenerate(aRootUrl)}var joined=aPath.charAt(0)==="/"?aPath:normalize(aRoot.replace(/\/+$/,"")+"/"+aPath);if(aRootUrl){aRootUrl.path=joined;return urlGenerate(aRootUrl)}return joined}exports.join=join;function relative(aRoot,aPath){if(aRoot===""){aRoot="."}aRoot=aRoot.replace(/\/$/,"");var url=urlParse(aRoot);if(aPath.charAt(0)=="/"&&url&&url.path=="/"){return aPath.slice(1)}return aPath.indexOf(aRoot+"/")===0?aPath.substr(aRoot.length+1):aPath}exports.relative=relative;function toSetString(aStr){return"$"+aStr}exports.toSetString=toSetString;function fromSetString(aStr){return aStr.substr(1)}exports.fromSetString=fromSetString;function strcmp(aStr1,aStr2){var s1=aStr1||"";var s2=aStr2||"";return(s1>s2)-(s1<s2)}function compareByOriginalPositions(mappingA,mappingB,onlyCompareOriginal){var cmp;cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp||onlyCompareOriginal){return cmp}cmp=strcmp(mappingA.name,mappingB.name);if(cmp){return cmp}cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}return mappingA.generatedColumn-mappingB.generatedColumn}exports.compareByOriginalPositions=compareByOriginalPositions;function compareByGeneratedPositions(mappingA,mappingB,onlyCompareGenerated){var cmp;cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp||onlyCompareGenerated){return cmp}cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp){return cmp}return strcmp(mappingA.name,mappingB.name)}exports.compareByGeneratedPositions=compareByGeneratedPositions})},{amdefine:126}],126:[function(require,module,exports){(function(process,__filename){"use strict";function amdefine(module,requireFn){"use strict";var defineCache={},loaderCache={},alreadyCalled=false,path=require("path"),makeRequire,stringRequire;function trimDots(ary){var i,part;for(i=0;ary[i];i+=1){part=ary[i];if(part==="."){ary.splice(i,1);i-=1}else if(part===".."){if(i===1&&(ary[2]===".."||ary[0]==="..")){break}else if(i>0){ary.splice(i-1,2);i-=2}}}}function normalize(name,baseName){var baseParts;if(name&&name.charAt(0)==="."){if(baseName){baseParts=baseName.split("/");baseParts=baseParts.slice(0,baseParts.length-1);baseParts=baseParts.concat(name.split("/"));trimDots(baseParts);name=baseParts.join("/")}}return name}function makeNormalize(relName){return function(name){return normalize(name,relName)}}function makeLoad(id){function load(value){loaderCache[id]=value}load.fromText=function(id,text){throw new Error("amdefine does not implement load.fromText")};return load}makeRequire=function(systemRequire,exports,module,relId){function amdRequire(deps,callback){if(typeof deps==="string"){return stringRequire(systemRequire,exports,module,deps,relId)}else{deps=deps.map(function(depName){return stringRequire(systemRequire,exports,module,depName,relId)});process.nextTick(function(){callback.apply(null,deps)})}}amdRequire.toUrl=function(filePath){if(filePath.indexOf(".")===0){return normalize(filePath,path.dirname(module.filename))}else{return filePath}};return amdRequire};requireFn=requireFn||function req(){return module.require.apply(module,arguments)};function runFactory(id,deps,factory){var r,e,m,result;if(id){e=loaderCache[id]={};m={id:id,uri:__filename,exports:e};r=makeRequire(requireFn,e,m,id)}else{if(alreadyCalled){throw new Error("amdefine with no module ID cannot be called more than once per file.")}alreadyCalled=true;e=module.exports;m=module;r=makeRequire(requireFn,e,m,module.id)}if(deps){deps=deps.map(function(depName){return r(depName)})}if(typeof factory==="function"){result=factory.apply(m.exports,deps)}else{result=factory}if(result!==undefined){m.exports=result;if(id){loaderCache[id]=m.exports}}}stringRequire=function(systemRequire,exports,module,id,relId){var index=id.indexOf("!"),originalId=id,prefix,plugin;if(index===-1){id=normalize(id,relId);if(id==="require"){return makeRequire(systemRequire,exports,module,relId)}else if(id==="exports"){return exports}else if(id==="module"){return module}else if(loaderCache.hasOwnProperty(id)){return loaderCache[id]}else if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}else{if(systemRequire){return systemRequire(originalId)}else{throw new Error("No module with ID: "+id)}}}else{prefix=id.substring(0,index);id=id.substring(index+1,id.length);plugin=stringRequire(systemRequire,exports,module,prefix,relId);if(plugin.normalize){id=plugin.normalize(id,makeNormalize(relId))}else{id=normalize(id,relId)}if(loaderCache[id]){return loaderCache[id]}else{plugin.load(id,makeRequire(systemRequire,exports,module,relId),makeLoad(id),{});return loaderCache[id]}}};function define(id,deps,factory){if(Array.isArray(id)){factory=deps;deps=id;id=undefined}else if(typeof id!=="string"){factory=id;id=deps=undefined}if(deps&&!Array.isArray(deps)){factory=deps;deps=undefined}if(!deps){deps=["require","exports","module"]}if(id){defineCache[id]=[id,deps,factory]}else{runFactory(id,deps,factory)}}define.require=function(id){if(loaderCache[id]){return loaderCache[id]}if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}};define.amd={};return define}module.exports=amdefine}).call(this,require("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:101,path:100}],127:[function(require,module,exports){module.exports={"abstract-expression-call":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceGet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-delete":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceDelete"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-get":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceGet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-set":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceSet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"},{type:"Identifier",name:"VALUE"}]}}]},"apply-constructor":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"Constructor"},{type:"Identifier",name:"args"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"instance"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"prototype"},computed:false}]}}],kind:"var"},{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"result"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"Identifier",name:"instance"},{type:"Identifier",name:"args"}]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"Identifier",name:"result"},operator:"!=",right:{type:"Literal",value:null}},operator:"&&",right:{type:"ParenthesizedExpression",expression:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"object"}},operator:"||",right:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"function"}}}}},consequent:{type:"Identifier",name:"result"},alternate:{type:"Identifier",name:"instance"}}}]},expression:false}}}]},"array-comprehension-container":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"KEY"},init:{type:"ArrayExpression",elements:[]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[]}}]},"array-comprehension-for-each":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"forEach"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[]},expression:false}]}}]},"array-expression-comprehension-filter":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"filter"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"FILTER"}}]},expression:false}]},property:{type:"Identifier",name:"map"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"STATEMENT"}}]},expression:false}]}}]},"array-expression-comprehension-map":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"map"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"STATEMENT"}}]},expression:false}]}}]},"array-from":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"VALUE"}]}}]},"array-push":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"KEY"},property:{type:"Identifier",name:"push"},computed:false},arguments:[{type:"Identifier",name:"STATEMENT"}]}}]},call:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"CONTEXT"}]}}]},"class-props":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"},{type:"Identifier",name:"instanceProps"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"Identifier",name:"staticProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"}]}},alternate:null},{type:"IfStatement",test:{type:"Identifier",name:"instanceProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"Identifier",name:"instanceProps"}]}},alternate:null}]},expression:false}}}]},"class-super-constructor-call":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"SUPER_NAME"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"arguments"}]}}]},"class":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"CLASS_NAME"},init:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[]},expression:false}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"CLASS_NAME"}}]},expression:false}},arguments:[]}}]},"exports-assign-key":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"VARIABLE_NAME"},computed:false},right:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"Identifier",name:"KEY"},computed:false}}}]},"exports-assign":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"KEY"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-default-module":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"module"},property:{type:"Identifier",name:"exports"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-default":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"default"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-wildcard":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:null}],kind:"var"},right:{type:"Identifier",name:"obj"},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"i"},computed:true}}}]}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"extends":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"parent"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"parent"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"constructor"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"child"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"enumerable"},value:{type:"Literal",value:false},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"writable"},value:{type:"Literal",value:true},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"configurable"},value:{type:"Literal",value:true},kind:"init"}]},kind:"init"}]}]}}},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"__proto__"},computed:false},right:{type:"Identifier",name:"parent"}}}]},expression:false}}}]},"for-of":{type:"Program",body:[{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"ITERATOR_KEY"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"iterator"},computed:false},computed:true},arguments:[]}},{type:"VariableDeclarator",id:{type:"Identifier",name:"STEP_KEY"},init:null}],kind:"var"},test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"MemberExpression",object:{type:"ParenthesizedExpression",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"STEP_KEY"},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ITERATOR_KEY"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}}},property:{type:"Identifier",name:"done"},computed:false}},update:null,body:{type:"BlockStatement",body:[]}}]},"function-return-obj":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"has-own":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"hasOwnProperty"},computed:false}}]},"if-undefined-set-to":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"Identifier",name:"VARIABLE"},operator:"===",right:{type:"Identifier",name:"undefined"}},consequent:{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"VARIABLE"},right:{type:"Identifier",name:"DEFAULT"}}},alternate:null}]},"interop-require":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"LogicalExpression",left:{type:"Identifier",name:"obj"},operator:"&&",right:{type:"ParenthesizedExpression",expression:{type:"LogicalExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Literal",value:"default"},computed:true},operator:"||",right:{type:"Identifier",name:"obj"}}}}}]},expression:false}}}]},"let-scoping-return":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"RETURN"}},operator:"===",right:{type:"Literal",value:"object"}},consequent:{type:"ReturnStatement",argument:{type:"MemberExpression",object:{type:"Identifier",name:"RETURN"},property:{type:"Identifier",name:"v"},computed:false}},alternate:null}]},"object-define-properties-closure":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"Identifier",name:"CONTENT"}},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"object-define-properties":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"OBJECT"},{type:"Identifier",name:"PROPS"}]}}]},"object-spread":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"keys"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"target"},init:{type:"ObjectExpression",properties:[]}}],kind:"var"},{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:null}],kind:"var"},right:{type:"Identifier",name:"obj"},body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"keys"},property:{type:"Identifier",name:"indexOf"},computed:false},arguments:[{type:"Identifier",name:"i"}]},operator:">=",right:{type:"Literal",value:0}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"hasOwnProperty"},computed:false},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"i"}]}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"target"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"i"},computed:true}}}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"target"}}]},expression:false}}}]},"prototype-identifier":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"Identifier",name:"CLASS_NAME"},property:{type:"Identifier",name:"prototype"},computed:false}}]},register:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"System"},property:{type:"Identifier",name:"register"},computed:false},arguments:[{type:"Identifier",name:"MODULE_NAME"},{type:"Identifier",name:"MODULE_DEPENDENCIES"},{type:"Identifier",name:"MODULE_BODY"}]}}]},"require-assign-key":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]},property:{type:"Identifier",name:"KEY"},computed:false}}],kind:"var"}]},"require-assign":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]}}],kind:"var"}]},require:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]}}]},"self-global":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ConditionalExpression",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"global"}},operator:"===",right:{type:"Literal",value:"undefined"}},consequent:{type:"Identifier",name:"self"},alternate:{type:"Identifier",name:"global"}}}]},slice:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"slice"},computed:false}}]},"tagged-template-literal":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"strings"},{type:"Identifier",name:"raw"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"strings"},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"raw"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"raw"},kind:"init"}]},kind:"init"}]}]}}]},expression:false}}}]},"to-array":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"arr"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"isArray"},computed:false},arguments:[{type:"Identifier",name:"arr"}]},consequent:{type:"Identifier",name:"arr"},alternate:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"arr"}]}}}]},expression:false}}}]},"umd-runner-body":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"factory"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"define"}},operator:"===",right:{type:"Literal",value:"function"}},operator:"&&",right:{type:"MemberExpression",object:{type:"Identifier",name:"define"},property:{type:"Identifier",name:"amd"},computed:false}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"define"},arguments:[{type:"Identifier",name:"AMD_ARGUMENTS"},{type:"Identifier",name:"factory"}]}}]},alternate:{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"exports"}},operator:"!==",right:{type:"Literal",value:"undefined"}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"factory"},arguments:[{type:"Identifier",name:"exports"},{type:"Identifier",name:"COMMON_ARGUMENTS"}]}}]},alternate:null}}]},expression:false}}}]}} },{}]},{},[2])(2)});
node_modules/http-server/node_modules/union/node_modules/qs/test/browser/jquery.js
WhitDuBois/souqMarket
/*! * jQuery JavaScript Library v1.6.2 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Jun 30 14:16:56 2011 -0400 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Check for digits rdigit = /\d/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z])/ig, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return (context || rootjQuery).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.6.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.done( fn ); return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).unbind( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery._Deferred(); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNaN: function( obj ) { return obj == null || !rdigit.test( obj ) || isNaN( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return (new Function( "return " + data ))(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing // (xml & tmp used internally) parseXML: function( data , xml , tmp ) { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } tmp = xml.documentElement; if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Converts a dashed string to camelCased string; // Used by both the css and data modules camelCase: function( string ) { return string.replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( indexOf ) { return indexOf.call( array, elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { if ( typeof context === "string" ) { var tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can optionally be executed if it's a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return (new Date()).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } return jQuery; })(); var // Promise methods promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ // Create a simple deferred (one callbacks list) _Deferred: function() { var // callbacks list callbacks = [], // stored [ context , args ] fired, // to avoid firing when already doing so firing, // flag to know if the deferred has been cancelled cancelled, // the deferred itself deferred = { // done( f1, f2, ...) done: function() { if ( !cancelled ) { var args = arguments, i, length, elem, type, _fired; if ( fired ) { _fired = fired; fired = 0; } for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { deferred.done.apply( deferred, elem ); } else if ( type === "function" ) { callbacks.push( elem ); } } if ( _fired ) { deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); } } return this; }, // resolve with given context and args resolveWith: function( context, args ) { if ( !cancelled && !fired && !firing ) { // make sure args are available (#8421) args = args || []; firing = 1; try { while( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); } } finally { fired = [ context, args ]; firing = 0; } } return this; }, // resolve with this as context and given arguments resolve: function() { deferred.resolveWith( this, arguments ); return this; }, // Has this deferred been resolved? isResolved: function() { return !!( firing || fired ); }, // Cancel cancel: function() { cancelled = 1; callbacks = []; return this; } }; return deferred; }, // Full fledged deferred (two callbacks list) Deferred: function( func ) { var deferred = jQuery._Deferred(), failDeferred = jQuery._Deferred(), promise; // Add errorDeferred methods, then and promise jQuery.extend( deferred, { then: function( doneCallbacks, failCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ); return this; }, always: function() { return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); }, fail: failDeferred.done, rejectWith: failDeferred.resolveWith, reject: failDeferred.resolve, isRejected: failDeferred.isResolved, pipe: function( fnDone, fnFail ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject ); } else { newDefer[ action ]( returned ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { if ( promise ) { return promise; } promise = obj = {}; } var i = promiseMethods.length; while( i-- ) { obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; } return obj; } }); // Make sure only one callback list will be used deferred.done( failDeferred.cancel ).fail( deferred.cancel ); // Unexpose cancel delete deferred.cancel; // Call given func if any if ( func ) { func.call( deferred, deferred ); } return deferred; }, // Deferred helper when: function( firstParam ) { var args = arguments, i = 0, length = args.length, count = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { // Strange bug in FF4: // Values changed onto the arguments object sometimes end up as undefined values // outside the $.when method. Cloning the object into a fresh array solves the issue deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); } }; } if ( length > 1 ) { for( ; i < length; i++ ) { if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return deferred.promise(); } }); jQuery.support = (function() { var div = document.createElement( "div" ), documentElement = document.documentElement, all, a, select, opt, input, marginDiv, support, fragment, body, testElementParent, testElement, testElementStyle, tds, events, eventName, i, isSupported; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName( "tbody" ).length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName( "link" ).length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute( "href" ) === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains it's value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; div.innerHTML = ""; // Figure out if the W3C box model works as expected div.style.width = div.style.paddingLeft = "1px"; body = document.getElementsByTagName( "body" )[ 0 ]; // We use our own, invisible, body unless the body is already present // in which case we use a div (#9239) testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0 }; if ( body ) { jQuery.extend( testElementStyle, { position: "absolute", left: -1000, top: -1000 }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; support.boxModel = div.offsetWidth === 2; if ( "zoom" in div.style ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); } div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE < 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); div.innerHTML = ""; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( document.defaultView && document.defaultView.getComputedStyle ) { marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } // Remove the body element we added testElement.innerHTML = ""; testElementParent.removeChild( testElement ); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for( i in { submit: 1, change: 1, focusin: 1 } ) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Null connected elements to avoid leaks in IE testElement = fragment = select = opt = body = marginDiv = div = input = null; return support; })(); // Keep track of boxModel jQuery.boxModel = jQuery.support.boxModel; var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([a-z])([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ jQuery.expando ] = id = ++jQuery.uuid; } else { id = jQuery.expando; } } if ( !cache[ id ] ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); } else { cache[ id ] = jQuery.extend(cache[ id ], name); } } thisCache = cache[ id ]; // Internal jQuery data is stored in a separate object inside the object's data // cache in order to avoid key collisions between internal data and user-defined // data if ( pvt ) { if ( !thisCache[ internalKey ] ) { thisCache[ internalKey ] = {}; } thisCache = thisCache[ internalKey ]; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should // not attempt to inspect the internal events object using jQuery.data, as this // internal data object is undocumented and subject to change. if ( name === "events" && !thisCache[name] ) { return thisCache[ internalKey ] && thisCache[ internalKey ].events; } return getByName ? // Check for both converted-to-camel and non-converted data property names thisCache[ jQuery.camelCase( name ) ] || thisCache[ name ] : thisCache; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; if ( thisCache ) { delete thisCache[ name ]; // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !isEmptyDataObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( pvt ) { delete cache[ id ][ internalKey ]; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } var internalCache = cache[ id ][ internalKey ]; // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care if ( jQuery.support.deleteExpando || cache != window ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the entire user cache at once because it's faster than // iterating through each key, but we need to continue to persist internal // data if it existed if ( internalCache ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } cache[ id ][ internalKey ] = internalCache; // Otherwise, we need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist } else if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } else { elem[ jQuery.expando ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 ) { var attr = this[0].attributes, name; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( this[0], name, data[ name ] ); } } } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var $this = jQuery( this ), args = [ parts[0], value ]; $this.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); $this.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : !jQuery.isNaN( data ) ? parseFloat( data ) : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON // property to be considered empty objects; this property always exists in // order to make sure JSON.stringify does not expose internal metadata function isEmptyDataObject( obj ) { for ( var name in obj ) { if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery.data( elem, deferDataKey, undefined, true ); if ( defer && ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) && ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery.data( elem, queueDataKey, undefined, true ) && !jQuery.data( elem, markDataKey, undefined, true ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.resolve(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = (type || "fx") + "mark"; jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 ); if ( count ) { jQuery.data( elem, key, count, true ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { if ( elem ) { type = (type || "fx") + "queue"; var q = jQuery.data( elem, type, undefined, true ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data), true ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), defer; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function() { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { count++; tmp.done( resolve ); } } resolve(); return defer.promise(); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, rinvalidChar = /\:|^on/, formHook, boolHook; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.prop ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { classNames = (value || "").split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[ c ] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return undefined; } var isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attrFix: { // Always normalize to ensure hook usage tabindex: "tabIndex" }, attr: function( elem, name, value, pass ) { var nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( !("getAttribute" in elem) ) { return jQuery.prop( elem, name, value ); } var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // Normalize the name if needed if ( notxml ) { name = jQuery.attrFix[ name ] || name; hooks = jQuery.attrHooks[ name ]; if ( !hooks ) { // Use boolHook for boolean attributes if ( rboolean.test( name ) ) { hooks = boolHook; // Use formHook for forms and if the name contains certain characters } else if ( formHook && name !== "className" && (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) { hooks = formHook; } } } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return undefined; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, name ) { var propName; if ( elem.nodeType === 1 ) { name = jQuery.attrFix[ name ] || name; if ( jQuery.support.getSetAttribute ) { // Use removeAttribute in browsers that support it elem.removeAttribute( name ); } else { jQuery.attr( elem, name, "" ); elem.removeAttributeNode( elem.getAttributeNode( name ) ); } // Set corresponding property to false for boolean attributes if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) { elem[ propName ] = false; } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabIndex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } }, // Use the value property for back compat // Use the formHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( formHook && jQuery.nodeName( elem, "button" ) ) { return formHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( formHook && jQuery.nodeName( elem, "button" ) ) { return formHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return (elem[ name ] = value); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) { return ret; } else { return elem[ name ]; } } }, propHooks: {} }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties return jQuery.prop( elem, name ) ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !jQuery.support.getSetAttribute ) { // propFix is more comprehensive and contains all fixes jQuery.attrFix = jQuery.propFix; // Use this for any attribute on a form in IE6/7 formHook = jQuery.attrHooks.name = jQuery.attrHooks.title = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); // Return undefined if nodeValue is empty string return ret && ret.nodeValue !== "" ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Check form objects in IE (multiple bugs related) // Only use nodeValue if the attribute node exists on the form var ret = elem.getAttributeNode( name ); if ( ret ) { ret.nodeValue = value; return value; } } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return (elem.style.cssText = "" + value); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }); } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0); } } }); }); var rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspaces = / /g, rescape = /[^\w\s.|`]/g, fcleanup = function( nm ) { return nm.replace(rescape, "\\$&"); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } else if ( !handler ) { // Fixes bug #7229. Fix recommended by jdalton return; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery._data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events, eventHandle = elemData.handle; if ( !events ) { elemData.events = events = {}; } if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; if ( !handleObj.guid ) { handleObj.guid = handler.guid; } // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem, undefined, true ); } } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Event object or event type var type = event.type || event, namespaces = [], exclusive; if ( type.indexOf("!") >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.exclusive = exclusive; event.namespace = namespaces.join("."); event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); // triggerHandler() and global events don't bubble or run the default action if ( onlyHandlers || !elem ) { event.preventDefault(); event.stopPropagation(); } // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document jQuery.each( jQuery.cache, function() { // internalKey variable is just used to make it easier to find // and potentially change this stuff later; currently it just // points to jQuery.expando var internalKey = jQuery.expando, internalCache = this[ internalKey ]; if ( internalCache && internalCache.events && internalCache.events[ type ] ) { jQuery.event.trigger( event, data, internalCache.handle.elem ); } }); return; } // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // Clean up the event in case it is being reused event.result = undefined; event.target = elem; // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); var cur = elem, // IE doesn't like method names with a colon (#3533, #8272) ontype = type.indexOf(":") < 0 ? "on" + type : ""; // Fire event on the current element, then bubble up the DOM tree do { var handle = jQuery._data( cur, "handle" ); event.currentTarget = cur; if ( handle ) { handle.apply( cur, data ); } // Trigger an inline bound script if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) { event.result = false; event.preventDefault(); } // Bubble up to document, then to window cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window; } while ( cur && !event.isPropagationStopped() ); // If nobody prevented the default action, do it now if ( !event.isDefaultPrevented() ) { var old, special = jQuery.event.special[ type ] || {}; if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction)() check here because IE6/7 fails that test. // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch. try { if ( ontype && elem[ type ] ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } jQuery.event.triggered = type; elem[ type ](); } } catch ( ieError ) {} if ( old ) { elem[ ontype ] = old; } jQuery.event.triggered = undefined; } } return event.result; }, handle: function( event ) { event = jQuery.event.fix( event || window.event ); // Snapshot the handlers list since a called handler may add/remove events. var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0), run_all = !event.exclusive && !event.namespace, args = Array.prototype.slice.call( arguments, 0 ); // Use the fix-ed Event rather than the (read-only) native event args[0] = event; event.currentTarget = this; for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Triggered event must 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event. if ( run_all || event.namespace_re.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } return event.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( event ) { if ( event[ jQuery.expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { // Fixes #1925 where srcElement might not be defined either event.target = event.srcElement || document; } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var eventDocument = event.target.ownerDocument || document, doc = eventDocument.documentElement, body = eventDocument.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { event.which = event.charCode != null ? event.charCode : event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, liveConvert( handleObj.origType, handleObj.selector ), jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); }, remove: function( handleObj ) { jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var related = event.relatedTarget, inside = false, eventType = event.type; event.type = event.data; if ( related !== this ) { if ( related ) { inside = jQuery.contains( this, related ); } if ( !inside ) { jQuery.event.handle.apply( this, arguments ); event.type = eventType; } } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( !jQuery.nodeName( this, "form" ) ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( jQuery.nodeName( elem, "select" ) ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery._data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery._data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; e.liveFired = undefined; jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, beforedeactivate: testChange, click: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) { testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information beforeactivate: function( e ) { var elem = e.target; jQuery._data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return rformElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return rformElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; // Handle when the input is .focus()'d changeFilters.focus = changeFilters.beforeactivate; } function trigger( type, elem, args ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. // Don't pass args or remember liveFired; they apply to the donor event. var event = jQuery.extend( {}, args[ 0 ] ); event.type = type; event.originalEvent = {}; event.liveFired = undefined; jQuery.event.handle.call( elem, event ); if ( event.isDefaultPrevented() ) { args[ 0 ].preventDefault(); } } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; function handler( donor ) { // Donor event is always a native one; fix it and switch its type. // Let focusin/out handler cancel the donor focus/blur event. var e = jQuery.event.fix( donor ); e.type = fix; e.originalEvent = {}; jQuery.event.trigger( e, null, e.target ); if ( e.isDefaultPrevented() ) { donor.preventDefault(); } } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { var handler; // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( arguments.length === 2 || data === false ) { fn = data; data = undefined; } if ( name === "one" ) { handler = function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }; handler.guid = fn.guid || jQuery.guid++; } else { handler = fn; } if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( typeof types === "object" && !types.preventDefault ) { for ( var key in types ) { context[ name ]( key, data, types[key], selector ); } return this; } if ( name === "die" && !types && origSelector && origSelector.charAt(0) === "." ) { context.unbind( origSelector ); return this; } if ( data === false || jQuery.isFunction( data ) ) { fn = data || returnFalse; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( liveMap[ type ] ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler for ( var j = 0, l = context.length; j < l; j++ ) { jQuery.event.add( context[j], "live." + liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); } } else { // unbind live handler context.unbind( "live." + liveConvert( type, selector ), fn ); } } return this; }; }); function liveHandler( event ) { var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, elems = [], selectors = [], events = jQuery._data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { return; } if ( event.namespace ) { namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { close = match[i]; for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { elem = close.elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { event.type = handleObj.preType; related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; // Make sure not to accidentally match a child element with the same selector if ( related && jQuery.contains( elem, related ) ) { related = elem; } } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj, level: close.level }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; if ( maxLevel && match.level > maxLevel ) { break; } event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; ret = match.handleObj.origHandler.apply( match.elem, arguments ); if ( ret === false || event.isPropagationStopped() ) { maxLevel = match.level; if ( ret === false ) { stop = false; } if ( event.isImmediatePropagationStopped() ) { break; } } } return stop; } function liveConvert( type, selector ) { return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&"); } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.bind( name, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var match, type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var found, item, filter = Expr.filter[ type ], left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Utility function for retreiving the text value of an array of DOM nodes Sizzle.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += Sizzle.getText( elem.childNodes ); } } return ret; }; // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array if ( jQuery.isArray( selectors ) ) { var match, selector, matches = {}, level = 1; if ( cur && selectors.length ) { for ( i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[ selector ] ) { matches[ selector ] = POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[ selector ]; if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) { ret.push({ selector: selector, elem: cur, level: level }); } } cur = cur.parentNode; level++; } } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ), // The variable 'args' was introduced in // https://github.com/jquery/jquery/commit/52a0238 // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. // http://code.google.com/p/v8/issues/detail?id=1050 args = slice.call(arguments); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, args.join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); } var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<(?:script|object|embed|option|style)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || (l > 1 && i < lastIndex) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var internalKey = jQuery.expando, oldData = jQuery.data( src ), curData = jQuery.data( dest, oldData ); // Switch to use the internal data object, if it exists, for the next // stage of data copying if ( (oldData = oldData[ internalKey ]) ) { var events = oldData.events; curData = curData[ internalKey ] = jQuery.extend({}, oldData); if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); } } } } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = document; } // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( "getElementsByTagName" in elem ) { return elem.getElementsByTagName( "*" ); } else if ( "querySelectorAll" in elem ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( "getElementsByTagName" in elem ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var clone = elem.cloneNode(true), srcElements, destElements, i; if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName // instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = [], j; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ] && cache[ id ][ internalKey ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, rrelNum = /^[+\-]=/, rrelNumFilter = /[^+\-\.\de]+/g, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Make sure that NaN and null values aren't set. See: #7116 if ( type === "number" && isNaN( value ) || value == null ) { return; } // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && rrelNum.test( value ) ) { value = +value.replace( rrelNumFilter, "" ) + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } return val; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat( value ); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = jQuery.isNaN( value ) ? "" : "alpha(opacity=" + value * 100 + ")", filter = currentStyle && currentStyle.filter || style.filter || ""; style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block var ret; jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { ret = curCSS( elem, "margin-right", "marginRight" ); } else { ret = elem.style.marginRight; } }); return ret; } }; } }); if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( !(defaultView = elem.ownerDocument.defaultView) ) { return undefined; } if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, ret = elem.currentStyle && elem.currentStyle[ name ], rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ], style = elem.style; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, which = name === "width" ? cssWidth : cssHeight; if ( val > 0 ) { if ( extra !== "border" ) { jQuery.each( which, function() { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + this ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + this ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0; } }); } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, name ); if ( val < 0 || val == null ) { val = elem.style[ name ] || 0; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { jQuery.each( which, function() { val += parseFloat( jQuery.css( elem, "padding" + this ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + this ) ) || 0; } }); } return val + "px"; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for(; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for(; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.bind( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function ( target, settings ) { if ( !settings ) { // Only one parameter, we extend ajaxSettings settings = target; target = jQuery.extend( true, jQuery.ajaxSettings, settings ); } else { // target was provided, we extend into it jQuery.extend( true, target, jQuery.ajaxSettings, settings ); } // Flatten fields we don't want deep extended for( var field in { context: 1, url: 1 } ) { if ( field in settings ) { target[ field ] = settings[ field ]; } else if( field in jQuery.ajaxSettings ) { target[ field ] = jQuery.ajaxSettings[ field ]; } } return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": "*/*" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery._Deferred(), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, statusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status ? 4 : 0; var isSuccess, success, error, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = statusText; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.done; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefiler, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( status < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { jQuery.error( e ); } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for( key in s.converters ) { if( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = s.contentType === "application/x-www-form-urlencoded" && ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } responses.text = xhr.responseText; // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow, requestAnimationFrame = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( display === "" && jQuery.css( elem, "display" ) === "none" ) { jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName)); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data(elem, "olddisplay") || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { if ( this[i].style ) { var display = jQuery.css( this[i], "display" ); if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) { jQuery._data( this[i], "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); return this[ optall.queue === false ? "each" : "queue" ](function() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, display, e, parts, start, end, unit; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; for ( p in prop ) { // property name normalization name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height // animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { if ( !jQuery.support.inlineBlockNeedsLayout ) { this.style.display = "inline-block"; } else { display = defaultDisplay( this.nodeName ); // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( display === "inline" ) { this.style.display = "inline-block"; } else { this.style.display = "inline"; this.style.zoom = 1; } } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ](); } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ((end || 1) / e.cur()) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { if ( clearQueue ) { this.queue([]); } this.each(function() { var timers = jQuery.timers, i = timers.length; // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } while ( i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue !== false ) { jQuery.dequeue( this ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); }, // Get the current size cur: function() { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx, raf; this.startTime = fxNow || createFxNow(); this.start = from; this.end = to; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); this.now = this.start; this.pos = this.state = 0; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { // Use requestAnimationFrame instead of setInterval if available if ( requestAnimationFrame ) { timerId = true; raf = function() { // When timerId gets set to null at any point, this stops if ( timerId ) { requestAnimationFrame( raf ); fx.tick(); } }; requestAnimationFrame( raf ); } else { timerId = setInterval( fx.tick, fx.interval ); } } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options, i, n; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( i in options.animatedProperties ) { if ( options.animatedProperties[i] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function (index, value) { elem.style[ "overflow" + value ] = options.overflow[index]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery(elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( var p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[p] ); } } // Execute the complete function options.complete.call( elem ); } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[ this.prop ] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ((this.end - this.start) * this.pos); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { for ( var timers = jQuery.timers, i = 0 ; i < timers.length ; ++i ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var body = document.body, elem = jQuery( "<" + nodeName + ">" ).appendTo( body ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0, html = "<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>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed"; checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden"; innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if (options.top != null) { props.top = (options.top - curOffset.top) + curTop; } if (options.left != null) { props.left = (options.left - curOffset.left) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function( val ) { var elem, win; if ( val === undefined ) { elem = this[ 0 ]; if ( !elem ) { return null; } win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery( win ).scrollLeft(), i ? val : jQuery( win ).scrollTop() ); } else { this[ method ] = val; } }); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem && elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem && elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ]; return elem.document.compatMode === "CSS1Compat" && docElemProp || elem.document.body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNaN( ret ) ? orig : ret; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; })(window);
ajax/libs/6to5/2.6.1/browser-polyfill.js
bsquochoaidownloadfolders/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){require("core-js/shim");require("regenerator/runtime")},{"core-js/shim":2,"regenerator/runtime":3}],2:[function(require,module,exports){!function(returnThis,framework,undefined){"use strict";var global=returnThis(),OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,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=".";function isObject(it){return it!=null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var buildIn={Undefined:1,Null:1,Array:1,String:1,Arguments:1,Function:1,Error:1,Boolean:1,Number:1,Date:1,RegExp:1},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 it==undefined?it===undefined?"Undefined":"Null":toString.call(it).slice(8,-1)}function classof(it){var klass=cof(it),tag;return klass==OBJECT&&(tag=it[SYMBOL_TAG])?has(buildIn,tag)?"~"+tag:tag:klass}var call=FunctionProto.call,apply=FunctionProto.apply,REFERENCE_GET;function part(){var length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return partial(this,args,length,holder,_,false)}function partial(fn,argsPart,lengthPart,holder,_,bind,context){assertFunction(fn);return function(){var that=bind?context:this,length=arguments.length,i=0,j=0,args;if(!holder&&!length)return invoke(fn,argsPart,that);args=argsPart.slice();if(holder)for(;lengthPart>i;i++)if(args[i]===_)args[i]=arguments[j++];while(length>j)args.push(arguments[j++]);return invoke(fn,args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}function construct(target,argumentsList){var instance=create(target[PROTOTYPE]),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance}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,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object;function returnIt(it){return it}function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=ES5Object(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn){var O=Object(assertDefined(this)),that=arguments[1],self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el,fromIndex){var O=ES5Object(assertDefined(this)),length=toLength(O.length),index=toIndex(fromIndex,length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},0,ObjectProto)}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_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,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);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){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var DEF_VAL=DEFAULT==VALUE,entries=createIter(KEY+VALUE),keys=createIter(KEY),values=createIter(VALUE);if(DEF_VAL)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:keys,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]&&Symbol[ITERATOR]in O);return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=Symbol&&Symbol[ITERATOR]&&it[Symbol[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}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(typeof module!="undefined"&&module.exports)module.exports=core;if(isFunction(define)&&define.amd)define(function(){return core});if(!NODE||framework){core.noConflict=function(){global.core=old;return core};global.core=core}$define(GLOBAL+FORCED,{global:global});!function(TAG,SymbolRegistry,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description);setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return set(create(Symbol[PROTOTYPE]),TAG,tag)};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,"+"species,split,toPrimitive,unscopables"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(GLOBAL,{Reflect:{ownKeys:ownKeys}})}(safeSymbol("tag"),{},true);!function(isFinite,tmp){var RangeError=global.RangeError,isInteger=Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it},sign=Math.sign||function sign(it){return(it=+it)==0||it!=it?it:it<0?-1:1},pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,fcc=String.fromCharCode,at=createPointAt(true);var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=setPrototypeOf=setPrototypeOf||function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt});$define(STATIC,MATH,{acosh:function(x){return x<1?NaN:log(x+sqrt(x*x-1))},asinh:asinh,atanh:function(x){return x==0?+x:log((1+ +x)/(1-x))/2},cbrt:function(x){return sign(x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x)+exp(-x))/2},expm1:function(x){return x==0?+x:x>-1e-6&&x<1e-6?+x+x*x/2:exp(x)-1},fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,length=arguments.length,value;while(length--){value=+arguments[length];if(value==Infinity||value==-Infinity)return Infinity;sum+=value*value}return sqrt(sum)},imul:function(x,y){var UInt16=65535,xl=UInt16&x,yl=UInt16&y;return 0|xl*yl+((UInt16&x>>>16)*yl+xl*(UInt16&y>>>16)<<16>>>0)},log1p:function(x){return x>-1e-8&&x<1e-8?x-x*x/2:log(1+ +x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return x==0?+x:(exp(x)-exp(-x))/2},tanh:function(x){return isFinite(x)?x==0?+x:(exp(x)-exp(-x))/(exp(x)+exp(-x)):sign(x)},trunc:trunc});setToStringTag(Math,MATH,true);function assertNotRegExp(it){if(isObject(it)&&it instanceof RegExp)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fcc(code):fcc(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=ES5Object(assertDefined(callSite.raw)),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){var position=arguments[1];assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,position)},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString,position){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(position,that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}});defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)});$define(STATIC,ARRAY,{from:function(arrayLike){var O=Object(assertDefined(arrayLike)),result=new(generic(this,Array)),mapfn=arguments[1],that=arguments[2],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,that,2):undefined,index=0,length;if(isIterable(O))for(var iter=getIterator(O),step;!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(length=toLength(O.length);length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start,end){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value,start,end){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(start,length),endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:ES5Object(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length)return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];setToStringTag(global.JSON,"JSON",true);if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"});if(/./g.flags!="g")defineProperty(RegExp[PROTOTYPE],"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")})}}(isFinite,{});isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(part.call(run,id),0)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(Function()))==test||function(asap,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;try{if(then=isThenable(msg)){wrapper={def:def,done:false};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)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}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],{then:function(onFulfilled,onRejected){var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new this[CONSTRUCTOR](function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&&notify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=this,values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=this;return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new this(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&getPrototypeOf(x)===this[PROTOTYPE]?x:new this(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),DATA=safeSymbol("data"),WEAK=safeSymbol("weak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0;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];framework&&hidden(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,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,DATA,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;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!O||!(iter.l=entry=entry?entry.n:O[FIRST]))return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE,!isMap);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(!has(it,UID)){if(create)hidden(it,UID,++uid);else return""}return"O"+it[UID]}function def(that,key,value){var index=fastKey(key,true),data=that[DATA],last=that[LAST],entry;if(index in data)data[index].v=value;else{entry=data[index]={k:key,v:value,p:last};if(!that[FIRST])that[FIRST]=entry;if(last)last.n=entry;that[LAST]=entry;that[SIZE]++}return that}function del(that,index){var data=that[DATA],entry=data[index],next=entry.n,prev=entry.p;delete data[index];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]--}var collectionMethods={clear:function(){for(var index in this[DATA])del(this,index)},"delete":function(key){var index=fastKey(key),contains=index in this[DATA];if(contains)del(this,index);return contains},forEach:function(callbackfn,that){var f=ctx(callbackfn,that,3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return fastKey(key)in this[DATA]}};Map=getCollection(Map,MAP,{get:function(key){var entry=this[DATA][fastKey(key)];return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function setWeak(that,key,value){has(assertObject(key),WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value;return that}function hasWeak(key){return isObject(key)&&has(key,WEAK)&&has(key[WEAK],this[UID])}var weakMethods={"delete":function(key){return hasWeak.call(this,key)&&delete key[WEAK][this[UID]]},has:hasWeak};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)&&has(key,WEAK))return key[WEAK][this[UID]]},set:function(key,value){return setWeak(this,key,value)}},weakMethods,true,true);WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return setWeak(this,value,true)}},weakMethods,false,true)}();!function(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey,receiver){if(receiver===undefined)receiver=target;var desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return desc.get?desc.get.call(receiver):desc.value;return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V,receiver){if(receiver===undefined)receiver=target;var desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc){if(desc.writable===false)return false;if(desc.set)return desc.set.call(receiver,V),true}if(isObject(proto=getPrototypeOf(target)))return reflectSet(proto,propertyKey,V,receiver);desc=getOwnDescriptor(receiver,propertyKey)||descriptor(0);desc.value=V;return defineProperty(receiver,propertyKey,desc),true}var reflect={apply:ctx(call,apply,3),construct:construct,defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:getOwnDescriptor,getPrototypeOf:getPrototypeOf,has:function(target,propertyKey){return propertyKey in target},isExtensible:Object.isExtensible||function(target){return!!assertObject(target)},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet};if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=ES5Object(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,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[key]=ctx(call,ArrayProto[key],length)})}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$define(STATIC,ARRAY,arrayStatics)}({})}(Function("return this"),true)},{}],3:[function(require,module,exports){!function(){var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";if(typeof regeneratorRuntime==="object"){return}var runtime=regeneratorRuntime=typeof exports==="undefined"?{}:exports;function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[]) }runtime.wrap=wrap;var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){try{var info=this(arg);var value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){try{var info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1;function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next}return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}()},{}]},{},[1]);
ajax/libs/yui/3.7.1/event-focus/event-focus-debug.js
hasantayyar/cdnjs
YUI.add('event-focus', function (Y, NAME) { /** * Adds bubbling and delegation support to DOM events focus and blur. * * @module event * @submodule event-focus */ var Event = Y.Event, YLang = Y.Lang, isString = YLang.isString, arrayIndex = Y.Array.indexOf, useActivate = YLang.isFunction( Y.DOM.create('<p onbeforeactivate=";"/>').onbeforeactivate); function define(type, proxy, directEvent) { var nodeDataKey = '_' + type + 'Notifiers'; Y.Event.define(type, { _attach: function (el, notifier, delegate) { if (Y.DOM.isWindow(el)) { return Event._attach([type, function (e) { notifier.fire(e); }, el]); } else { return Event._attach( [proxy, this._proxy, el, this, notifier, delegate], { capture: true }); } }, _proxy: function (e, notifier, delegate) { var target = e.target, currentTarget = e.currentTarget, notifiers = target.getData(nodeDataKey), yuid = Y.stamp(currentTarget._node), defer = (useActivate || target !== currentTarget), directSub; notifier.currentTarget = (delegate) ? target : currentTarget; notifier.container = (delegate) ? currentTarget : null; // Maintain a list to handle subscriptions from nested // containers div#a>div#b>input #a.on(focus..) #b.on(focus..), // use one focus or blur subscription that fires notifiers from // #b then #a to emulate bubble sequence. if (!notifiers) { notifiers = {}; target.setData(nodeDataKey, notifiers); // only subscribe to the element's focus if the target is // not the current target ( if (defer) { directSub = Event._attach( [directEvent, this._notify, target._node]).sub; directSub.once = true; } } else { // In old IE, defer is always true. In capture-phase browsers, // The delegate subscriptions will be encountered first, which // will establish the notifiers data and direct subscription // on the node. If there is also a direct subscription to the // node's focus/blur, it should not call _notify because the // direct subscription from the delegate sub(s) exists, which // will call _notify. So this avoids _notify being called // twice, unnecessarily. defer = true; } if (!notifiers[yuid]) { notifiers[yuid] = []; } notifiers[yuid].push(notifier); if (!defer) { this._notify(e); } }, _notify: function (e, container) { var currentTarget = e.currentTarget, notifierData = currentTarget.getData(nodeDataKey), axisNodes = currentTarget.ancestors(), doc = currentTarget.get('ownerDocument'), delegates = [], // Used to escape loops when there are no more // notifiers to consider count = notifierData ? Y.Object.keys(notifierData).length : 0, target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret; // clear the notifications list (mainly for delegation) currentTarget.clearData(nodeDataKey); // Order the delegate subs by their placement in the parent axis axisNodes.push(currentTarget); // document.get('ownerDocument') returns null // which we'll use to prevent having duplicate Nodes in the list if (doc) { axisNodes.unshift(doc); } // ancestors() returns the Nodes from top to bottom axisNodes._nodes.reverse(); if (count) { // Store the count for step 2 tmp = count; axisNodes.some(function (node) { var yuid = Y.stamp(node), notifiers = notifierData[yuid], i, len; if (notifiers) { count--; for (i = 0, len = notifiers.length; i < len; ++i) { if (notifiers[i].handle.sub.filter) { delegates.push(notifiers[i]); } } } return !count; }); count = tmp; } // Walk up the parent axis, notifying direct subscriptions and // testing delegate filters. while (count && (target = axisNodes.shift())) { yuid = Y.stamp(target); notifiers = notifierData[yuid]; if (notifiers) { for (i = 0, len = notifiers.length; i < len; ++i) { notifier = notifiers[i]; sub = notifier.handle.sub; match = true; e.currentTarget = target; if (sub.filter) { match = sub.filter.apply(target, [target, e].concat(sub.args || [])); // No longer necessary to test against this // delegate subscription for the nodes along // the parent axis. delegates.splice( arrayIndex(delegates, notifier), 1); } if (match) { // undefined for direct subs e.container = notifier.container; ret = notifier.fire(e); } if (ret === false || e.stopped === 2) { break; } } delete notifiers[yuid]; count--; } if (e.stopped !== 2) { // delegates come after subs targeting this specific node // because they would not normally report until they'd // bubbled to the container node. for (i = 0, len = delegates.length; i < len; ++i) { notifier = delegates[i]; sub = notifier.handle.sub; if (sub.filter.apply(target, [target, e].concat(sub.args || []))) { e.container = notifier.container; e.currentTarget = target; ret = notifier.fire(e); } if (ret === false || e.stopped === 2) { break; } } } if (e.stopped) { break; } } }, on: function (node, sub, notifier) { sub.handle = this._attach(node._node, notifier); }, detach: function (node, sub) { sub.handle.detach(); }, delegate: function (node, sub, notifier, filter) { if (isString(filter)) { sub.filter = function (target) { return Y.Selector.test(target._node, filter, node === target ? null : node._node); }; } sub.handle = this._attach(node._node, notifier, true); }, detachDelegate: function (node, sub) { sub.handle.detach(); } }, true); } // For IE, we need to defer to focusin rather than focus because // `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate, // el.onfocusin, doSomething, then el.onfocus. All others support capture // phase focus, which executes before doSomething. To guarantee consistent // behavior for this use case, IE's direct subscriptions are made against // focusin so subscribers will be notified before js following el.focus() is // executed. if (useActivate) { // name capture phase direct subscription define("focus", "beforeactivate", "focusin"); define("blur", "beforedeactivate", "focusout"); } else { define("focus", "focus", "focus"); define("blur", "blur", "blur"); } }, '@VERSION@', {"requires": ["event-synthetic"]});
packages/icons/src/instances.js
geek/joyent-portal
import React from 'react'; import Rotate from './rotate'; import calcFill from './fill'; export default ({ fill = null, light = false, disabled = false, direction = 'down', colors = {}, style = {}, ...rest }) => ( <Rotate direction={direction}> {({ style: rotateStyle }) => ( <svg width="18" height="9" viewBox="0 0 18 9" xmlns="http://www.w3.org/2000/svg" style={{ ...style, ...rotateStyle }} {...rest} > <path fill={calcFill({ fill, disabled, light, colors })} fillRule="evenodd" d="M4.5 0a4.5 4.5 0 1 0 0 9 4.5 4.5 0 0 0 0-9m8.59 0c-.375 0-.739.047-1.09.12 2.184.456 3.818 2.239 3.818 4.38S14.184 8.424 12 8.88c.351.073.715.12 1.09.12C15.803 9 18 6.985 18 4.5S15.802 0 13.09 0M14 4.5C14 6.985 11.802 9 9.09 9c-.375 0-.739-.047-1.09-.12 2.184-.456 3.818-2.239 3.818-4.38S10.184.576 8 .12C8.351.047 8.715 0 9.09 0 11.803 0 14 2.015 14 4.5" /> </svg> )} </Rotate> );
tests/react-api.tests.js
Mavrin/component-inspector
import {assert} from 'chai'; import React from 'react'; import { render, unmountComponentAtNode } from 'react-dom'; import App from './../examples/react-todomvc/containers/App'; console.log('React version', React.version); describe('react api test', function() { before(function() { this.domContainer = document.createElement('div'); document.body.appendChild(this.domContainer); render(<App />, this.domContainer); }); var api = window.reactInspectorApi; it('getComponentNameByNode', function() { var footer = this.domContainer.querySelector('footer'); var input = this.domContainer.querySelector('.new-todo'); assert.equal(api.getComponentNameByNode(footer), 'Footer'); assert.equal(api.getComponentNameByNode(input), 'TodoTextInput'); }); it('isComponentRootNode', function() { var footer = this.domContainer.querySelector('footer'); var input = this.domContainer.querySelector('.new-todo'); var checkbox = this.domContainer.querySelector('.todo-list checkbox'); assert.equal(api.isComponentRootNode(footer), true); assert.equal(api.isComponentRootNode(input), true); assert.equal(api.isComponentRootNode(checkbox), false); }); it('getInstanceRenderLocation', function() { var footer = this.domContainer.querySelector('footer'); var input = this.domContainer.querySelector('.new-todo'); var checkbox = this.domContainer.querySelector('.todo-list checkbox'); assert.equal(api.getInstanceRenderLocation(api.getInstanceByNode(footer)), '/examples/react-todomvc/components/Footer.js:20:3:34:4'); assert.equal(api.getInstanceRenderLocation(api.getInstanceByNode(input)), '/examples/react-todomvc/components/TodoTextInput.js:40:3:54:4'); assert.equal(api.getInstanceRenderLocation(api.getInstanceByNode(checkbox)), undefined); }); it('getAdditionalInstanceInfo', function() { var node = this.domContainer.querySelector('footer'); var reactElementByNode = api.getInstanceByNode(node); var info = reactInspectorApi.getAdditionalInstanceInfo(reactElementByNode); assert.equal(info[0].name, 'Footer'); assert.include(info[0].loc, '/examples/react-todomvc/components/MainSection.js:76:9:80:46'); assert.equal(info[0].props[0].key, 'markedCount'); assert.equal(info[0].props[0].type, 'other'); assert.equal(info[0].props[0].valueText, '0'); assert.equal(info[0].props[0].valueLoc, undefined); assert.equal(info[0].props[2].key, 'filter'); assert.equal(info[0].props[2].type, 'string'); assert.equal(info[0].props[2].valueText, 'show_all'); assert.equal(info[0].props[2].valueLoc, undefined); assert.equal(info[1].className, 'Footer'); assert.equal(info[1].isClass, true); }); it('getInstanceRootNode', function() { var footer = this.domContainer.querySelector('footer'); assert.equal(api.getInstanceRootNode(api.getInstanceByNode(footer)), footer); }); after(function() { unmountComponentAtNode(this.domContainer); }); });
app/components/Widgets/UserWidget.js
longgame/koa-react-demo
'use strict;' import React, { Component } from 'react'; import { LinkedStateMixin } from 'react-addons'; import { History } from 'react-router'; import Reflux from 'reflux'; import { UserStore, UserActions } from '../Widgets'; import template from './UserWidget.rt'; import styles from './UserWidget.scss'; module.exports = React.createClass({ mixins: [ History, LinkedStateMixin, Reflux.connect(UserStore, 'title') ], getInitialState: function() { return { user: {}, email: null, password: null, title: 'Login', }; }, handleLogin: function(event) { UserActions.loginUser({ email: this.state.email, password: this.state.password }); }, handleRegister: function(event) { UserActions.loginUser({ email: this.state.email, password: this.state.password }); }, render: template });
node_modules/react-router/es/RouterContext.js
prodigalyijun/demo-by-antd
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; import invariant from 'invariant'; import React from 'react'; import createReactClass from 'create-react-class'; import { array, func, object } from 'prop-types'; import getRouteParams from './getRouteParams'; import { ContextProvider } from './ContextUtils'; import { isReactChildren } from './RouteUtils'; /** * A <RouterContext> renders the component tree for a given router state * and sets the history object and the current location in context. */ var RouterContext = createReactClass({ displayName: 'RouterContext', mixins: [ContextProvider('router')], propTypes: { router: object.isRequired, location: object.isRequired, routes: array.isRequired, params: object.isRequired, components: array.isRequired, createElement: func.isRequired }, getDefaultProps: function getDefaultProps() { return { createElement: React.createElement }; }, childContextTypes: { router: object.isRequired }, getChildContext: function getChildContext() { return { router: this.props.router }; }, createElement: function createElement(component, props) { return component == null ? null : this.props.createElement(component, props); }, render: function render() { var _this = this; var _props = this.props, location = _props.location, routes = _props.routes, params = _props.params, components = _props.components, router = _props.router; var element = null; if (components) { element = components.reduceRight(function (element, components, index) { if (components == null) return element; // Don't create new children; use the grandchildren. var route = routes[index]; var routeParams = getRouteParams(route, params); var props = { location: location, params: params, route: route, router: router, routeParams: routeParams, routes: routes }; if (isReactChildren(element)) { props.children = element; } else if (element) { for (var prop in element) { if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop]; } } if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') { var elements = {}; for (var key in components) { if (Object.prototype.hasOwnProperty.call(components, key)) { // Pass through the key as a prop to createElement to allow // custom createElement functions to know which named component // they're rendering, for e.g. matching up to fetched data. elements[key] = _this.createElement(components[key], _extends({ key: key }, props)); } } return elements; } return _this.createElement(components, props); }, element); } !(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : void 0; return element; } }); export default RouterContext;
ajax/libs/handsontable/0.15.0-beta1/handsontable.full.js
dhenson02/cdnjs
/*! * Handsontable 0.15.0-beta1 * Handsontable is a JavaScript library for editable tables with basic copy-paste compatibility with Excel and Google Docs * * Copyright (c) 2012-2014 Marcin Warpechowski * Copyright 2015 Handsoncode sp. z o.o. <[email protected]> * Licensed under the MIT license. * http://handsontable.com/ * * Date: Wed Apr 29 2015 13:16:22 GMT+0200 (CEST) */ /*jslint white: true, browser: true, plusplus: true, indent: 4, maxerr: 50 */ window.Handsontable = { version: '0.15.0-beta1' }; require=(function outer (modules, cache, entry) { // Save the require from previous bundle to this closure if any var previousRequire = typeof require == "function" && require; var globalNS = JSON.parse('{"zeroclipboard":"ZeroClipboard","moment":"moment","numeral":"numeral","pikaday":"Pikaday"}') || {}; function newRequire(name, jumped){ if(!cache[name]) { if(!modules[name]) { // if we cannot find the the module within our internal map or // cache jump to the current global require ie. the last bundle // that was added to the page. var currentRequire = typeof require == "function" && require; if (!jumped && currentRequire) return currentRequire(name, true); // If there are other bundles on this page the require from the // previous one is saved to 'previousRequire'. Repeat this as // many times as there are bundles until the module is found or // we exhaust the require chain. if (previousRequire) return previousRequire(name, true); // Try find module from global scope if (globalNS[name] && typeof window[globalNS[name]] !== 'undefined') { return window[globalNS[name]]; } var err = new Error('Cannot find module \'' + name + '\''); err.code = 'MODULE_NOT_FOUND'; throw err; } var m = cache[name] = {exports:{}}; modules[name][0].call(m.exports, function(x){ var id = modules[name][1][x]; return newRequire(id ? id : x); },m,m.exports,outer,modules,cache,entry); } return cache[name].exports; } for(var i=0;i<entry.length;i++) newRequire(entry[i]); // Override the current require with this new one return newRequire; }) ({1:[function(require,module,exports){ "use strict"; if (window.jQuery) { (function(window, $, Handsontable) { $.fn.handsontable = function(action) { var i, ilen, args, output, userSettings, $this = this.first(), instance = $this.data('handsontable'); if (typeof action !== 'string') { userSettings = action || {}; if (instance) { instance.updateSettings(userSettings); } else { instance = new Handsontable.Core($this[0], userSettings); $this.data('handsontable', instance); instance.init(); } return $this; } else { args = []; if (arguments.length > 1) { for (i = 1, ilen = arguments.length; i < ilen; i++) { args.push(arguments[i]); } } if (instance) { if (typeof instance[action] !== 'undefined') { output = instance[action].apply(instance, args); if (action === 'destroy') { $this.removeData(); } } else { throw new Error('Handsontable do not provide action: ' + action); } } return output; } }; })(window, jQuery, Handsontable); } //# },{}],2:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { autoResize: {get: function() { return autoResize; }}, __esModule: {value: true} }); ; function autoResize() { var defaults = { minHeight: 200, maxHeight: 300, minWidth: 100, maxWidth: 300 }, el, body = document.body, text = document.createTextNode(''), span = document.createElement('SPAN'), observe = function(element, event, handler) { if (window.attachEvent) { element.attachEvent('on' + event, handler); } else { element.addEventListener(event, handler, false); } }, unObserve = function(element, event, handler) { if (window.removeEventListener) { element.removeEventListener(event, handler, false); } else { element.detachEvent('on' + event, handler); } }, resize = function(newChar) { var width, scrollHeight; if (!newChar) { newChar = ""; } else if (!/^[a-zA-Z \.,\\\/\|0-9]$/.test(newChar)) { newChar = "."; } if (text.textContent !== void 0) { text.textContent = el.value + newChar; } else { text.data = el.value + newChar; } span.style.fontSize = Handsontable.Dom.getComputedStyle(el).fontSize; span.style.fontFamily = Handsontable.Dom.getComputedStyle(el).fontFamily; span.style.whiteSpace = "pre"; body.appendChild(span); width = span.clientWidth + 2; body.removeChild(span); el.style.height = defaults.minHeight + 'px'; if (defaults.minWidth > width) { el.style.width = defaults.minWidth + 'px'; } else if (width > defaults.maxWidth) { el.style.width = defaults.maxWidth + 'px'; } else { el.style.width = width + 'px'; } scrollHeight = el.scrollHeight ? el.scrollHeight - 1 : 0; if (defaults.minHeight > scrollHeight) { el.style.height = defaults.minHeight + 'px'; } else if (defaults.maxHeight < scrollHeight) { el.style.height = defaults.maxHeight + 'px'; el.style.overflowY = 'visible'; } else { el.style.height = scrollHeight + 'px'; } }, delayedResize = function() { window.setTimeout(resize, 0); }, extendDefaults = function(config) { if (config && config.minHeight) { if (config.minHeight == 'inherit') { defaults.minHeight = el.clientHeight; } else { var minHeight = parseInt(config.minHeight); if (!isNaN(minHeight)) { defaults.minHeight = minHeight; } } } if (config && config.maxHeight) { if (config.maxHeight == 'inherit') { defaults.maxHeight = el.clientHeight; } else { var maxHeight = parseInt(config.maxHeight); if (!isNaN(maxHeight)) { defaults.maxHeight = maxHeight; } } } if (config && config.minWidth) { if (config.minWidth == 'inherit') { defaults.minWidth = el.clientWidth; } else { var minWidth = parseInt(config.minWidth); if (!isNaN(minWidth)) { defaults.minWidth = minWidth; } } } if (config && config.maxWidth) { if (config.maxWidth == 'inherit') { defaults.maxWidth = el.clientWidth; } else { var maxWidth = parseInt(config.maxWidth); if (!isNaN(maxWidth)) { defaults.maxWidth = maxWidth; } } } if (!span.firstChild) { span.className = "autoResize"; span.style.display = 'inline-block'; span.appendChild(text); } }, init = function(el_, config, doObserve) { el = el_; extendDefaults(config); if (el.nodeName == 'TEXTAREA') { el.style.resize = 'none'; el.style.overflowY = ''; el.style.height = defaults.minHeight + 'px'; el.style.minWidth = defaults.minWidth + 'px'; el.style.maxWidth = defaults.maxWidth + 'px'; el.style.overflowY = 'hidden'; } if (doObserve) { observe(el, 'change', resize); observe(el, 'cut', delayedResize); observe(el, 'paste', delayedResize); observe(el, 'drop', delayedResize); observe(el, 'keydown', delayedResize); } resize(); }; return { init: function(el_, config, doObserve) { init(el_, config, doObserve); }, unObserve: function() { unObserve(el, 'change', resize); unObserve(el, 'cut', delayedResize); unObserve(el, 'paste', delayedResize); unObserve(el, 'drop', delayedResize); unObserve(el, 'keydown', delayedResize); }, resize: resize }; } //# },{}],3:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { copyPasteManager: {get: function() { return copyPasteManager; }}, __esModule: {value: true} }); var $___46__46__47_helpers_46_js__, $___46__46__47_eventManager_46_js__; var helper = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}); var eventManagerObject = ($___46__46__47_eventManager_46_js__ = require("./../eventManager.js"), $___46__46__47_eventManager_46_js__ && $___46__46__47_eventManager_46_js__.__esModule && $___46__46__47_eventManager_46_js__ || {default: $___46__46__47_eventManager_46_js__}).eventManager; ; var instance; function copyPasteManager() { if (!instance) { instance = new CopyPasteClass(); } else if (instance.hasBeenDestroyed()) { instance.init(); } instance.refCounter++; return instance; } function CopyPasteClass() { this.refCounter = 0; this.init(); } CopyPasteClass.prototype.init = function() { var style, parent; this.copyCallbacks = []; this.cutCallbacks = []; this.pasteCallbacks = []; this._eventManager = eventManagerObject(this); parent = document.body; if (document.getElementById('CopyPasteDiv')) { this.elDiv = document.getElementById('CopyPasteDiv'); this.elTextarea = this.elDiv.firstChild; } else { this.elDiv = document.createElement('div'); this.elDiv.id = 'CopyPasteDiv'; style = this.elDiv.style; style.position = 'fixed'; style.top = '-10000px'; style.left = '-10000px'; parent.appendChild(this.elDiv); this.elTextarea = document.createElement('textarea'); this.elTextarea.className = 'copyPaste'; this.elTextarea.onpaste = function(event) { if ('WebkitAppearance' in document.documentElement.style) { this.value = event.clipboardData.getData("Text"); return false; } }; style = this.elTextarea.style; style.width = '10000px'; style.height = '10000px'; style.overflow = 'hidden'; this.elDiv.appendChild(this.elTextarea); if (typeof style.opacity !== 'undefined') { style.opacity = 0; } } this.keyDownRemoveEvent = this._eventManager.addEventListener(document.documentElement, 'keydown', this.onKeyDown.bind(this), false); }; CopyPasteClass.prototype.onKeyDown = function(event) { var _this = this, isCtrlDown = false; function isActiveElementEditable() { var element = document.activeElement; if (element.shadowRoot && element.shadowRoot.activeElement) { element = element.shadowRoot.activeElement; } return ['INPUT', 'SELECT', 'TEXTAREA'].indexOf(element.nodeName) > -1; } if (event.metaKey) { isCtrlDown = true; } else if (event.ctrlKey && navigator.userAgent.indexOf('Mac') === -1) { isCtrlDown = true; } if (isCtrlDown) { if (document.activeElement !== this.elTextarea && (this.getSelectionText() !== '' || isActiveElementEditable())) { return; } this.selectNodeText(this.elTextarea); setTimeout(function() { _this.selectNodeText(_this.elTextarea); }, 0); } if (isCtrlDown && (event.keyCode === helper.keyCode.C || event.keyCode === helper.keyCode.V || event.keyCode === helper.keyCode.X)) { if (event.keyCode === 88) { setTimeout(function() { _this.triggerCut(event); }, 0); } else if (event.keyCode === 86) { setTimeout(function() { _this.triggerPaste(event); }, 0); } } }; CopyPasteClass.prototype.selectNodeText = function(element) { if (element) { element.select(); } }; CopyPasteClass.prototype.getSelectionText = function() { var text = ''; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type !== 'Control') { text = document.selection.createRange().text; } return text; }; CopyPasteClass.prototype.copyable = function(string) { if (typeof string !== 'string' && string.toString === void 0) { throw new Error('copyable requires string parameter'); } this.elTextarea.value = string; }; CopyPasteClass.prototype.onCut = function(callback) { this.cutCallbacks.push(callback); }; CopyPasteClass.prototype.onPaste = function(callback) { this.pasteCallbacks.push(callback); }; CopyPasteClass.prototype.removeCallback = function(callback) { var i, len; for (i = 0, len = this.copyCallbacks.length; i < len; i++) { if (this.copyCallbacks[i] === callback) { this.copyCallbacks.splice(i, 1); return true; } } for (i = 0, len = this.cutCallbacks.length; i < len; i++) { if (this.cutCallbacks[i] === callback) { this.cutCallbacks.splice(i, 1); return true; } } for (i = 0, len = this.pasteCallbacks.length; i < len; i++) { if (this.pasteCallbacks[i] === callback) { this.pasteCallbacks.splice(i, 1); return true; } } return false; }; CopyPasteClass.prototype.triggerCut = function(event) { var _this = this; if (_this.cutCallbacks) { setTimeout(function() { for (var i = 0, len = _this.cutCallbacks.length; i < len; i++) { _this.cutCallbacks[i](event); } }, 50); } }; CopyPasteClass.prototype.triggerPaste = function(event, string) { var _this = this; if (_this.pasteCallbacks) { setTimeout(function() { var val = string || _this.elTextarea.value; for (var i = 0, len = _this.pasteCallbacks.length; i < len; i++) { _this.pasteCallbacks[i](val, event); } }, 50); } }; CopyPasteClass.prototype.destroy = function() { if (!this.hasBeenDestroyed() && --this.refCounter === 0) { if (this.elDiv && this.elDiv.parentNode) { this.elDiv.parentNode.removeChild(this.elDiv); this.elDiv = null; this.elTextarea = null; } this.keyDownRemoveEvent(); } }; CopyPasteClass.prototype.hasBeenDestroyed = function() { return !this.refCounter; }; //# },{"./../eventManager.js":48,"./../helpers.js":49}],4:[function(require,module,exports){ "use strict"; var jsonpatch; (function(jsonpatch) { var objOps = { add: function(obj, key) { obj[key] = this.value; return true; }, remove: function(obj, key) { delete obj[key]; return true; }, replace: function(obj, key) { obj[key] = this.value; return true; }, move: function(obj, key, tree) { var temp = { op: "_get", path: this.from }; apply(tree, [temp]); apply(tree, [{ op: "remove", path: this.from }]); apply(tree, [{ op: "add", path: this.path, value: temp.value }]); return true; }, copy: function(obj, key, tree) { var temp = { op: "_get", path: this.from }; apply(tree, [temp]); apply(tree, [{ op: "add", path: this.path, value: temp.value }]); return true; }, test: function(obj, key) { return (JSON.stringify(obj[key]) === JSON.stringify(this.value)); }, _get: function(obj, key) { this.value = obj[key]; } }; var arrOps = { add: function(arr, i) { arr.splice(i, 0, this.value); return true; }, remove: function(arr, i) { arr.splice(i, 1); return true; }, replace: function(arr, i) { arr[i] = this.value; return true; }, move: objOps.move, copy: objOps.copy, test: objOps.test, _get: objOps._get }; var observeOps = { add: function(patches, path) { var patch = { op: "add", path: path + escapePathComponent(this.name), value: this.object[this.name] }; patches.push(patch); }, 'delete': function(patches, path) { var patch = { op: "remove", path: path + escapePathComponent(this.name) }; patches.push(patch); }, update: function(patches, path) { var patch = { op: "replace", path: path + escapePathComponent(this.name), value: this.object[this.name] }; patches.push(patch); } }; function escapePathComponent(str) { if (str.indexOf('/') === -1 && str.indexOf('~') === -1) { return str; } return str.replace(/~/g, '~0').replace(/\//g, '~1'); } function _getPathRecursive(root, obj) { var found; for (var key in root) { if (root.hasOwnProperty(key)) { if (root[key] === obj) { return escapePathComponent(key) + '/'; } else if (typeof root[key] === 'object') { found = _getPathRecursive(root[key], obj); if (found != '') { return escapePathComponent(key) + '/' + found; } } } } return ''; } function getPath(root, obj) { if (root === obj) { return '/'; } var path = _getPathRecursive(root, obj); if (path === '') { throw new Error("Object not found in root"); } return '/' + path; } var beforeDict = []; jsonpatch.intervals; var Mirror = (function() { function Mirror(obj) { this.observers = []; this.obj = obj; } return Mirror; })(); var ObserverInfo = (function() { function ObserverInfo(callback, observer) { this.callback = callback; this.observer = observer; } return ObserverInfo; })(); function getMirror(obj) { for (var i = 0, ilen = beforeDict.length; i < ilen; i++) { if (beforeDict[i].obj === obj) { return beforeDict[i]; } } } function getObserverFromMirror(mirror, callback) { for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) { if (mirror.observers[j].callback === callback) { return mirror.observers[j].observer; } } } function removeObserverFromMirror(mirror, observer) { for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) { if (mirror.observers[j].observer === observer) { mirror.observers.splice(j, 1); return; } } } function unobserve(root, observer) { generate(observer); if (Object.observe) { _unobserve(observer, root); } else { clearTimeout(observer.next); } var mirror = getMirror(root); removeObserverFromMirror(mirror, observer); } jsonpatch.unobserve = unobserve; function observe(obj, callback) { var patches = []; var root = obj; var observer; var mirror = getMirror(obj); if (!mirror) { mirror = new Mirror(obj); beforeDict.push(mirror); } else { observer = getObserverFromMirror(mirror, callback); } if (observer) { return observer; } if (Object.observe) { observer = function(arr) { _unobserve(observer, obj); _observe(observer, obj); var a = 0, alen = arr.length; while (a < alen) { if (!(arr[a].name === 'length' && _isArray(arr[a].object)) && !(arr[a].name === '__Jasmine_been_here_before__')) { var type = arr[a].type; switch (type) { case 'new': type = 'add'; break; case 'deleted': type = 'delete'; break; case 'updated': type = 'update'; break; } observeOps[type].call(arr[a], patches, getPath(root, arr[a].object)); } a++; } if (patches) { if (callback) { callback(patches); } } observer.patches = patches; patches = []; }; } else { observer = {}; mirror.value = JSON.parse(JSON.stringify(obj)); if (callback) { observer.callback = callback; observer.next = null; var intervals = this.intervals || [100, 1000, 10000, 60000]; var currentInterval = 0; var dirtyCheck = function() { generate(observer); }; var fastCheck = function() { clearTimeout(observer.next); observer.next = setTimeout(function() { dirtyCheck(); currentInterval = 0; observer.next = setTimeout(slowCheck, intervals[currentInterval++]); }, 0); }; var slowCheck = function() { dirtyCheck(); if (currentInterval == intervals.length) { currentInterval = intervals.length - 1; } observer.next = setTimeout(slowCheck, intervals[currentInterval++]); }; if (typeof window !== 'undefined') { if (window.addEventListener) { window.addEventListener('mousedown', fastCheck); window.addEventListener('mouseup', fastCheck); window.addEventListener('keydown', fastCheck); } else { window.attachEvent('onmousedown', fastCheck); window.attachEvent('onmouseup', fastCheck); window.attachEvent('onkeydown', fastCheck); } } observer.next = setTimeout(slowCheck, intervals[currentInterval++]); } } observer.patches = patches; observer.object = obj; mirror.observers.push(new ObserverInfo(callback, observer)); return _observe(observer, obj); } jsonpatch.observe = observe; function _observe(observer, obj) { if (Object.observe) { Object.observe(obj, observer); for (var key in obj) { if (obj.hasOwnProperty(key)) { var v = obj[key]; if (v && typeof(v) === "object") { _observe(observer, v); } } } } return observer; } function _unobserve(observer, obj) { if (Object.observe) { Object.unobserve(obj, observer); for (var key in obj) { if (obj.hasOwnProperty(key)) { var v = obj[key]; if (v && typeof(v) === "object") { _unobserve(observer, v); } } } } return observer; } function generate(observer) { if (Object.observe) { Object.deliverChangeRecords(observer); } else { var mirror; for (var i = 0, ilen = beforeDict.length; i < ilen; i++) { if (beforeDict[i].obj === observer.object) { mirror = beforeDict[i]; break; } } _generate(mirror.value, observer.object, observer.patches, ""); } var temp = observer.patches; if (temp.length > 0) { observer.patches = []; if (observer.callback) { observer.callback(temp); } } return temp; } jsonpatch.generate = generate; var _objectKeys; if (Object.keys) { _objectKeys = Object.keys; } else { _objectKeys = function(obj) { var keys = []; for (var o in obj) { if (obj.hasOwnProperty(o)) { keys.push(o); } } return keys; }; } function _generate(mirror, obj, patches, path) { var newKeys = _objectKeys(obj); var oldKeys = _objectKeys(mirror); var changed = false; var deleted = false; for (var t = oldKeys.length - 1; t >= 0; t--) { var key = oldKeys[t]; var oldVal = mirror[key]; if (obj.hasOwnProperty(key)) { var newVal = obj[key]; if (oldVal instanceof Object) { _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key)); } else { if (oldVal != newVal) { changed = true; patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: newVal }); mirror[key] = newVal; } } } else { patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) }); delete mirror[key]; deleted = true; } } if (!deleted && newKeys.length == oldKeys.length) { return; } for (var t = 0; t < newKeys.length; t++) { var key = newKeys[t]; if (!mirror.hasOwnProperty(key)) { patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: obj[key] }); mirror[key] = JSON.parse(JSON.stringify(obj[key])); } } } var _isArray; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function(obj) { return obj.push && typeof obj.length === 'number'; }; } function apply(tree, patches) { var result = false, p = 0, plen = patches.length, patch; while (p < plen) { patch = patches[p]; var keys = patch.path.split('/'); var obj = tree; var t = 1; var len = keys.length; while (true) { if (_isArray(obj)) { var index = parseInt(keys[t], 10); t++; if (t >= len) { result = arrOps[patch.op].call(patch, obj, index, tree); break; } obj = obj[index]; } else { var key = keys[t]; if (key.indexOf('~') != -1) { key = key.replace(/~1/g, '/').replace(/~0/g, '~'); } t++; if (t >= len) { result = objOps[patch.op].call(patch, obj, key, tree); break; } obj = obj[key]; } } p++; } return result; } jsonpatch.apply = apply; })(jsonpatch || (jsonpatch = {})); if (typeof exports !== "undefined") { exports.apply = jsonpatch.apply; exports.observe = jsonpatch.observe; exports.unobserve = jsonpatch.unobserve; exports.generate = jsonpatch.generate; } //# },{}],5:[function(require,module,exports){ "use strict"; (function(global) { "use strict"; function countQuotes(str) { return str.split('"').length - 1; } var SheetClip = { parse: function(str) { var r, rLen, rows, arr = [], a = 0, c, cLen, multiline, last; rows = str.split('\n'); if (rows.length > 1 && rows[rows.length - 1] === '') { rows.pop(); } for (r = 0, rLen = rows.length; r < rLen; r += 1) { rows[r] = rows[r].split('\t'); for (c = 0, cLen = rows[r].length; c < cLen; c += 1) { if (!arr[a]) { arr[a] = []; } if (multiline && c === 0) { last = arr[a].length - 1; arr[a][last] = arr[a][last] + '\n' + rows[r][0]; if (multiline && (countQuotes(rows[r][0]) & 1)) { multiline = false; arr[a][last] = arr[a][last].substring(0, arr[a][last].length - 1).replace(/""/g, '"'); } } else { if (c === cLen - 1 && rows[r][c].indexOf('"') === 0) { arr[a].push(rows[r][c].substring(1).replace(/""/g, '"')); multiline = true; } else { arr[a].push(rows[r][c].replace(/""/g, '"')); multiline = false; } } } if (!multiline) { a += 1; } } return arr; }, stringify: function(arr) { var r, rLen, c, cLen, str = '', val; for (r = 0, rLen = arr.length; r < rLen; r += 1) { cLen = arr[r].length; for (c = 0; c < cLen; c += 1) { if (c > 0) { str += '\t'; } val = arr[r][c]; if (typeof val === 'string') { if (val.indexOf('\n') > -1) { str += '"' + val.replace(/"/g, '""') + '"'; } else { str += val; } } else if (val === null || val === void 0) { str += ''; } else { str += val; } } str += '\n'; } return str; } }; if (typeof exports !== 'undefined') { exports.parse = SheetClip.parse; exports.stringify = SheetClip.stringify; } else { global.SheetClip = SheetClip; } }(window)); //# },{}],6:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableOverlay: {get: function() { return WalkontableOverlay; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $__columnStrategy_46_js__, $___46__46__47__46__46__47__46__46__47_eventManager_46_js__, $__scrollbarNativeHorizontal_46_js__, $__core_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var ColumnStrategy = ($__columnStrategy_46_js__ = require("./columnStrategy.js"), $__columnStrategy_46_js__ && $__columnStrategy_46_js__.__esModule && $__columnStrategy_46_js__ || {default: $__columnStrategy_46_js__}).ColumnStrategy; var eventManagerObject = ($___46__46__47__46__46__47__46__46__47_eventManager_46_js__ = require("./../../../eventManager.js"), $___46__46__47__46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_eventManager_46_js__}).eventManager; var WalkontableHorizontalScrollbarNative = ($__scrollbarNativeHorizontal_46_js__ = require("./scrollbarNativeHorizontal.js"), $__scrollbarNativeHorizontal_46_js__ && $__scrollbarNativeHorizontal_46_js__.__esModule && $__scrollbarNativeHorizontal_46_js__ || {default: $__scrollbarNativeHorizontal_46_js__}).WalkontableHorizontalScrollbarNative; var Walkontable = ($__core_46_js__ = require("./core.js"), $__core_46_js__ && $__core_46_js__.__esModule && $__core_46_js__ || {default: $__core_46_js__}).Walkontable; ; window.WalkontableOverlay = WalkontableOverlay; function WalkontableOverlay() {} WalkontableOverlay.prototype.init = function() { this.TABLE = this.instance.wtTable.TABLE; this.hider = this.instance.wtTable.hider; this.spreader = this.instance.wtTable.spreader; this.holder = this.instance.wtTable.holder; this.wtRootElement = this.instance.wtTable.wtRootElement; this.trimmingContainer = dom.getTrimmingContainer(this.hider.parentNode.parentNode); this.mainTableScrollableElement = dom.getScrollableElement(this.instance.wtTable.TABLE); }; WalkontableOverlay.prototype.makeClone = function(direction) { var clone = document.createElement('DIV'); clone.className = 'ht_clone_' + direction + ' handsontable'; clone.style.position = 'absolute'; clone.style.top = 0; clone.style.left = 0; clone.style.overflow = 'hidden'; var clonedTable = document.createElement('TABLE'); clonedTable.className = this.instance.wtTable.TABLE.className; clone.appendChild(clonedTable); this.instance.wtTable.wtRootElement.parentNode.appendChild(clone); return new Walkontable({ cloneSource: this.instance, cloneOverlay: this, table: clonedTable }); }; WalkontableOverlay.prototype.refresh = function(fastDraw) { if (this.clone) { this.clone.draw(fastDraw); } }; WalkontableOverlay.prototype.destroy = function() { var eventManager = eventManagerObject(this.clone); eventManager.clear(); }; //# },{"./../../../dom.js":34,"./../../../eventManager.js":48,"./columnStrategy.js":11,"./core.js":12,"./scrollbarNativeHorizontal.js":19}],7:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableBorder: {get: function() { return WalkontableBorder; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47__46__46__47_eventManager_46_js__, $__cellCoords_46_js__, $__scrollbarNativeHorizontal_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47__46__46__47_eventManager_46_js__ = require("./../../../eventManager.js"), $___46__46__47__46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_eventManager_46_js__}).eventManager; var WalkontableCellCoords = ($__cellCoords_46_js__ = require("./cellCoords.js"), $__cellCoords_46_js__ && $__cellCoords_46_js__.__esModule && $__cellCoords_46_js__ || {default: $__cellCoords_46_js__}).WalkontableCellCoords; var WalkontableHorizontalScrollbarNative = ($__scrollbarNativeHorizontal_46_js__ = require("./scrollbarNativeHorizontal.js"), $__scrollbarNativeHorizontal_46_js__ && $__scrollbarNativeHorizontal_46_js__.__esModule && $__scrollbarNativeHorizontal_46_js__ || {default: $__scrollbarNativeHorizontal_46_js__}).WalkontableHorizontalScrollbarNative; ; window.WalkontableBorder = WalkontableBorder; function WalkontableBorder(instance, settings) { var style; var createMultipleSelectorHandles = function() { this.selectionHandles = { topLeft: document.createElement('DIV'), topLeftHitArea: document.createElement('DIV'), bottomRight: document.createElement('DIV'), bottomRightHitArea: document.createElement('DIV') }; var width = 10, hitAreaWidth = 40; this.selectionHandles.topLeft.className = 'topLeftSelectionHandle'; this.selectionHandles.topLeftHitArea.className = 'topLeftSelectionHandle-HitArea'; this.selectionHandles.bottomRight.className = 'bottomRightSelectionHandle'; this.selectionHandles.bottomRightHitArea.className = 'bottomRightSelectionHandle-HitArea'; this.selectionHandles.styles = { topLeft: this.selectionHandles.topLeft.style, topLeftHitArea: this.selectionHandles.topLeftHitArea.style, bottomRight: this.selectionHandles.bottomRight.style, bottomRightHitArea: this.selectionHandles.bottomRightHitArea.style }; var hitAreaStyle = { 'position': 'absolute', 'height': hitAreaWidth + 'px', 'width': hitAreaWidth + 'px', 'border-radius': parseInt(hitAreaWidth / 1.5, 10) + 'px' }; for (var prop in hitAreaStyle) { if (hitAreaStyle.hasOwnProperty(prop)) { this.selectionHandles.styles.bottomRightHitArea[prop] = hitAreaStyle[prop]; this.selectionHandles.styles.topLeftHitArea[prop] = hitAreaStyle[prop]; } } var handleStyle = { 'position': 'absolute', 'height': width + 'px', 'width': width + 'px', 'border-radius': parseInt(width / 1.5, 10) + 'px', 'background': '#F5F5FF', 'border': '1px solid #4285c8' }; for (var prop in handleStyle) { if (handleStyle.hasOwnProperty(prop)) { this.selectionHandles.styles.bottomRight[prop] = handleStyle[prop]; this.selectionHandles.styles.topLeft[prop] = handleStyle[prop]; } } this.main.appendChild(this.selectionHandles.topLeft); this.main.appendChild(this.selectionHandles.bottomRight); this.main.appendChild(this.selectionHandles.topLeftHitArea); this.main.appendChild(this.selectionHandles.bottomRightHitArea); }; if (!settings) { return; } var eventManager = eventManagerObject(instance); this.instance = instance; this.settings = settings; this.main = document.createElement("div"); style = this.main.style; style.position = 'absolute'; style.top = 0; style.left = 0; var borderDivs = ['top', 'left', 'bottom', 'right', 'corner']; for (var i = 0; i < 5; i++) { var position = borderDivs[i]; var DIV = document.createElement('DIV'); DIV.className = 'wtBorder ' + (this.settings.className || ''); if (this.settings[position] && this.settings[position].hide) { DIV.className += " hidden"; } style = DIV.style; style.backgroundColor = (this.settings[position] && this.settings[position].color) ? this.settings[position].color : settings.border.color; style.height = (this.settings[position] && this.settings[position].width) ? this.settings[position].width + 'px' : settings.border.width + 'px'; style.width = (this.settings[position] && this.settings[position].width) ? this.settings[position].width + 'px' : settings.border.width + 'px'; this.main.appendChild(DIV); } this.top = this.main.childNodes[0]; this.left = this.main.childNodes[1]; this.bottom = this.main.childNodes[2]; this.right = this.main.childNodes[3]; this.topStyle = this.top.style; this.leftStyle = this.left.style; this.bottomStyle = this.bottom.style; this.rightStyle = this.right.style; this.cornerDefaultStyle = { width: '5px', height: '5px', borderWidth: '2px', borderStyle: 'solid', borderColor: '#FFF' }; this.corner = this.main.childNodes[4]; this.corner.className += ' corner'; this.cornerStyle = this.corner.style; this.cornerStyle.width = this.cornerDefaultStyle.width; this.cornerStyle.height = this.cornerDefaultStyle.height; this.cornerStyle.border = [this.cornerDefaultStyle.borderWidth, this.cornerDefaultStyle.borderStyle, this.cornerDefaultStyle.borderColor].join(' '); if (Handsontable.mobileBrowser) { createMultipleSelectorHandles.call(this); } this.disappear(); if (!instance.wtTable.bordersHolder) { instance.wtTable.bordersHolder = document.createElement('div'); instance.wtTable.bordersHolder.className = 'htBorders'; instance.wtTable.spreader.appendChild(instance.wtTable.bordersHolder); } instance.wtTable.bordersHolder.insertBefore(this.main, instance.wtTable.bordersHolder.firstChild); var down = false; eventManager.addEventListener(document.body, 'mousedown', function() { down = true; }); eventManager.addEventListener(document.body, 'mouseup', function() { down = false; }); for (var c = 0, len = this.main.childNodes.length; c < len; c++) { eventManager.addEventListener(this.main.childNodes[c], 'mouseenter', function(event) { if (!down || !instance.getSetting('hideBorderOnMouseDownOver')) { return; } event.preventDefault(); event.stopImmediatePropagation(); var bounds = this.getBoundingClientRect(); this.style.display = 'none'; var isOutside = function(event) { if (event.clientY < Math.floor(bounds.top)) { return true; } if (event.clientY > Math.ceil(bounds.top + bounds.height)) { return true; } if (event.clientX < Math.floor(bounds.left)) { return true; } if (event.clientX > Math.ceil(bounds.left + bounds.width)) { return true; } }; var handler = function(event) { if (isOutside(event)) { eventManager.removeEventListener(document.body, 'mousemove', handler); this.style.display = 'block'; } }; eventManager.addEventListener(document.body, 'mousemove', handler); }); } } WalkontableBorder.prototype.appear = function(corners) { if (this.disabled) { return; } var instance = this.instance; var isMultiple, fromTD, toTD, fromOffset, toOffset, containerOffset, top, minTop, left, minLeft, height, width, fromRow, fromColumn, toRow, toColumn, i, ilen, s; var isPartRange = function() { if (this.instance.selections.area.cellRange) { if (toRow != this.instance.selections.area.cellRange.to.row || toColumn != this.instance.selections.area.cellRange.to.col) { return true; } } return false; }; var updateMultipleSelectionHandlesPosition = function(top, left, width, height) { var handleWidth = parseInt(this.selectionHandles.styles.topLeft.width, 10), hitAreaWidth = parseInt(this.selectionHandles.styles.topLeftHitArea.width, 10); this.selectionHandles.styles.topLeft.top = parseInt(top - handleWidth, 10) + "px"; this.selectionHandles.styles.topLeft.left = parseInt(left - handleWidth, 10) + "px"; this.selectionHandles.styles.topLeftHitArea.top = parseInt(top - (hitAreaWidth / 4) * 3, 10) + "px"; this.selectionHandles.styles.topLeftHitArea.left = parseInt(left - (hitAreaWidth / 4) * 3, 10) + "px"; this.selectionHandles.styles.bottomRight.top = parseInt(top + height, 10) + "px"; this.selectionHandles.styles.bottomRight.left = parseInt(left + width, 10) + "px"; this.selectionHandles.styles.bottomRightHitArea.top = parseInt(top + height - hitAreaWidth / 4, 10) + "px"; this.selectionHandles.styles.bottomRightHitArea.left = parseInt(left + width - hitAreaWidth / 4, 10) + "px"; if (this.settings.border.multipleSelectionHandlesVisible && this.settings.border.multipleSelectionHandlesVisible()) { this.selectionHandles.styles.topLeft.display = "block"; this.selectionHandles.styles.topLeftHitArea.display = "block"; if (!isPartRange.call(this)) { this.selectionHandles.styles.bottomRight.display = "block"; this.selectionHandles.styles.bottomRightHitArea.display = "block"; } else { this.selectionHandles.styles.bottomRight.display = "none"; this.selectionHandles.styles.bottomRightHitArea.display = "none"; } } else { this.selectionHandles.styles.topLeft.display = "none"; this.selectionHandles.styles.bottomRight.display = "none"; this.selectionHandles.styles.topLeftHitArea.display = "none"; this.selectionHandles.styles.bottomRightHitArea.display = "none"; } if (fromRow == this.instance.wtSettings.getSetting('fixedRowsTop') || fromColumn == this.instance.wtSettings.getSetting('fixedColumnsLeft')) { this.selectionHandles.styles.topLeft.zIndex = "9999"; this.selectionHandles.styles.topLeftHitArea.zIndex = "9999"; } else { this.selectionHandles.styles.topLeft.zIndex = ""; this.selectionHandles.styles.topLeftHitArea.zIndex = ""; } }; if (instance.cloneOverlay instanceof WalkontableTopOverlay || instance.cloneOverlay instanceof WalkontableCornerOverlay) { ilen = instance.getSetting('fixedRowsTop'); } else { ilen = instance.wtTable.getRenderedRowsCount(); } for (i = 0; i < ilen; i++) { s = instance.wtTable.rowFilter.renderedToSource(i); if (s >= corners[0] && s <= corners[2]) { fromRow = s; break; } } for (i = ilen - 1; i >= 0; i--) { s = instance.wtTable.rowFilter.renderedToSource(i); if (s >= corners[0] && s <= corners[2]) { toRow = s; break; } } ilen = instance.wtTable.getRenderedColumnsCount(); for (i = 0; i < ilen; i++) { s = instance.wtTable.columnFilter.renderedToSource(i); if (s >= corners[1] && s <= corners[3]) { fromColumn = s; break; } } for (i = ilen - 1; i >= 0; i--) { s = instance.wtTable.columnFilter.renderedToSource(i); if (s >= corners[1] && s <= corners[3]) { toColumn = s; break; } } if (fromRow !== void 0 && fromColumn !== void 0) { isMultiple = (fromRow !== toRow || fromColumn !== toColumn); fromTD = instance.wtTable.getCell(new WalkontableCellCoords(fromRow, fromColumn)); toTD = isMultiple ? instance.wtTable.getCell(new WalkontableCellCoords(toRow, toColumn)) : fromTD; fromOffset = dom.offset(fromTD); toOffset = isMultiple ? dom.offset(toTD) : fromOffset; containerOffset = dom.offset(instance.wtTable.TABLE); minTop = fromOffset.top; height = toOffset.top + dom.outerHeight(toTD) - minTop; minLeft = fromOffset.left; width = toOffset.left + dom.outerWidth(toTD) - minLeft; top = minTop - containerOffset.top - 1; left = minLeft - containerOffset.left - 1; var style = dom.getComputedStyle(fromTD); if (parseInt(style['borderTopWidth'], 10) > 0) { top += 1; height = height > 0 ? height - 1 : 0; } if (parseInt(style['borderLeftWidth'], 10) > 0) { left += 1; width = width > 0 ? width - 1 : 0; } } else { this.disappear(); return; } this.topStyle.top = top + 'px'; this.topStyle.left = left + 'px'; this.topStyle.width = width + 'px'; this.topStyle.display = 'block'; this.leftStyle.top = top + 'px'; this.leftStyle.left = left + 'px'; this.leftStyle.height = height + 'px'; this.leftStyle.display = 'block'; var delta = Math.floor(this.settings.border.width / 2); this.bottomStyle.top = top + height - delta + 'px'; this.bottomStyle.left = left + 'px'; this.bottomStyle.width = width + 'px'; this.bottomStyle.display = 'block'; this.rightStyle.top = top + 'px'; this.rightStyle.left = left + width - delta + 'px'; this.rightStyle.height = height + 1 + 'px'; this.rightStyle.display = 'block'; if (Handsontable.mobileBrowser || (!this.hasSetting(this.settings.border.cornerVisible) || isPartRange.call(this))) { this.cornerStyle.display = 'none'; } else { this.cornerStyle.top = top + height - 4 + 'px'; this.cornerStyle.left = left + width - 4 + 'px'; this.cornerStyle.borderRightWidth = this.cornerDefaultStyle.borderWidth; this.cornerStyle.width = this.cornerDefaultStyle.width; this.cornerStyle.display = 'block'; if (toColumn === this.instance.getSetting('totalColumns') - 1) { var trimmingContainer = dom.getTrimmingContainer(instance.wtTable.TABLE), cornerOverlappingContainer = toTD.offsetLeft + dom.outerWidth(toTD) >= dom.innerWidth(trimmingContainer); if (cornerOverlappingContainer) { this.cornerStyle.left = Math.floor(left + width - 3 - parseInt(this.cornerDefaultStyle.width) / 2) + "px"; this.cornerStyle.borderRightWidth = 0; } } } if (Handsontable.mobileBrowser) { updateMultipleSelectionHandlesPosition.call(this, top, left, width, height); } }; WalkontableBorder.prototype.disappear = function() { this.topStyle.display = 'none'; this.leftStyle.display = 'none'; this.bottomStyle.display = 'none'; this.rightStyle.display = 'none'; this.cornerStyle.display = 'none'; if (Handsontable.mobileBrowser) { this.selectionHandles.styles.topLeft.display = 'none'; this.selectionHandles.styles.bottomRight.display = 'none'; } }; WalkontableBorder.prototype.hasSetting = function(setting) { if (typeof setting === 'function') { return setting(); } return !!setting; }; //# },{"./../../../dom.js":34,"./../../../eventManager.js":48,"./cellCoords.js":8,"./scrollbarNativeHorizontal.js":19}],8:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableCellCoords: {get: function() { return WalkontableCellCoords; }}, __esModule: {value: true} }); ; window.WalkontableCellCoords = WalkontableCellCoords; function WalkontableCellCoords(row, col) { if (typeof row !== 'undefined' && typeof col !== 'undefined') { this.row = row; this.col = col; } else { this.row = null; this.col = null; } } WalkontableCellCoords.prototype.isValid = function(instance) { if (this.row < 0 || this.col < 0) { return false; } if (this.row >= instance.getSetting('totalRows') || this.col >= instance.getSetting('totalColumns')) { return false; } return true; }; WalkontableCellCoords.prototype.isEqual = function(cellCoords) { if (cellCoords === this) { return true; } return (this.row === cellCoords.row && this.col === cellCoords.col); }; WalkontableCellCoords.prototype.isSouthEastOf = function(testedCoords) { return this.row >= testedCoords.row && this.col >= testedCoords.col; }; WalkontableCellCoords.prototype.isNorthWestOf = function(testedCoords) { return this.row <= testedCoords.row && this.col <= testedCoords.col; }; WalkontableCellCoords.prototype.isSouthWestOf = function(testedCoords) { return this.row >= testedCoords.row && this.col <= testedCoords.col; }; WalkontableCellCoords.prototype.isNorthEastOf = function(testedCoords) { return this.row <= testedCoords.row && this.col >= testedCoords.col; }; //# },{}],9:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableCellRange: {get: function() { return WalkontableCellRange; }}, __esModule: {value: true} }); var $__cellCoords_46_js__; var WalkontableCellCoords = ($__cellCoords_46_js__ = require("./cellCoords.js"), $__cellCoords_46_js__ && $__cellCoords_46_js__.__esModule && $__cellCoords_46_js__ || {default: $__cellCoords_46_js__}).WalkontableCellCoords; ; window.WalkontableCellRange = WalkontableCellRange; function WalkontableCellRange(highlight, from, to) { this.highlight = highlight; this.from = from; this.to = to; } WalkontableCellRange.prototype.isValid = function(instance) { return this.from.isValid(instance) && this.to.isValid(instance); }; WalkontableCellRange.prototype.isSingle = function() { return this.from.row === this.to.row && this.from.col === this.to.col; }; WalkontableCellRange.prototype.getHeight = function() { return Math.max(this.from.row, this.to.row) - Math.min(this.from.row, this.to.row) + 1; }; WalkontableCellRange.prototype.getWidth = function() { return Math.max(this.from.col, this.to.col) - Math.min(this.from.col, this.to.col) + 1; }; WalkontableCellRange.prototype.includes = function(cellCoords) { var topLeft = this.getTopLeftCorner(); var bottomRight = this.getBottomRightCorner(); if (cellCoords.row < 0) { cellCoords.row = 0; } if (cellCoords.col < 0) { cellCoords.col = 0; } return (topLeft.row <= cellCoords.row && bottomRight.row >= cellCoords.row && topLeft.col <= cellCoords.col && bottomRight.col >= cellCoords.col); }; WalkontableCellRange.prototype.includesRange = function(testedRange) { return this.includes(testedRange.getTopLeftCorner()) && this.includes(testedRange.getBottomRightCorner()); }; WalkontableCellRange.prototype.isEqual = function(testedRange) { return (Math.min(this.from.row, this.to.row) == Math.min(testedRange.from.row, testedRange.to.row)) && (Math.max(this.from.row, this.to.row) == Math.max(testedRange.from.row, testedRange.to.row)) && (Math.min(this.from.col, this.to.col) == Math.min(testedRange.from.col, testedRange.to.col)) && (Math.max(this.from.col, this.to.col) == Math.max(testedRange.from.col, testedRange.to.col)); }; WalkontableCellRange.prototype.overlaps = function(testedRange) { return testedRange.isSouthEastOf(this.getTopLeftCorner()) && testedRange.isNorthWestOf(this.getBottomRightCorner()); }; WalkontableCellRange.prototype.isSouthEastOf = function(testedCoords) { return this.getTopLeftCorner().isSouthEastOf(testedCoords) || this.getBottomRightCorner().isSouthEastOf(testedCoords); }; WalkontableCellRange.prototype.isNorthWestOf = function(testedCoords) { return this.getTopLeftCorner().isNorthWestOf(testedCoords) || this.getBottomRightCorner().isNorthWestOf(testedCoords); }; WalkontableCellRange.prototype.expand = function(cellCoords) { var topLeft = this.getTopLeftCorner(); var bottomRight = this.getBottomRightCorner(); if (cellCoords.row < topLeft.row || cellCoords.col < topLeft.col || cellCoords.row > bottomRight.row || cellCoords.col > bottomRight.col) { this.from = new WalkontableCellCoords(Math.min(topLeft.row, cellCoords.row), Math.min(topLeft.col, cellCoords.col)); this.to = new WalkontableCellCoords(Math.max(bottomRight.row, cellCoords.row), Math.max(bottomRight.col, cellCoords.col)); return true; } return false; }; WalkontableCellRange.prototype.expandByRange = function(expandingRange) { if (this.includesRange(expandingRange) || !this.overlaps(expandingRange)) { return false; } var topLeft = this.getTopLeftCorner(), bottomRight = this.getBottomRightCorner(), topRight = this.getTopRightCorner(), bottomLeft = this.getBottomLeftCorner(); var expandingTopLeft = expandingRange.getTopLeftCorner(); var expandingBottomRight = expandingRange.getBottomRightCorner(); var resultTopRow = Math.min(topLeft.row, expandingTopLeft.row); var resultTopCol = Math.min(topLeft.col, expandingTopLeft.col); var resultBottomRow = Math.max(bottomRight.row, expandingBottomRight.row); var resultBottomCol = Math.max(bottomRight.col, expandingBottomRight.col); var finalFrom = new WalkontableCellCoords(resultTopRow, resultTopCol), finalTo = new WalkontableCellCoords(resultBottomRow, resultBottomCol); var isCorner = new WalkontableCellRange(finalFrom, finalFrom, finalTo).isCorner(this.from, expandingRange), onlyMerge = expandingRange.isEqual(new WalkontableCellRange(finalFrom, finalFrom, finalTo)); if (isCorner && !onlyMerge) { if (this.from.col > finalFrom.col) { finalFrom.col = resultBottomCol; finalTo.col = resultTopCol; } if (this.from.row > finalFrom.row) { finalFrom.row = resultBottomRow; finalTo.row = resultTopRow; } } this.from = finalFrom; this.to = finalTo; return true; }; WalkontableCellRange.prototype.getDirection = function() { if (this.from.isNorthWestOf(this.to)) { return "NW-SE"; } else if (this.from.isNorthEastOf(this.to)) { return "NE-SW"; } else if (this.from.isSouthEastOf(this.to)) { return "SE-NW"; } else if (this.from.isSouthWestOf(this.to)) { return "SW-NE"; } }; WalkontableCellRange.prototype.setDirection = function(direction) { switch (direction) { case "NW-SE": this.from = this.getTopLeftCorner(); this.to = this.getBottomRightCorner(); break; case "NE-SW": this.from = this.getTopRightCorner(); this.to = this.getBottomLeftCorner(); break; case "SE-NW": this.from = this.getBottomRightCorner(); this.to = this.getTopLeftCorner(); break; case "SW-NE": this.from = this.getBottomLeftCorner(); this.to = this.getTopRightCorner(); break; } }; WalkontableCellRange.prototype.getTopLeftCorner = function() { return new WalkontableCellCoords(Math.min(this.from.row, this.to.row), Math.min(this.from.col, this.to.col)); }; WalkontableCellRange.prototype.getBottomRightCorner = function() { return new WalkontableCellCoords(Math.max(this.from.row, this.to.row), Math.max(this.from.col, this.to.col)); }; WalkontableCellRange.prototype.getTopRightCorner = function() { return new WalkontableCellCoords(Math.min(this.from.row, this.to.row), Math.max(this.from.col, this.to.col)); }; WalkontableCellRange.prototype.getBottomLeftCorner = function() { return new WalkontableCellCoords(Math.max(this.from.row, this.to.row), Math.min(this.from.col, this.to.col)); }; WalkontableCellRange.prototype.isCorner = function(coords, expandedRange) { if (expandedRange) { if (expandedRange.includes(coords)) { if (this.getTopLeftCorner().isEqual(new WalkontableCellCoords(expandedRange.from.row, expandedRange.from.col)) || this.getTopRightCorner().isEqual(new WalkontableCellCoords(expandedRange.from.row, expandedRange.to.col)) || this.getBottomLeftCorner().isEqual(new WalkontableCellCoords(expandedRange.to.row, expandedRange.from.col)) || this.getBottomRightCorner().isEqual(new WalkontableCellCoords(expandedRange.to.row, expandedRange.to.col))) { return true; } } } return coords.isEqual(this.getTopLeftCorner()) || coords.isEqual(this.getTopRightCorner()) || coords.isEqual(this.getBottomLeftCorner()) || coords.isEqual(this.getBottomRightCorner()); }; WalkontableCellRange.prototype.getOppositeCorner = function(coords, expandedRange) { if (!(coords instanceof WalkontableCellCoords)) { return false; } if (expandedRange) { if (expandedRange.includes(coords)) { if (this.getTopLeftCorner().isEqual(new WalkontableCellCoords(expandedRange.from.row, expandedRange.from.col))) { return this.getBottomRightCorner(); } if (this.getTopRightCorner().isEqual(new WalkontableCellCoords(expandedRange.from.row, expandedRange.to.col))) { return this.getBottomLeftCorner(); } if (this.getBottomLeftCorner().isEqual(new WalkontableCellCoords(expandedRange.to.row, expandedRange.from.col))) { return this.getTopRightCorner(); } if (this.getBottomRightCorner().isEqual(new WalkontableCellCoords(expandedRange.to.row, expandedRange.to.col))) { return this.getTopLeftCorner(); } } } if (coords.isEqual(this.getBottomRightCorner())) { return this.getTopLeftCorner(); } else if (coords.isEqual(this.getTopLeftCorner())) { return this.getBottomRightCorner(); } else if (coords.isEqual(this.getTopRightCorner())) { return this.getBottomLeftCorner(); } else if (coords.isEqual(this.getBottomLeftCorner())) { return this.getTopRightCorner(); } }; WalkontableCellRange.prototype.getBordersSharedWith = function(range) { if (!this.includesRange(range)) { return []; } var thisBorders = { top: Math.min(this.from.row, this.to.row), bottom: Math.max(this.from.row, this.to.row), left: Math.min(this.from.col, this.to.col), right: Math.max(this.from.col, this.to.col) }, rangeBorders = { top: Math.min(range.from.row, range.to.row), bottom: Math.max(range.from.row, range.to.row), left: Math.min(range.from.col, range.to.col), right: Math.max(range.from.col, range.to.col) }, result = []; if (thisBorders.top == rangeBorders.top) { result.push('top'); } if (thisBorders.right == rangeBorders.right) { result.push('right'); } if (thisBorders.bottom == rangeBorders.bottom) { result.push('bottom'); } if (thisBorders.left == rangeBorders.left) { result.push('left'); } return result; }; WalkontableCellRange.prototype.getInner = function() { var topLeft = this.getTopLeftCorner(); var bottomRight = this.getBottomRightCorner(); var out = []; for (var r = topLeft.row; r <= bottomRight.row; r++) { for (var c = topLeft.col; c <= bottomRight.col; c++) { if (!(this.from.row === r && this.from.col === c) && !(this.to.row === r && this.to.col === c)) { out.push(new WalkontableCellCoords(r, c)); } } } return out; }; WalkontableCellRange.prototype.getAll = function() { var topLeft = this.getTopLeftCorner(); var bottomRight = this.getBottomRightCorner(); var out = []; for (var r = topLeft.row; r <= bottomRight.row; r++) { for (var c = topLeft.col; c <= bottomRight.col; c++) { if (topLeft.row === r && topLeft.col === c) { out.push(topLeft); } else if (bottomRight.row === r && bottomRight.col === c) { out.push(bottomRight); } else { out.push(new WalkontableCellCoords(r, c)); } } } return out; }; WalkontableCellRange.prototype.forAll = function(callback) { var topLeft = this.getTopLeftCorner(); var bottomRight = this.getBottomRightCorner(); for (var r = topLeft.row; r <= bottomRight.row; r++) { for (var c = topLeft.col; c <= bottomRight.col; c++) { var breakIteration = callback(r, c); if (breakIteration === false) { return; } } } }; //# },{"./cellCoords.js":8}],10:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableColumnFilter: {get: function() { return WalkontableColumnFilter; }}, __esModule: {value: true} }); ; window.WalkontableColumnFilter = WalkontableColumnFilter; function WalkontableColumnFilter(offset, total, countTH) { this.offset = offset; this.total = total; this.countTH = countTH; } WalkontableColumnFilter.prototype.offsetted = function(n) { return n + this.offset; }; WalkontableColumnFilter.prototype.unOffsetted = function(n) { return n - this.offset; }; WalkontableColumnFilter.prototype.renderedToSource = function(n) { return this.offsetted(n); }; WalkontableColumnFilter.prototype.sourceToRendered = function(n) { return this.unOffsetted(n); }; WalkontableColumnFilter.prototype.offsettedTH = function(n) { return n - this.countTH; }; WalkontableColumnFilter.prototype.unOffsettedTH = function(n) { return n + this.countTH; }; WalkontableColumnFilter.prototype.visibleRowHeadedColumnToSourceColumn = function(n) { return this.renderedToSource(this.offsettedTH(n)); }; WalkontableColumnFilter.prototype.sourceColumnToVisibleRowHeadedColumn = function(n) { return this.unOffsettedTH(this.sourceToRendered(n)); }; //# },{}],11:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableColumnStrategy: {get: function() { return WalkontableColumnStrategy; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $__cellCoords_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var WalkontableCellCoords = ($__cellCoords_46_js__ = require("./cellCoords.js"), $__cellCoords_46_js__ && $__cellCoords_46_js__.__esModule && $__cellCoords_46_js__ || {default: $__cellCoords_46_js__}).WalkontableCellCoords; ; window.WalkontableColumnStrategy = WalkontableColumnStrategy; function WalkontableColumnStrategy(instance, containerSizeFn, sizeAtIndex, strategy) { var size, i = 0; this.instance = instance; this.containerSizeFn = containerSizeFn; this.cellSizesSum = 0; this.cellSizes = []; this.cellStretch = []; this.cellCount = 0; this.visibleCellCount = 0; this.remainingSize = 0; this.strategy = strategy; while (true) { size = sizeAtIndex(i); if (size === void 0) { break; } if (this.cellSizesSum < this.getContainerSize()) { this.visibleCellCount++; } this.cellSizes.push(size); this.cellSizesSum += size; this.cellCount++; i++; } var containerSize = this.getContainerSize(); this.remainingSize = this.cellSizesSum - containerSize; } WalkontableColumnStrategy.prototype.getContainerSize = function() { return typeof this.containerSizeFn === 'function' ? this.containerSizeFn() : this.containerSizeFn; }; WalkontableColumnStrategy.prototype.getSize = function(index) { return this.cellSizes[index] + (this.cellStretch[index] || 0); }; WalkontableColumnStrategy.prototype.stretch = function() { var containerSize = this.getContainerSize(), i = 0; this.remainingSize = this.cellSizesSum - containerSize; this.cellStretch.length = 0; if (this.strategy === 'all') { if (this.remainingSize < 0) { var ratio = containerSize / this.cellSizesSum; var newSize; while (i < this.cellCount - 1) { newSize = Math.floor(ratio * this.cellSizes[i]); this.remainingSize += newSize - this.cellSizes[i]; this.cellStretch[i] = newSize - this.cellSizes[i]; i++; } this.cellStretch[this.cellCount - 1] = -this.remainingSize; this.remainingSize = 0; } } else if (this.strategy === 'last') { if (this.remainingSize < 0 && containerSize !== Infinity) { this.cellStretch[this.cellCount - 1] = -this.remainingSize; this.remainingSize = 0; } } }; WalkontableColumnStrategy.prototype.countVisible = function() { return this.visibleCellCount; }; WalkontableColumnStrategy.prototype.isLastIncomplete = function() { var firstRow = this.instance.wtTable.getFirstVisibleRow(); var lastCol = this.instance.wtTable.getLastVisibleColumn(); var cell = this.instance.wtTable.getCell(new WalkontableCellCoords(firstRow, lastCol)); var cellOffset = dom.offset(cell); var cellWidth = dom.outerWidth(cell); var cellEnd = cellOffset.left + cellWidth; var viewportOffsetLeft = this.instance.wtOverlays.topOverlay.getScrollPosition(); var viewportWitdh = this.instance.wtViewport.getViewportWidth(); var viewportEnd = viewportOffsetLeft + viewportWitdh; return viewportEnd >= cellEnd; }; //# },{"./../../../dom.js":34,"./cellCoords.js":8}],12:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { Walkontable: {get: function() { return Walkontable; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $__event_46_js__, $__overlays_46_js__, $__helpers_46_js__, $__scroll_46_js__, $__settings_46_js__, $__table_46_js__, $__viewport_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var WalkontableEvent = ($__event_46_js__ = require("./event.js"), $__event_46_js__ && $__event_46_js__.__esModule && $__event_46_js__ || {default: $__event_46_js__}).WalkontableEvent; var WalkontableOverlays = ($__overlays_46_js__ = require("./overlays.js"), $__overlays_46_js__ && $__overlays_46_js__.__esModule && $__overlays_46_js__ || {default: $__overlays_46_js__}).WalkontableOverlays; var walkontableRandomString = ($__helpers_46_js__ = require("./helpers.js"), $__helpers_46_js__ && $__helpers_46_js__.__esModule && $__helpers_46_js__ || {default: $__helpers_46_js__}).walkontableRandomString; var WalkontableScroll = ($__scroll_46_js__ = require("./scroll.js"), $__scroll_46_js__ && $__scroll_46_js__.__esModule && $__scroll_46_js__ || {default: $__scroll_46_js__}).WalkontableScroll; var WalkontableSettings = ($__settings_46_js__ = require("./settings.js"), $__settings_46_js__ && $__settings_46_js__.__esModule && $__settings_46_js__ || {default: $__settings_46_js__}).WalkontableSettings; var WalkontableTable = ($__table_46_js__ = require("./table.js"), $__table_46_js__ && $__table_46_js__.__esModule && $__table_46_js__ || {default: $__table_46_js__}).WalkontableTable; var WalkontableViewport = ($__viewport_46_js__ = require("./viewport.js"), $__viewport_46_js__ && $__viewport_46_js__.__esModule && $__viewport_46_js__ || {default: $__viewport_46_js__}).WalkontableViewport; ; window.Walkontable = Walkontable; function Walkontable(settings) { var originalHeaders = []; this.guid = 'wt_' + walkontableRandomString(); if (settings.cloneSource) { this.cloneSource = settings.cloneSource; this.cloneOverlay = settings.cloneOverlay; this.wtSettings = settings.cloneSource.wtSettings; this.wtTable = new WalkontableTable(this, settings.table, settings.wtRootElement); this.wtScroll = new WalkontableScroll(this); this.wtViewport = settings.cloneSource.wtViewport; this.wtEvent = new WalkontableEvent(this); this.selections = this.cloneSource.selections; } else { this.wtSettings = new WalkontableSettings(this, settings); this.wtTable = new WalkontableTable(this, settings.table); this.wtScroll = new WalkontableScroll(this); this.wtViewport = new WalkontableViewport(this); this.wtEvent = new WalkontableEvent(this); this.selections = this.getSetting('selections'); this.wtOverlays = new WalkontableOverlays(this); } if (this.wtTable.THEAD.childNodes.length && this.wtTable.THEAD.childNodes[0].childNodes.length) { for (var c = 0, clen = this.wtTable.THEAD.childNodes[0].childNodes.length; c < clen; c++) { originalHeaders.push(this.wtTable.THEAD.childNodes[0].childNodes[c].innerHTML); } if (!this.getSetting('columnHeaders').length) { this.update('columnHeaders', [function(column, TH) { dom.fastInnerText(TH, originalHeaders[column]); }]); } } this.drawn = false; this.drawInterrupted = false; } Walkontable.prototype.draw = function(fastDraw) { this.drawInterrupted = false; if (!fastDraw && !dom.isVisible(this.wtTable.TABLE)) { this.drawInterrupted = true; return this; } this.wtTable.draw(fastDraw); return this; }; Walkontable.prototype.getCell = function(coords, topmost) { if (!topmost) { return this.wtTable.getCell(coords); } else { var fixedRows = this.wtSettings.getSetting('fixedRowsTop'), fixedColumns = this.wtSettings.getSetting('fixedColumnsLeft'); if (coords.row < fixedRows && coords.col < fixedColumns) { return this.wtOverlays.topLeftCornerOverlay.clone.wtTable.getCell(coords); } else if (coords.row < fixedRows) { return this.wtOverlays.topOverlay.clone.wtTable.getCell(coords); } else if (coords.col < fixedColumns) { return this.wtOverlays.leftOverlay.clone.wtTable.getCell(coords); } else { return this.wtTable.getCell(coords); } } }; Walkontable.prototype.update = function(settings, value) { return this.wtSettings.update(settings, value); }; Walkontable.prototype.scrollVertical = function(row) { this.wtOverlays.topOverlay.scrollTo(row); this.getSetting('onScrollVertically'); return this; }; Walkontable.prototype.scrollHorizontal = function(column) { this.wtOverlays.leftOverlay.scrollTo(column); this.getSetting('onScrollHorizontally'); return this; }; Walkontable.prototype.scrollViewport = function(coords) { this.wtScroll.scrollViewport(coords); return this; }; Walkontable.prototype.getViewport = function() { return [this.wtTable.getFirstVisibleRow(), this.wtTable.getFirstVisibleColumn(), this.wtTable.getLastVisibleRow(), this.wtTable.getLastVisibleColumn()]; }; Walkontable.prototype.getSetting = function(key, param1, param2, param3, param4) { return this.wtSettings.getSetting(key, param1, param2, param3, param4); }; Walkontable.prototype.hasSetting = function(key) { return this.wtSettings.has(key); }; Walkontable.prototype.destroy = function() { this.wtOverlays.destroy(); if (this.wtEvent) { this.wtEvent.destroy(); } }; //# },{"./../../../dom.js":34,"./event.js":14,"./helpers.js":15,"./overlays.js":16,"./scroll.js":18,"./settings.js":21,"./table.js":22,"./viewport.js":24}],13:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableDebugOverlay: {get: function() { return WalkontableDebugOverlay; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $___95_overlay_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var WalkontableOverlay = ($___95_overlay_46_js__ = require("./_overlay.js"), $___95_overlay_46_js__ && $___95_overlay_46_js__.__esModule && $___95_overlay_46_js__ || {default: $___95_overlay_46_js__}).WalkontableOverlay; ; window.WalkontableDebugOverlay = WalkontableDebugOverlay; function WalkontableDebugOverlay(instance) { this.instance = instance; this.init(); this.clone = this.makeClone('debug'); this.clone.wtTable.holder.style.opacity = 0.4; this.clone.wtTable.holder.style.textShadow = '0 0 2px #ff0000'; this.lastTimeout = null; dom.addClass(this.clone.wtTable.holder.parentNode, 'wtDebugVisible'); } WalkontableDebugOverlay.prototype = new WalkontableOverlay(); WalkontableDebugOverlay.prototype.destroy = function() { WalkontableOverlay.prototype.destroy.call(this); clearTimeout(this.lastTimeout); }; //# },{"./../../../dom.js":34,"./_overlay.js":6}],14:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableEvent: {get: function() { return WalkontableEvent; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47__46__46__47_eventManager_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47__46__46__47_eventManager_46_js__ = require("./../../../eventManager.js"), $___46__46__47__46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_eventManager_46_js__}).eventManager; ; window.WalkontableEvent = WalkontableEvent; function WalkontableEvent(instance) { var that = this; var eventManager = eventManagerObject(instance); this.instance = instance; var dblClickOrigin = [null, null]; this.dblClickTimeout = [null, null]; var onMouseDown = function(event) { var cell = that.parentCell(event.realTarget); if (dom.hasClass(event.realTarget, 'corner')) { that.instance.getSetting('onCellCornerMouseDown', event, event.realTarget); } else if (cell.TD) { if (that.instance.hasSetting('onCellMouseDown')) { that.instance.getSetting('onCellMouseDown', event, cell.coords, cell.TD, that.instance); } } if (event.button !== 2) { if (cell.TD) { dblClickOrigin[0] = cell.TD; clearTimeout(that.dblClickTimeout[0]); that.dblClickTimeout[0] = setTimeout(function() { dblClickOrigin[0] = null; }, 1000); } } }; var onTouchMove = function(event) { that.instance.touchMoving = true; }; var longTouchTimeout; var onTouchStart = function(event) { var container = this; eventManager.addEventListener(this, 'touchmove', onTouchMove); that.checkIfTouchMove = setTimeout(function() { if (that.instance.touchMoving === true) { that.instance.touchMoving = void 0; eventManager.removeEventListener("touchmove", onTouchMove, false); return; } else { onMouseDown(event); } }, 30); }; var lastMouseOver; var onMouseOver = function(event) { var table, td; if (that.instance.hasSetting('onCellMouseOver')) { table = that.instance.wtTable.TABLE; td = dom.closest(event.realTarget, ['TD', 'TH'], table); if (td && td !== lastMouseOver && dom.isChildOf(td, table)) { lastMouseOver = td; that.instance.getSetting('onCellMouseOver', event, that.instance.wtTable.getCoords(td), td, that.instance); } } }; var onMouseUp = function(event) { if (event.button !== 2) { var cell = that.parentCell(event.realTarget); if (cell.TD === dblClickOrigin[0] && cell.TD === dblClickOrigin[1]) { if (dom.hasClass(event.realTarget, 'corner')) { that.instance.getSetting('onCellCornerDblClick', event, cell.coords, cell.TD, that.instance); } else { that.instance.getSetting('onCellDblClick', event, cell.coords, cell.TD, that.instance); } dblClickOrigin[0] = null; dblClickOrigin[1] = null; } else if (cell.TD === dblClickOrigin[0]) { dblClickOrigin[1] = cell.TD; clearTimeout(that.dblClickTimeout[1]); that.dblClickTimeout[1] = setTimeout(function() { dblClickOrigin[1] = null; }, 500); } } }; var onTouchEnd = function(event) { clearTimeout(longTouchTimeout); event.preventDefault(); onMouseUp(event); }; eventManager.addEventListener(this.instance.wtTable.holder, 'mousedown', onMouseDown); eventManager.addEventListener(this.instance.wtTable.TABLE, 'mouseover', onMouseOver); eventManager.addEventListener(this.instance.wtTable.holder, 'mouseup', onMouseUp); if (this.instance.wtTable.holder.parentNode.parentNode && Handsontable.mobileBrowser && !that.instance.wtTable.isWorkingOnClone()) { var classSelector = "." + this.instance.wtTable.holder.parentNode.className.split(" ").join("."); eventManager.addEventListener(this.instance.wtTable.holder, 'touchstart', function(event) { that.instance.touchApplied = true; if (dom.isChildOf(event.target, classSelector)) { onTouchStart.call(event.target, event); } }); eventManager.addEventListener(this.instance.wtTable.holder, 'touchend', function(event) { that.instance.touchApplied = false; if (dom.isChildOf(event.target, classSelector)) { onTouchEnd.call(event.target, event); } }); if (!that.instance.momentumScrolling) { that.instance.momentumScrolling = {}; } eventManager.addEventListener(this.instance.wtTable.holder, 'scroll', function(event) { clearTimeout(that.instance.momentumScrolling._timeout); if (!that.instance.momentumScrolling.ongoing) { that.instance.getSetting('onBeforeTouchScroll'); } that.instance.momentumScrolling.ongoing = true; that.instance.momentumScrolling._timeout = setTimeout(function() { if (!that.instance.touchApplied) { that.instance.momentumScrolling.ongoing = false; that.instance.getSetting('onAfterMomentumScroll'); } }, 200); }); } eventManager.addEventListener(window, 'resize', function() { that.instance.draw(); }); this.destroy = function() { clearTimeout(this.dblClickTimeout[0]); clearTimeout(this.dblClickTimeout[1]); eventManager.clear(); }; } WalkontableEvent.prototype.parentCell = function(elem) { var cell = {}; var TABLE = this.instance.wtTable.TABLE; var TD = dom.closest(elem, ['TD', 'TH'], TABLE); if (TD && dom.isChildOf(TD, TABLE)) { cell.coords = this.instance.wtTable.getCoords(TD); cell.TD = TD; } else if (dom.hasClass(elem, 'wtBorder') && dom.hasClass(elem, 'current')) { cell.coords = this.instance.selections.current.cellRange.highlight; cell.TD = this.instance.wtTable.getCell(cell.coords); } else if (dom.hasClass(elem, 'wtBorder') && dom.hasClass(elem, 'area')) { if (this.instance.selections.area.cellRange) { cell.coords = this.instance.selections.area.cellRange.to; cell.TD = this.instance.wtTable.getCell(cell.coords); } } return cell; }; //# },{"./../../../dom.js":34,"./../../../eventManager.js":48}],15:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { walkontableRangesIntersect: {get: function() { return walkontableRangesIntersect; }}, walkontableRandomString: {get: function() { return walkontableRandomString; }}, __esModule: {value: true} }); window.walkontableRangesIntersect = walkontableRangesIntersect; window.walkontableRandomString = walkontableRandomString; function walkontableRangesIntersect() { var from = arguments[0]; var to = arguments[1]; for (var i = 1, ilen = arguments.length / 2; i < ilen; i++) { if (from <= arguments[2 * i + 1] && to >= arguments[2 * i]) { return true; } } return false; } function walkontableRandomString() { function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } return s4() + s4() + s4() + s4(); } //# },{}],16:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableOverlays: {get: function() { return WalkontableOverlays; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47__46__46__47_dom_46_js__; var eventManagerObject = ($___46__46__47__46__46__47__46__46__47_eventManager_46_js__ = require("./../../../eventManager.js"), $___46__46__47__46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_eventManager_46_js__}).eventManager; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); ; window.WalkontableOverlays = WalkontableOverlays; function WalkontableOverlays(instance) { this.instance = instance; instance.update('scrollbarWidth', dom.getScrollbarWidth()); instance.update('scrollbarHeight', dom.getScrollbarWidth()); this.topOverlay = new WalkontableTopOverlay(instance); this.leftOverlay = new WalkontableLeftOverlay(instance); this.topLeftCornerOverlay = new WalkontableCornerOverlay(instance); this.scrollCallbacksPending = 0; if (instance.getSetting('debug')) { this.debug = new WalkontableDebugOverlay(instance); } this.registerListeners(); } WalkontableOverlays.prototype.registerListeners = function() { var that = this; this.mainTableScrollableElement = dom.getScrollableElement(this.instance.wtTable.TABLE); this.refreshAll = function refreshAll() { if (!that.instance.drawn) { return; } if (!that.instance.wtTable.holder.parentNode) { that.destroy(); return; } that.instance.draw(true); that.topOverlay.onScroll(); that.leftOverlay.onScroll(); }; var eventManager = eventManagerObject(that.instance); this.requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; this.overlayScrollPositions = { 'master': { top: 0, left: 0 }, 'top': { top: null, left: 0 }, 'left': { top: 0, left: null } }; eventManager.addEventListener(this.mainTableScrollableElement, 'scroll', function(e) { that.requestAnimFrame.call(window, function() { that.syncScrollPositions(e); }); }); eventManager.addEventListener(this.topOverlay.clone.wtTable.holder, 'scroll', function(e) { that.requestAnimFrame.call(window, function() { that.syncScrollPositions(e); }); }); eventManager.addEventListener(this.topOverlay.clone.wtTable.holder, 'wheel', function(e) { that.requestAnimFrame.call(window, function() { that.translateMouseWheelToScroll(e); }); }); eventManager.addEventListener(this.leftOverlay.clone.wtTable.holder, 'scroll', function(e) { that.requestAnimFrame.call(window, function() { that.syncScrollPositions(e); }); }); eventManager.addEventListener(this.leftOverlay.clone.wtTable.holder, 'wheel', function(e) { that.requestAnimFrame.call(window, function() { that.translateMouseWheelToScroll(e); }); }); if (this.topOverlay.trimmingContainer !== window && this.leftOverlay.trimmingContainer !== window) { eventManager.addEventListener(window, 'scroll', function(e) { that.refreshAll(); }); eventManager.addEventListener(window, 'wheel', function(e) { var overlay, deltaY = e.wheelDeltaY || e.deltaY, deltaX = e.wheelDeltaX || e.deltaX; if (that.topOverlay.clone.wtTable.holder.contains(e.target)) { overlay = 'top'; } else if (that.leftOverlay.clone.wtTable.holder.contains(e.target)) { overlay = 'left'; } if (overlay == 'top' && deltaY !== 0) { e.preventDefault(); } else if (overlay == 'left' && deltaX !== 0) { e.preventDefault(); } }); } }; WalkontableOverlays.prototype.translateMouseWheelToScroll = function(e) { var topOverlay = this.topOverlay.clone.wtTable.holder, leftOverlay = this.leftOverlay.clone.wtTable.holder, parentHolder, tempElem = e.target, eventMockup = {}, deltaY = e.wheelDeltaY || (-1) * e.deltaY, deltaX = e.wheelDeltaX || (-1) * e.deltaX; while (tempElem != document && tempElem != null) { if (tempElem.className.indexOf('wtHolder') > -1) { parentHolder = tempElem; break; } tempElem = tempElem.parentNode; } eventMockup.target = parentHolder; if (parentHolder == topOverlay) { this.syncScrollPositions(eventMockup, (-0.2) * deltaY); } else if (parentHolder == leftOverlay) { this.syncScrollPositions(eventMockup, (-0.2) * deltaX); } return false; }; WalkontableOverlays.prototype.syncScrollPositions = function(e, fakeScrollValue) { if (this.destroyed) { return; } if (this.scrollCallbacksPending > 0) { this.scrollCallbacksPending--; return; } var target = e.target, master = this.topOverlay.mainTableScrollableElement, topOverlay = this.topOverlay.clone.wtTable.holder, leftOverlay = this.leftOverlay.clone.wtTable.holder, tempScrollValue = 0, scrollValueChanged = false; if (target === document) { target = window; } if (target === master || target === document) { tempScrollValue = dom.getScrollLeft(target); if (this.overlayScrollPositions.master.left !== tempScrollValue) { this.scrollCallbacksPending++; topOverlay.scrollLeft = tempScrollValue; this.overlayScrollPositions.master.left = tempScrollValue; scrollValueChanged = true; } tempScrollValue = dom.getScrollTop(target); if (this.overlayScrollPositions.master.top !== tempScrollValue) { this.scrollCallbacksPending++; leftOverlay.scrollTop = tempScrollValue; this.overlayScrollPositions.master.top = tempScrollValue; scrollValueChanged = true; } } else if (target === topOverlay) { tempScrollValue = dom.getScrollLeft(target); if (this.overlayScrollPositions.top.left !== tempScrollValue) { this.scrollCallbacksPending++; master.scrollLeft = tempScrollValue; this.overlayScrollPositions.top.left = tempScrollValue; scrollValueChanged = true; } if (fakeScrollValue) { master.scrollTop += fakeScrollValue; } } else if (target === leftOverlay) { tempScrollValue = dom.getScrollTop(target); if (this.overlayScrollPositions.left.top !== tempScrollValue) { this.scrollCallbacksPending++; master.scrollTop = tempScrollValue; this.overlayScrollPositions.left.top = tempScrollValue; scrollValueChanged = true; } if (fakeScrollValue) { master.scrollLeft += fakeScrollValue; } } if (scrollValueChanged) { this.refreshAll(); } }; WalkontableOverlays.prototype.destroy = function() { var eventManager = eventManagerObject(this.instance); if (this.topOverlay) { this.topOverlay.destroy(); eventManager.removeEventListener(this.topOverlay.trimmingContainer, 'scroll', this.refreshAll); } if (this.leftOverlay) { this.leftOverlay.destroy(); eventManager.removeEventListener(this.leftOverlay.trimmingContainer, 'scroll', this.refreshAll); } eventManager.removeEventListener(window, 'scroll', this.refreshAll); if (this.topLeftCornerOverlay) { this.topLeftCornerOverlay.destroy(); } if (this.debug) { this.debug.destroy(); } this.destroyed = true; }; WalkontableOverlays.prototype.refresh = function(fastDraw) { if (this.leftOverlay) { this.leftOverlay.refresh(fastDraw); } if (this.topOverlay) { this.topOverlay.refresh(fastDraw); } if (this.topLeftCornerOverlay) { this.topLeftCornerOverlay.refresh(fastDraw); } if (this.debug) { this.debug.refresh(fastDraw); } }; WalkontableOverlays.prototype.applyToDOM = function() { if (this.leftOverlay) { this.leftOverlay.applyToDOM(); } if (this.topOverlay) { this.topOverlay.applyToDOM(); } }; //# },{"./../../../dom.js":34,"./../../../eventManager.js":48}],17:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableRowFilter: {get: function() { return WalkontableRowFilter; }}, __esModule: {value: true} }); ; window.WalkontableRowFilter = WalkontableRowFilter; function WalkontableRowFilter(offset, total, countTH) { this.offset = offset; this.total = total; this.countTH = countTH; } WalkontableRowFilter.prototype.offsetted = function(n) { return n + this.offset; }; WalkontableRowFilter.prototype.unOffsetted = function(n) { return n - this.offset; }; WalkontableRowFilter.prototype.renderedToSource = function(n) { return this.offsetted(n); }; WalkontableRowFilter.prototype.sourceToRendered = function(n) { return this.unOffsetted(n); }; WalkontableRowFilter.prototype.offsettedTH = function(n) { return n - this.countTH; }; WalkontableRowFilter.prototype.visibleColHeadedRowToSourceRow = function(n) { return this.renderedToSource(this.offsettedTH(n)); }; WalkontableRowFilter.prototype.sourceRowToVisibleColHeadedRow = function(n) { return this.unOffsettedTH(this.sourceToRendered(n)); }; //# },{}],18:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableScroll: {get: function() { return WalkontableScroll; }}, __esModule: {value: true} }); ; window.WalkontableScroll = WalkontableScroll; function WalkontableScroll(instance) { this.instance = instance; } WalkontableScroll.prototype.scrollViewport = function(coords) { if (!this.instance.drawn) { return; } var totalRows = this.instance.getSetting('totalRows'), totalColumns = this.instance.getSetting('totalColumns'); if (coords.row < 0 || coords.row > totalRows - 1) { throw new Error('row ' + coords.row + ' does not exist'); } if (coords.col < 0 || coords.col > totalColumns - 1) { throw new Error('column ' + coords.col + ' does not exist'); } if (coords.row > this.instance.wtTable.getLastVisibleRow()) { this.instance.wtOverlays.topOverlay.scrollTo(coords.row, true); } else if (coords.row >= this.instance.getSetting('fixedRowsTop') && coords.row < this.instance.wtTable.getFirstVisibleRow()) { this.instance.wtOverlays.topOverlay.scrollTo(coords.row); } if (coords.col > this.instance.wtTable.getLastVisibleColumn()) { this.instance.wtOverlays.leftOverlay.scrollTo(coords.col, true); } else if (coords.col >= this.instance.getSetting('fixedColumnsLeft') && coords.col < this.instance.wtTable.getFirstVisibleColumn()) { this.instance.wtOverlays.leftOverlay.scrollTo(coords.col); } }; //# },{}],19:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableHorizontalScrollbarNative: {get: function() { return WalkontableHorizontalScrollbarNative; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $___95_overlay_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var WalkontableOverlay = ($___95_overlay_46_js__ = require("./_overlay.js"), $___95_overlay_46_js__ && $___95_overlay_46_js__.__esModule && $___95_overlay_46_js__ || {default: $___95_overlay_46_js__}).WalkontableOverlay; ; window.WalkontableHorizontalScrollbarNative = WalkontableHorizontalScrollbarNative; function WalkontableHorizontalScrollbarNative(instance) { this.instance = instance; this.type = 'horizontal'; this.offset = 0; this.init(); this.clone = this.makeClone('left'); } WalkontableHorizontalScrollbarNative.prototype = new WalkontableOverlay(); WalkontableHorizontalScrollbarNative.prototype.resetFixedPosition = function() { var finalLeft, finalTop; if (!this.instance.wtTable.holder.parentNode) { return; } var elem = this.clone.wtTable.holder.parentNode; if (this.scrollHandler === window) { var box = this.instance.wtTable.holder.getBoundingClientRect(); var left = Math.ceil(box.left); var right = Math.ceil(box.right); if (left < 0 && (right - elem.offsetWidth) > 0) { finalLeft = -left + 'px'; } else { finalLeft = '0'; } finalTop = this.instance.wtTable.hider.style.top; } else if (!Handsontable.freezeOverlays) { finalLeft = this.getScrollPosition() + "px"; finalTop = this.instance.wtTable.hider.style.top; } dom.setOverlayPosition(elem, finalLeft, finalTop); elem.style.height = dom.outerHeight(this.clone.wtTable.TABLE) + 'px'; elem.style.width = dom.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px'; }; WalkontableHorizontalScrollbarNative.prototype.refresh = function(fastDraw) { this.applyToDOM(); WalkontableOverlay.prototype.refresh.call(this, fastDraw); }; WalkontableHorizontalScrollbarNative.prototype.getScrollPosition = function() { return dom.getScrollLeft(this.scrollHandler); }; WalkontableHorizontalScrollbarNative.prototype.setScrollPosition = function(pos) { if (this.scrollHandler === window) { window.scrollTo(pos, dom.getWindowScrollTop()); } else { this.scrollHandler.scrollLeft = pos; } }; WalkontableHorizontalScrollbarNative.prototype.onScroll = function() { this.instance.getSetting('onScrollHorizontally'); }; WalkontableHorizontalScrollbarNative.prototype.sumCellSizes = function(from, length) { var sum = 0; while (from < length) { sum += this.instance.wtTable.getStretchedColumnWidth(from) || this.instance.wtSettings.defaultColumnWidth; from++; } return sum; }; WalkontableHorizontalScrollbarNative.prototype.applyToDOM = function() { var total = this.instance.getSetting('totalColumns'); var headerSize = this.instance.wtViewport.getRowHeaderWidth(); this.fixedContainer.style.width = headerSize + this.sumCellSizes(0, total) + 'px'; if (typeof this.instance.wtViewport.columnsRenderCalculator.startPosition === 'number') { this.fixed.style.left = this.instance.wtViewport.columnsRenderCalculator.startPosition + 'px'; } else if (total === 0) { this.fixed.style.left = '0'; } else { throw new Error('Incorrect value of the columnsRenderCalculator'); } this.fixed.style.right = ''; }; WalkontableHorizontalScrollbarNative.prototype.scrollTo = function(sourceCol, beyondRendered) { var newX = this.getTableParentOffset(); if (beyondRendered) { newX += this.sumCellSizes(0, sourceCol + 1); newX -= this.instance.wtViewport.getViewportWidth(); } else { var fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft'); newX += this.sumCellSizes(fixedColumnsLeft, sourceCol); } this.setScrollPosition(newX); }; WalkontableHorizontalScrollbarNative.prototype.getTableParentOffset = function() { if (this.scrollHandler === window) { return this.instance.wtTable.holderOffset.left; } else { return 0; } }; //# },{"./../../../dom.js":34,"./_overlay.js":6}],20:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableSelection: {get: function() { return WalkontableSelection; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $__border_46_js__, $__cellCoords_46_js__, $__cellRange_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var WalkontableBorder = ($__border_46_js__ = require("./border.js"), $__border_46_js__ && $__border_46_js__.__esModule && $__border_46_js__ || {default: $__border_46_js__}).WalkontableBorder; var WalkontableCellCoords = ($__cellCoords_46_js__ = require("./cellCoords.js"), $__cellCoords_46_js__ && $__cellCoords_46_js__.__esModule && $__cellCoords_46_js__ || {default: $__cellCoords_46_js__}).WalkontableCellCoords; var WalkontableCellRange = ($__cellRange_46_js__ = require("./cellRange.js"), $__cellRange_46_js__ && $__cellRange_46_js__.__esModule && $__cellRange_46_js__ || {default: $__cellRange_46_js__}).WalkontableCellRange; ; window.WalkontableSelection = WalkontableSelection; function WalkontableSelection(settings, cellRange) { this.settings = settings; this.cellRange = cellRange || null; this.instanceBorders = {}; } WalkontableSelection.prototype.getBorder = function(instance) { if (this.instanceBorders[instance.guid]) { return this.instanceBorders[instance.guid]; } this.instanceBorders[instance.guid] = new WalkontableBorder(instance, this.settings); }; WalkontableSelection.prototype.isEmpty = function() { return this.cellRange === null; }; WalkontableSelection.prototype.add = function(coords) { if (this.isEmpty()) { this.cellRange = new WalkontableCellRange(coords, coords, coords); } else { this.cellRange.expand(coords); } }; WalkontableSelection.prototype.replace = function(oldCoords, newCoords) { if (!this.isEmpty()) { if (this.cellRange.from.isEqual(oldCoords)) { this.cellRange.from = newCoords; return true; } if (this.cellRange.to.isEqual(oldCoords)) { this.cellRange.to = newCoords; return true; } } return false; }; WalkontableSelection.prototype.clear = function() { this.cellRange = null; }; WalkontableSelection.prototype.getCorners = function() { var topLeft = this.cellRange.getTopLeftCorner(), bottomRight = this.cellRange.getBottomRightCorner(); return [topLeft.row, topLeft.col, bottomRight.row, bottomRight.col]; }; WalkontableSelection.prototype.addClassAtCoords = function(instance, sourceRow, sourceColumn, cls) { var TD = instance.wtTable.getCell(new WalkontableCellCoords(sourceRow, sourceColumn)); if (typeof TD === 'object') { dom.addClass(TD, cls); } }; WalkontableSelection.prototype.draw = function(instance) { var _this = this, renderedRows = instance.wtTable.getRenderedRowsCount(), renderedColumns = instance.wtTable.getRenderedColumnsCount(), corners, sourceRow, sourceCol, border, TH; if (this.isEmpty()) { if (this.settings.border) { border = this.getBorder(instance); if (border) { border.disappear(); } } return; } corners = this.getCorners(); for (var column = 0; column < renderedColumns; column++) { sourceCol = instance.wtTable.columnFilter.renderedToSource(column); if (sourceCol >= corners[1] && sourceCol <= corners[3]) { TH = instance.wtTable.getColumnHeader(sourceCol); if (TH && _this.settings.highlightColumnClassName) { dom.addClass(TH, _this.settings.highlightColumnClassName); } } } for (var row = 0; row < renderedRows; row++) { sourceRow = instance.wtTable.rowFilter.renderedToSource(row); if (sourceRow >= corners[0] && sourceRow <= corners[2]) { TH = instance.wtTable.getRowHeader(sourceRow); if (TH && _this.settings.highlightRowClassName) { dom.addClass(TH, _this.settings.highlightRowClassName); } } for (var column = 0; column < renderedColumns; column++) { sourceCol = instance.wtTable.columnFilter.renderedToSource(column); if (sourceRow >= corners[0] && sourceRow <= corners[2] && sourceCol >= corners[1] && sourceCol <= corners[3]) { if (_this.settings.className) { _this.addClassAtCoords(instance, sourceRow, sourceCol, _this.settings.className); } } else if (sourceRow >= corners[0] && sourceRow <= corners[2]) { if (_this.settings.highlightRowClassName) { _this.addClassAtCoords(instance, sourceRow, sourceCol, _this.settings.highlightRowClassName); } } else if (sourceCol >= corners[1] && sourceCol <= corners[3]) { if (_this.settings.highlightColumnClassName) { _this.addClassAtCoords(instance, sourceRow, sourceCol, _this.settings.highlightColumnClassName); } } } } instance.getSetting('onBeforeDrawBorders', corners, this.settings.className); if (this.settings.border) { border = this.getBorder(instance); if (border) { border.appear(corners); } } }; //# },{"./../../../dom.js":34,"./border.js":7,"./cellCoords.js":8,"./cellRange.js":9}],21:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableSettings: {get: function() { return WalkontableSettings; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); ; window.WalkontableSettings = WalkontableSettings; function WalkontableSettings(instance, settings) { var that = this; this.instance = instance; this.defaults = { table: void 0, debug: false, stretchH: 'none', currentRowClassName: null, currentColumnClassName: null, data: void 0, fixedColumnsLeft: 0, fixedRowsTop: 0, rowHeaders: function() { return []; }, columnHeaders: function() { return []; }, totalRows: void 0, totalColumns: void 0, cellRenderer: function(row, column, TD) { var cellData = that.getSetting('data', row, column); dom.fastInnerText(TD, cellData === void 0 || cellData === null ? '' : cellData); }, columnWidth: function(col) { return; }, rowHeight: function(row) { return; }, defaultRowHeight: 23, defaultColumnWidth: 50, selections: null, hideBorderOnMouseDownOver: false, viewportRowCalculatorOverride: null, viewportColumnCalculatorOverride: null, onCellMouseDown: null, onCellMouseOver: null, onCellDblClick: null, onCellCornerMouseDown: null, onCellCornerDblClick: null, beforeDraw: null, onDraw: null, onBeforeDrawBorders: null, onScrollVertically: null, onScrollHorizontally: null, onBeforeTouchScroll: null, onAfterMomentumScroll: null, scrollbarWidth: 10, scrollbarHeight: 10, renderAllRows: false, groups: false }; this.settings = {}; for (var i in this.defaults) { if (this.defaults.hasOwnProperty(i)) { if (settings[i] !== void 0) { this.settings[i] = settings[i]; } else if (this.defaults[i] === void 0) { throw new Error('A required setting "' + i + '" was not provided'); } else { this.settings[i] = this.defaults[i]; } } } } WalkontableSettings.prototype.update = function(settings, value) { if (value === void 0) { for (var i in settings) { if (settings.hasOwnProperty(i)) { this.settings[i] = settings[i]; } } } else { this.settings[settings] = value; } return this.instance; }; WalkontableSettings.prototype.getSetting = function(key, param1, param2, param3, param4) { if (typeof this.settings[key] === 'function') { return this.settings[key](param1, param2, param3, param4); } else if (param1 !== void 0 && Array.isArray(this.settings[key])) { return this.settings[key][param1]; } else { return this.settings[key]; } }; WalkontableSettings.prototype.has = function(key) { return !!this.settings[key]; }; //# },{"./../../../dom.js":34}],22:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableTable: {get: function() { return WalkontableTable; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $__cellCoords_46_js__, $__cellRange_46_js__, $__columnFilter_46_js__, $__walkontableCornerOverlay_46_js__, $__debugOverlay_46_js__, $__scrollbarNativeHorizontal_46_js__, $__walkontableLeftOverlay_46_js__, $__rowFilter_46_js__, $__tableRenderer_46_js__, $__walkontableTopOverlay_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var WalkontableCellCoords = ($__cellCoords_46_js__ = require("./cellCoords.js"), $__cellCoords_46_js__ && $__cellCoords_46_js__.__esModule && $__cellCoords_46_js__ || {default: $__cellCoords_46_js__}).WalkontableCellCoords; var WalkontableCellRange = ($__cellRange_46_js__ = require("./cellRange.js"), $__cellRange_46_js__ && $__cellRange_46_js__.__esModule && $__cellRange_46_js__ || {default: $__cellRange_46_js__}).WalkontableCellRange; var WalkontableColumnFilter = ($__columnFilter_46_js__ = require("./columnFilter.js"), $__columnFilter_46_js__ && $__columnFilter_46_js__.__esModule && $__columnFilter_46_js__ || {default: $__columnFilter_46_js__}).WalkontableColumnFilter; var WalkontableCornerOverlay = ($__walkontableCornerOverlay_46_js__ = require("./walkontableCornerOverlay.js"), $__walkontableCornerOverlay_46_js__ && $__walkontableCornerOverlay_46_js__.__esModule && $__walkontableCornerOverlay_46_js__ || {default: $__walkontableCornerOverlay_46_js__}).WalkontableCornerOverlay; var WalkontableDebugOverlay = ($__debugOverlay_46_js__ = require("./debugOverlay.js"), $__debugOverlay_46_js__ && $__debugOverlay_46_js__.__esModule && $__debugOverlay_46_js__ || {default: $__debugOverlay_46_js__}).WalkontableDebugOverlay; var WalkontableHorizontalScrollbarNative = ($__scrollbarNativeHorizontal_46_js__ = require("./scrollbarNativeHorizontal.js"), $__scrollbarNativeHorizontal_46_js__ && $__scrollbarNativeHorizontal_46_js__.__esModule && $__scrollbarNativeHorizontal_46_js__ || {default: $__scrollbarNativeHorizontal_46_js__}).WalkontableHorizontalScrollbarNative; var WalkontableLeftOverlay = ($__walkontableLeftOverlay_46_js__ = require("./walkontableLeftOverlay.js"), $__walkontableLeftOverlay_46_js__ && $__walkontableLeftOverlay_46_js__.__esModule && $__walkontableLeftOverlay_46_js__ || {default: $__walkontableLeftOverlay_46_js__}).WalkontableLeftOverlay; var WalkontableRowFilter = ($__rowFilter_46_js__ = require("./rowFilter.js"), $__rowFilter_46_js__ && $__rowFilter_46_js__.__esModule && $__rowFilter_46_js__ || {default: $__rowFilter_46_js__}).WalkontableRowFilter; var WalkontableTableRenderer = ($__tableRenderer_46_js__ = require("./tableRenderer.js"), $__tableRenderer_46_js__ && $__tableRenderer_46_js__.__esModule && $__tableRenderer_46_js__ || {default: $__tableRenderer_46_js__}).WalkontableTableRenderer; var WalkontableTopOverlay = ($__walkontableTopOverlay_46_js__ = require("./walkontableTopOverlay.js"), $__walkontableTopOverlay_46_js__ && $__walkontableTopOverlay_46_js__.__esModule && $__walkontableTopOverlay_46_js__ || {default: $__walkontableTopOverlay_46_js__}).WalkontableTopOverlay; ; window.WalkontableTable = WalkontableTable; function WalkontableTable(instance, table) { this.instance = instance; this.TABLE = table; dom.removeTextNodes(this.TABLE); var parent = this.TABLE.parentNode; if (!parent || parent.nodeType !== 1 || !dom.hasClass(parent, 'wtHolder')) { var spreader = document.createElement('DIV'); spreader.className = 'wtSpreader'; if (parent) { parent.insertBefore(spreader, this.TABLE); } spreader.appendChild(this.TABLE); } this.spreader = this.TABLE.parentNode; this.spreader.style.position = 'relative'; parent = this.spreader.parentNode; if (!parent || parent.nodeType !== 1 || !dom.hasClass(parent, 'wtHolder')) { var hider = document.createElement('DIV'); hider.className = 'wtHider'; if (parent) { parent.insertBefore(hider, this.spreader); } hider.appendChild(this.spreader); } this.hider = this.spreader.parentNode; parent = this.hider.parentNode; if (!parent || parent.nodeType !== 1 || !dom.hasClass(parent, 'wtHolder')) { var holder = document.createElement('DIV'); holder.style.position = 'relative'; holder.className = 'wtHolder'; if (parent) { parent.insertBefore(holder, this.hider); } if (!instance.cloneSource) { holder.parentNode.className += 'ht_master handsontable'; } holder.appendChild(this.hider); } this.holder = this.hider.parentNode; this.wtRootElement = this.holder.parentNode; this.alignOverlaysWithTrimmingContainer(); this.TBODY = this.TABLE.getElementsByTagName('TBODY')[0]; if (!this.TBODY) { this.TBODY = document.createElement('TBODY'); this.TABLE.appendChild(this.TBODY); } this.THEAD = this.TABLE.getElementsByTagName('THEAD')[0]; if (!this.THEAD) { this.THEAD = document.createElement('THEAD'); this.TABLE.insertBefore(this.THEAD, this.TBODY); } this.COLGROUP = this.TABLE.getElementsByTagName('COLGROUP')[0]; if (!this.COLGROUP) { this.COLGROUP = document.createElement('COLGROUP'); this.TABLE.insertBefore(this.COLGROUP, this.THEAD); } if (this.instance.getSetting('columnHeaders').length) { if (!this.THEAD.childNodes.length) { var TR = document.createElement('TR'); this.THEAD.appendChild(TR); } } this.colgroupChildrenLength = this.COLGROUP.childNodes.length; this.theadChildrenLength = this.THEAD.firstChild ? this.THEAD.firstChild.childNodes.length : 0; this.tbodyChildrenLength = this.TBODY.childNodes.length; this.rowFilter = null; this.columnFilter = null; } WalkontableTable.prototype.alignOverlaysWithTrimmingContainer = function() { var trimmingElement = dom.getTrimmingContainer(this.wtRootElement); if (!this.isWorkingOnClone()) { this.holder.parentNode.style.position = 'relative'; if (trimmingElement !== window) { this.holder.style.width = dom.getStyle(trimmingElement, 'width'); this.holder.style.height = dom.getStyle(trimmingElement, 'height'); this.holder.style.overflow = ''; } else { this.holder.style.overflow = 'visible'; this.wtRootElement.style.overflow = 'visible'; } } }; WalkontableTable.prototype.isWorkingOnClone = function() { return !!this.instance.cloneSource; }; WalkontableTable.prototype.draw = function(fastDraw) { if (!this.isWorkingOnClone()) { this.holderOffset = dom.offset(this.holder); fastDraw = this.instance.wtViewport.createRenderCalculators(fastDraw); } if (!fastDraw) { if (this.isWorkingOnClone()) { this.tableOffset = this.instance.cloneSource.wtTable.tableOffset; } else { this.tableOffset = dom.offset(this.TABLE); } var startRow; if (this.instance.cloneOverlay instanceof WalkontableDebugOverlay || this.instance.cloneOverlay instanceof WalkontableTopOverlay || this.instance.cloneOverlay instanceof WalkontableCornerOverlay) { startRow = 0; } else { startRow = this.instance.wtViewport.rowsRenderCalculator.startRow; } var startColumn; if (this.instance.cloneOverlay instanceof WalkontableDebugOverlay || this.instance.cloneOverlay instanceof WalkontableLeftOverlay || this.instance.cloneOverlay instanceof WalkontableCornerOverlay) { startColumn = 0; } else { startColumn = this.instance.wtViewport.columnsRenderCalculator.startColumn; } this.rowFilter = new WalkontableRowFilter(startRow, this.instance.getSetting('totalRows'), this.instance.getSetting('columnHeaders').length); this.columnFilter = new WalkontableColumnFilter(startColumn, this.instance.getSetting('totalColumns'), this.instance.getSetting('rowHeaders').length); this._doDraw(); this.alignOverlaysWithTrimmingContainer(); } else { if (!this.isWorkingOnClone()) { this.instance.wtViewport.createVisibleCalculators(); } if (this.instance.wtOverlays) { this.instance.wtOverlays.refresh(true); } } this.refreshSelections(fastDraw); if (!this.isWorkingOnClone()) { this.instance.wtOverlays.topOverlay.resetFixedPosition(); this.instance.wtOverlays.leftOverlay.resetFixedPosition(); this.instance.wtOverlays.topLeftCornerOverlay.resetFixedPosition(); } this.instance.drawn = true; return this; }; WalkontableTable.prototype._doDraw = function() { var wtRenderer = new WalkontableTableRenderer(this); wtRenderer.render(); }; WalkontableTable.prototype.removeClassFromCells = function(className) { var nodes = this.TABLE.querySelectorAll('.' + className); for (var i = 0, ilen = nodes.length; i < ilen; i++) { dom.removeClass(nodes[i], className); } }; WalkontableTable.prototype.refreshSelections = function(fastDraw) { var i, len; if (!this.instance.selections) { return; } len = this.instance.selections.length; if (fastDraw) { for (i = 0; i < len; i++) { if (this.instance.selections[i].settings.className) { this.removeClassFromCells(this.instance.selections[i].settings.className); } if (this.instance.selections[i].settings.highlightRowClassName) { this.removeClassFromCells(this.instance.selections[i].settings.highlightRowClassName); } if (this.instance.selections[i].settings.highlightColumnClassName) { this.removeClassFromCells(this.instance.selections[i].settings.highlightColumnClassName); } } } for (i = 0; i < len; i++) { this.instance.selections[i].draw(this.instance, fastDraw); } }; WalkontableTable.prototype.getCell = function(coords) { if (this.isRowBeforeRenderedRows(coords.row)) { return -1; } else if (this.isRowAfterRenderedRows(coords.row)) { return -2; } var TR = this.TBODY.childNodes[this.rowFilter.sourceToRendered(coords.row)]; if (TR) { return TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(coords.col)]; } }; WalkontableTable.prototype.getColumnHeader = function(col, level) { if (!level) { level = 0; } var TR = this.THEAD.childNodes[level]; if (TR) { return TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(col)]; } }; WalkontableTable.prototype.getRowHeader = function(row) { if (this.columnFilter.sourceColumnToVisibleRowHeadedColumn(0) === 0) { return null; } var TR = this.TBODY.childNodes[this.rowFilter.sourceToRendered(row)]; if (TR) { return TR.childNodes[0]; } }; WalkontableTable.prototype.getCoords = function(TD) { var TR = TD.parentNode; var row = dom.index(TR); if (TR.parentNode === this.THEAD) { row = this.rowFilter.visibleColHeadedRowToSourceRow(row); } else { row = this.rowFilter.renderedToSource(row); } return new WalkontableCellCoords(row, this.columnFilter.visibleRowHeadedColumnToSourceColumn(TD.cellIndex)); }; WalkontableTable.prototype.getTrForRow = function(row) { return this.TBODY.childNodes[this.rowFilter.sourceToRendered(row)]; }; WalkontableTable.prototype.getFirstRenderedRow = function() { return this.instance.wtViewport.rowsRenderCalculator.startRow; }; WalkontableTable.prototype.getFirstVisibleRow = function() { return this.instance.wtViewport.rowsVisibleCalculator.startRow; }; WalkontableTable.prototype.getFirstRenderedColumn = function() { return this.instance.wtViewport.columnsRenderCalculator.startColumn; }; WalkontableTable.prototype.getFirstVisibleColumn = function() { return this.instance.wtViewport.columnsVisibleCalculator.startColumn; }; WalkontableTable.prototype.getLastRenderedRow = function() { return this.instance.wtViewport.rowsRenderCalculator.endRow; }; WalkontableTable.prototype.getLastVisibleRow = function() { return this.instance.wtViewport.rowsVisibleCalculator.endRow; }; WalkontableTable.prototype.getLastRenderedColumn = function() { return this.instance.wtViewport.columnsRenderCalculator.endColumn; }; WalkontableTable.prototype.getLastVisibleColumn = function() { return this.instance.wtViewport.columnsVisibleCalculator.endColumn; }; WalkontableTable.prototype.isRowBeforeRenderedRows = function(r) { return (this.rowFilter.sourceToRendered(r) < 0 && r >= 0); }; WalkontableTable.prototype.isRowAfterViewport = function(r) { return (r > this.getLastVisibleRow()); }; WalkontableTable.prototype.isRowAfterRenderedRows = function(r) { return (r > this.getLastRenderedRow()); }; WalkontableTable.prototype.isColumnBeforeViewport = function(c) { return (this.columnFilter.sourceToRendered(c) < 0 && c >= 0); }; WalkontableTable.prototype.isColumnAfterViewport = function(c) { return (c > this.getLastVisibleColumn()); }; WalkontableTable.prototype.isLastRowFullyVisible = function() { return (this.getLastVisibleRow() === this.getLastRenderedRow()); }; WalkontableTable.prototype.isLastColumnFullyVisible = function() { return (this.getLastVisibleColumn() === this.getLastRenderedColumn); }; WalkontableTable.prototype.getRenderedColumnsCount = function() { if (this.instance.cloneOverlay instanceof WalkontableDebugOverlay) { return this.instance.getSetting('totalColumns'); } else if (this.instance.cloneOverlay instanceof WalkontableLeftOverlay || this.instance.cloneOverlay instanceof WalkontableCornerOverlay) { return this.instance.getSetting('fixedColumnsLeft'); } else { return this.instance.wtViewport.columnsRenderCalculator.count; } }; WalkontableTable.prototype.getRenderedRowsCount = function() { if (this.instance.cloneOverlay instanceof WalkontableDebugOverlay) { return this.instance.getSetting('totalRows'); } else if (this.instance.cloneOverlay instanceof WalkontableTopOverlay || this.instance.cloneOverlay instanceof WalkontableCornerOverlay) { return this.instance.getSetting('fixedRowsTop'); } return this.instance.wtViewport.rowsRenderCalculator.count; }; WalkontableTable.prototype.getVisibleRowsCount = function() { return this.instance.wtViewport.rowsVisibleCalculator.count; }; WalkontableTable.prototype.allRowsInViewport = function() { return this.instance.getSetting('totalRows') == this.getVisibleRowsCount(); }; WalkontableTable.prototype.getRowHeight = function(sourceRow) { var height = this.instance.wtSettings.settings.rowHeight(sourceRow), oversizedHeight = this.instance.wtViewport.oversizedRows[sourceRow]; if (oversizedHeight !== void 0) { height = height ? Math.max(height, oversizedHeight) : oversizedHeight; } return height; }; WalkontableTable.prototype.getColumnHeaderHeight = function(level) { var height = this.instance.wtSettings.settings.defaultRowHeight, oversizedHeight = this.instance.wtViewport.oversizedColumnHeaders[level]; if (oversizedHeight !== void 0) { height = height ? Math.max(height, oversizedHeight) : oversizedHeight; } return height; }; WalkontableTable.prototype.getVisibleColumnsCount = function() { return this.instance.wtViewport.columnsVisibleCalculator.count; }; WalkontableTable.prototype.allColumnsInViewport = function() { return this.instance.getSetting('totalColumns') == this.getVisibleColumnsCount(); }; WalkontableTable.prototype.getColumnWidth = function(sourceColumn) { var width = this.instance.wtSettings.settings.columnWidth; if (typeof width === 'function') { width = width(sourceColumn); } else if (typeof width === 'object') { width = width[sourceColumn]; } var oversizedWidth = this.instance.wtViewport.oversizedCols[sourceColumn]; if (oversizedWidth !== void 0) { width = width ? Math.max(width, oversizedWidth) : oversizedWidth; } return width; }; WalkontableTable.prototype.getStretchedColumnWidth = function(sourceColumn) { var width = this.getColumnWidth(sourceColumn) || this.instance.wtSettings.settings.defaultColumnWidth, calculator = this.instance.wtViewport.columnsRenderCalculator, stretchedWidth; if (calculator) { stretchedWidth = calculator.getStretchedColumnWidth(sourceColumn, width); if (stretchedWidth) { width = stretchedWidth; } } return width; }; //# },{"./../../../dom.js":34,"./cellCoords.js":8,"./cellRange.js":9,"./columnFilter.js":10,"./debugOverlay.js":13,"./rowFilter.js":17,"./scrollbarNativeHorizontal.js":19,"./tableRenderer.js":23,"./walkontableCornerOverlay.js":27,"./walkontableLeftOverlay.js":28,"./walkontableTopOverlay.js":29}],23:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableTableRenderer: {get: function() { return WalkontableTableRenderer; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); ; window.WalkontableTableRenderer = WalkontableTableRenderer; function WalkontableTableRenderer(wtTable) { this.wtTable = wtTable; this.instance = wtTable.instance; this.rowFilter = wtTable.rowFilter; this.columnFilter = wtTable.columnFilter; this.TABLE = wtTable.TABLE; this.THEAD = wtTable.THEAD; this.TBODY = wtTable.TBODY; this.COLGROUP = wtTable.COLGROUP; this.utils = WalkontableTableRenderer.utils; } WalkontableTableRenderer.prototype.render = function() { if (!this.wtTable.isWorkingOnClone()) { this.instance.getSetting('beforeDraw', true); } this.rowHeaders = this.instance.getSetting('rowHeaders'); this.rowHeaderCount = this.rowHeaders.length; this.fixedRowsTop = this.instance.getSetting('fixedRowsTop'); this.columnHeaders = this.instance.getSetting('columnHeaders'); this.columnHeaderCount = this.columnHeaders.length; var visibleColIndex, totalRows = this.instance.getSetting('totalRows'), totalColumns = this.instance.getSetting('totalColumns'), columnsToRender = this.wtTable.getRenderedColumnsCount(), adjusted = false, workspaceWidth, rowsToRender = this.wtTable.getRenderedRowsCount(); if (totalColumns > 0) { this.adjustAvailableNodes(); adjusted = true; this.renderColGroups(); this.renderColumnHeaders(); this.renderRows(totalRows, rowsToRender, columnsToRender); if (!this.wtTable.isWorkingOnClone()) { workspaceWidth = this.instance.wtViewport.getWorkspaceWidth(); this.instance.wtViewport.containerWidth = null; } else { this.adjustColumnHeaderHeights(); } this.adjustColumnWidths(columnsToRender); } if (!adjusted) { this.adjustAvailableNodes(); } this.removeRedundantRows(rowsToRender); if (!this.wtTable.isWorkingOnClone()) { this.markOversizedRows(); this.instance.wtViewport.createVisibleCalculators(); this.instance.wtOverlays.applyToDOM(); this.instance.wtOverlays.refresh(false); if (workspaceWidth !== this.instance.wtViewport.getWorkspaceWidth()) { this.instance.wtViewport.containerWidth = null; var firstRendered = this.wtTable.getFirstRenderedColumn(); var lastRendered = this.wtTable.getLastRenderedColumn(); for (var i = firstRendered; i < lastRendered; i++) { var width = this.wtTable.getStretchedColumnWidth(i); var renderedIndex = this.columnFilter.sourceToRendered(i); this.COLGROUP.childNodes[renderedIndex + this.rowHeaderCount].style.width = width + 'px'; } } this.instance.getSetting('onDraw', true); } }; WalkontableTableRenderer.prototype.removeRedundantRows = function(renderedRowsCount) { while (this.wtTable.tbodyChildrenLength > renderedRowsCount) { this.TBODY.removeChild(this.TBODY.lastChild); this.wtTable.tbodyChildrenLength--; } }; WalkontableTableRenderer.prototype.renderRows = function(totalRows, rowsToRender, columnsToRender) { var lastTD, TR; var visibleRowIndex = 0; var sourceRowIndex = this.rowFilter.renderedToSource(visibleRowIndex); var isWorkingOnClone = this.wtTable.isWorkingOnClone(); while (sourceRowIndex < totalRows && sourceRowIndex >= 0) { if (visibleRowIndex > 1000) { throw new Error('Security brake: Too much TRs. Please define height for your table, which will enforce scrollbars.'); } if (rowsToRender !== void 0 && visibleRowIndex === rowsToRender) { break; } TR = this.getOrCreateTrForRow(visibleRowIndex, TR); this.renderRowHeaders(sourceRowIndex, TR); this.adjustColumns(TR, columnsToRender + this.rowHeaderCount); lastTD = this.renderCells(sourceRowIndex, TR, columnsToRender); if (!isWorkingOnClone) { this.resetOversizedRow(sourceRowIndex); } if (TR.firstChild) { var height = this.instance.wtTable.getRowHeight(sourceRowIndex); if (height) { TR.firstChild.style.height = height + 'px'; } else { TR.firstChild.style.height = ''; } } visibleRowIndex++; sourceRowIndex = this.rowFilter.renderedToSource(visibleRowIndex); } }; WalkontableTableRenderer.prototype.resetOversizedRow = function(sourceRow) { if (this.instance.wtViewport.oversizedRows && this.instance.wtViewport.oversizedRows[sourceRow]) { this.instance.wtViewport.oversizedRows[sourceRow] = void 0; } }; WalkontableTableRenderer.prototype.markOversizedRows = function() { var previousRowHeight, trInnerHeight, sourceRowIndex, currentTr; var rowCount = this.instance.wtTable.TBODY.childNodes.length; while (rowCount) { rowCount--; sourceRowIndex = this.instance.wtTable.rowFilter.renderedToSource(rowCount); previousRowHeight = this.instance.wtTable.getRowHeight(sourceRowIndex); currentTr = this.instance.wtTable.getTrForRow(sourceRowIndex); trInnerHeight = dom.innerHeight(currentTr) - 1; if ((!previousRowHeight && this.instance.wtSettings.settings.defaultRowHeight < trInnerHeight || previousRowHeight < trInnerHeight)) { this.instance.wtViewport.oversizedRows[sourceRowIndex] = trInnerHeight; } } }; WalkontableTableRenderer.prototype.adjustColumnHeaderHeights = function() { var columnHeaders = this.instance.getSetting('columnHeaders'), childs = this.instance.wtTable.THEAD.childNodes; for (var i = 0, columnHeadersCount = columnHeaders.length; i < columnHeadersCount; i++) { if (this.instance.wtViewport.oversizedColumnHeaders[i]) { if (childs[i].childNodes.length === 0) { return; } childs[i].childNodes[0].style.height = this.instance.wtViewport.oversizedColumnHeaders[i] + "px"; } } }; WalkontableTableRenderer.prototype.markIfOversizedColumnHeader = function(col) { var level = this.instance.getSetting('columnHeaders').length, defaultRowHeight = this.instance.wtSettings.settings.defaultRowHeight, sourceColIndex, previousColHeaderHeight, currentHeader, currentHeaderHeight; sourceColIndex = this.instance.wtTable.columnFilter.renderedToSource(col); while (level) { level--; previousColHeaderHeight = this.instance.wtTable.getColumnHeaderHeight(level); currentHeader = this.instance.wtTable.getColumnHeader(sourceColIndex, level); if (!currentHeader) { continue; } currentHeaderHeight = defaultRowHeight; if (!previousColHeaderHeight && defaultRowHeight < currentHeaderHeight || previousColHeaderHeight < currentHeaderHeight) { this.instance.wtViewport.oversizedColumnHeaders[level] = currentHeaderHeight; } } }; WalkontableTableRenderer.prototype.renderCells = function(sourceRowIndex, TR, columnsToRender) { var TD, sourceColIndex; for (var visibleColIndex = 0; visibleColIndex < columnsToRender; visibleColIndex++) { sourceColIndex = this.columnFilter.renderedToSource(visibleColIndex); if (visibleColIndex === 0) { TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(sourceColIndex)]; } else { TD = TD.nextSibling; } if (TD.nodeName == 'TH') { TD = this.utils.replaceThWithTd(TD, TR); } if (!dom.hasClass(TD, 'hide')) { TD.className = ''; } TD.removeAttribute('style'); this.instance.wtSettings.settings.cellRenderer(sourceRowIndex, sourceColIndex, TD); } return TD; }; WalkontableTableRenderer.prototype.adjustColumnWidths = function(columnsToRender) { var width, rowsCalculator = this.instance.wtViewport.rowsRenderCalculator, scrollbarCompensation = 0, sourceInstance = this.instance.cloneSource ? this.instance.cloneSource : this.instance, mainHolder = sourceInstance.wtTable.holder, trimmingContainer = dom.getTrimmingContainer(sourceInstance.wtTable.TABLE); if (mainHolder.offsetHeight < mainHolder.scrollHeight) { scrollbarCompensation = dom.getScrollbarWidth(); } this.instance.wtViewport.columnsRenderCalculator.refreshStretching(this.instance.wtViewport.getViewportWidth() - scrollbarCompensation); for (var renderedColIndex = 0; renderedColIndex < columnsToRender; renderedColIndex++) { width = this.wtTable.getStretchedColumnWidth(this.columnFilter.renderedToSource(renderedColIndex)); this.COLGROUP.childNodes[renderedColIndex + this.rowHeaderCount].style.width = width + 'px'; } }; WalkontableTableRenderer.prototype.appendToTbody = function(TR) { this.TBODY.appendChild(TR); this.wtTable.tbodyChildrenLength++; }; WalkontableTableRenderer.prototype.getOrCreateTrForRow = function(rowIndex, currentTr) { var TR; if (rowIndex >= this.wtTable.tbodyChildrenLength) { TR = this.createRow(); this.appendToTbody(TR); } else if (rowIndex === 0) { TR = this.TBODY.firstChild; } else { TR = currentTr.nextSibling; } return TR; }; WalkontableTableRenderer.prototype.createRow = function() { var TR = document.createElement('TR'); for (var visibleColIndex = 0; visibleColIndex < this.rowHeaderCount; visibleColIndex++) { TR.appendChild(document.createElement('TH')); } return TR; }; WalkontableTableRenderer.prototype.renderRowHeader = function(row, col, TH) { TH.className = ''; TH.removeAttribute('style'); this.rowHeaders[col](row, TH, col); }; WalkontableTableRenderer.prototype.renderRowHeaders = function(row, TR) { for (var TH = TR.firstChild, visibleColIndex = 0; visibleColIndex < this.rowHeaderCount; visibleColIndex++) { if (!TH) { TH = document.createElement('TH'); TR.appendChild(TH); } else if (TH.nodeName == 'TD') { TH = this.utils.replaceTdWithTh(TH, TR); } this.renderRowHeader(row, visibleColIndex, TH); TH = TH.nextSibling; } }; WalkontableTableRenderer.prototype.adjustAvailableNodes = function() { this.adjustColGroups(); this.adjustThead(); }; WalkontableTableRenderer.prototype.renderColumnHeaders = function() { if (!this.columnHeaderCount) { return; } var columnCount = this.wtTable.getRenderedColumnsCount(), TR, renderedColumnIndex; for (var i = 0; i < this.columnHeaderCount; i++) { TR = this.getTrForColumnHeaders(i); for (renderedColumnIndex = (-1) * this.rowHeaderCount; renderedColumnIndex < columnCount; renderedColumnIndex++) { var sourceCol = this.columnFilter.renderedToSource(renderedColumnIndex); this.renderColumnHeader(i, sourceCol, TR.childNodes[renderedColumnIndex + this.rowHeaderCount]); if (!this.wtTable.isWorkingOnClone()) { this.markIfOversizedColumnHeader(renderedColumnIndex); } } } }; WalkontableTableRenderer.prototype.adjustColGroups = function() { var columnCount = this.wtTable.getRenderedColumnsCount(); while (this.wtTable.colgroupChildrenLength < columnCount + this.rowHeaderCount) { this.COLGROUP.appendChild(document.createElement('COL')); this.wtTable.colgroupChildrenLength++; } while (this.wtTable.colgroupChildrenLength > columnCount + this.rowHeaderCount) { this.COLGROUP.removeChild(this.COLGROUP.lastChild); this.wtTable.colgroupChildrenLength--; } }; WalkontableTableRenderer.prototype.adjustThead = function() { var columnCount = this.wtTable.getRenderedColumnsCount(); var TR = this.THEAD.firstChild; if (this.columnHeaders.length) { for (var i = 0, columnHeadersLength = this.columnHeaders.length; i < columnHeadersLength; i++) { TR = this.THEAD.childNodes[i]; if (!TR) { TR = document.createElement('TR'); this.THEAD.appendChild(TR); } this.theadChildrenLength = TR.childNodes.length; while (this.theadChildrenLength < columnCount + this.rowHeaderCount) { TR.appendChild(document.createElement('TH')); this.theadChildrenLength++; } while (this.theadChildrenLength > columnCount + this.rowHeaderCount) { TR.removeChild(TR.lastChild); this.theadChildrenLength--; } } var theadChildrenLength = this.THEAD.childNodes.length; if (theadChildrenLength > this.columnHeaders.length) { for (var i = this.columnHeaders.length; i < theadChildrenLength; i++) { this.THEAD.removeChild(this.THEAD.lastChild); } } } else if (TR) { dom.empty(TR); } }; WalkontableTableRenderer.prototype.getTrForColumnHeaders = function(index) { var TR = this.THEAD.childNodes[index]; return TR; }; WalkontableTableRenderer.prototype.renderColumnHeader = function(row, col, TH) { TH.className = ''; TH.removeAttribute('style'); return this.columnHeaders[row](col, TH, row); }; WalkontableTableRenderer.prototype.renderColGroups = function() { for (var colIndex = 0; colIndex < this.wtTable.colgroupChildrenLength; colIndex++) { if (colIndex < this.rowHeaderCount) { dom.addClass(this.COLGROUP.childNodes[colIndex], 'rowHeader'); } else { dom.removeClass(this.COLGROUP.childNodes[colIndex], 'rowHeader'); } } }; WalkontableTableRenderer.prototype.adjustColumns = function(TR, desiredCount) { var count = TR.childNodes.length; while (count < desiredCount) { var TD = document.createElement('TD'); TR.appendChild(TD); count++; } while (count > desiredCount) { TR.removeChild(TR.lastChild); count--; } }; WalkontableTableRenderer.prototype.removeRedundantColumns = function(columnsToRender) { while (this.wtTable.tbodyChildrenLength > columnsToRender) { this.TBODY.removeChild(this.TBODY.lastChild); this.wtTable.tbodyChildrenLength--; } }; WalkontableTableRenderer.utils = {}; WalkontableTableRenderer.utils.replaceTdWithTh = function(TD, TR) { var TH; TH = document.createElement('TH'); TR.insertBefore(TH, TD); TR.removeChild(TD); return TH; }; WalkontableTableRenderer.utils.replaceThWithTd = function(TH, TR) { var TD = document.createElement('TD'); TR.insertBefore(TD, TH); TR.removeChild(TH); return TD; }; //# },{"./../../../dom.js":34}],24:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableViewport: {get: function() { return WalkontableViewport; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47__46__46__47_eventManager_46_js__, $__viewportColumnsCalculator_46_js__, $__viewportRowsCalculator_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47__46__46__47_eventManager_46_js__ = require("./../../../eventManager.js"), $___46__46__47__46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_eventManager_46_js__}).eventManager; var WalkontableViewportColumnsCalculator = ($__viewportColumnsCalculator_46_js__ = require("./viewportColumnsCalculator.js"), $__viewportColumnsCalculator_46_js__ && $__viewportColumnsCalculator_46_js__.__esModule && $__viewportColumnsCalculator_46_js__ || {default: $__viewportColumnsCalculator_46_js__}).WalkontableViewportColumnsCalculator; var WalkontableViewportRowsCalculator = ($__viewportRowsCalculator_46_js__ = require("./viewportRowsCalculator.js"), $__viewportRowsCalculator_46_js__ && $__viewportRowsCalculator_46_js__.__esModule && $__viewportRowsCalculator_46_js__ || {default: $__viewportRowsCalculator_46_js__}).WalkontableViewportRowsCalculator; ; window.WalkontableViewport = WalkontableViewport; function WalkontableViewport(instance) { this.instance = instance; this.oversizedRows = []; this.oversizedCols = []; this.oversizedColumnHeaders = []; var that = this; var eventManager = eventManagerObject(instance); eventManager.addEventListener(window, 'resize', function() { that.clientHeight = that.getWorkspaceHeight(); }); } WalkontableViewport.prototype.getWorkspaceHeight = function() { var trimmingContainer = this.instance.wtOverlays.topOverlay.trimmingContainer; if (trimmingContainer === window) { return document.documentElement.clientHeight; } else { var elemHeight = dom.outerHeight(trimmingContainer); var height = (elemHeight > 0 && trimmingContainer.clientHeight > 0) ? trimmingContainer.clientHeight : Infinity; return height; } }; WalkontableViewport.prototype.getWorkspaceWidth = function() { var width, totalColumns = this.instance.getSetting("totalColumns"), trimmingContainer = this.instance.wtOverlays.leftOverlay.trimmingContainer, overflow, stretchSetting = this.instance.getSetting('stretchH'); if (Handsontable.freezeOverlays) { width = Math.min(document.documentElement.offsetWidth - this.getWorkspaceOffset().left, document.documentElement.offsetWidth); } else { width = Math.min(this.getContainerFillWidth(), document.documentElement.offsetWidth - this.getWorkspaceOffset().left, document.documentElement.offsetWidth); } if (trimmingContainer === window && totalColumns > 0 && this.sumColumnWidths(0, totalColumns - 1) > width) { return document.documentElement.clientWidth; } if (trimmingContainer !== window) { overflow = dom.getStyle(this.instance.wtOverlays.leftOverlay.trimmingContainer, 'overflow'); if (overflow == "scroll" || overflow == "hidden" || overflow == "auto") { return Math.max(width, trimmingContainer.clientWidth); } } if (stretchSetting === 'none' || !stretchSetting) { return Math.max(width, dom.outerWidth(this.instance.wtTable.TABLE)); } else { return width; } }; WalkontableViewport.prototype.sumColumnWidths = function(from, length) { var sum = 0; while (from < length) { sum += this.instance.wtTable.getColumnWidth(from) || this.instance.wtSettings.defaultColumnWidth; from++; } return sum; }; WalkontableViewport.prototype.getContainerFillWidth = function() { if (this.containerWidth) { return this.containerWidth; } var mainContainer = this.instance.wtTable.holder, fillWidth, dummyElement; dummyElement = document.createElement("DIV"); dummyElement.style.width = "100%"; dummyElement.style.height = "1px"; mainContainer.appendChild(dummyElement); fillWidth = dummyElement.offsetWidth; this.containerWidth = fillWidth; mainContainer.removeChild(dummyElement); return fillWidth; }; WalkontableViewport.prototype.getWorkspaceOffset = function() { return dom.offset(this.instance.wtTable.TABLE); }; WalkontableViewport.prototype.getWorkspaceActualHeight = function() { return dom.outerHeight(this.instance.wtTable.TABLE); }; WalkontableViewport.prototype.getWorkspaceActualWidth = function() { return dom.outerWidth(this.instance.wtTable.TABLE) || dom.outerWidth(this.instance.wtTable.TBODY) || dom.outerWidth(this.instance.wtTable.THEAD); }; WalkontableViewport.prototype.getColumnHeaderHeight = function() { if (isNaN(this.columnHeaderHeight)) { this.columnHeaderHeight = dom.outerHeight(this.instance.wtTable.THEAD); } return this.columnHeaderHeight; }; WalkontableViewport.prototype.getViewportHeight = function() { var containerHeight = this.getWorkspaceHeight(); if (containerHeight === Infinity) { return containerHeight; } var columnHeaderHeight = this.getColumnHeaderHeight(); if (columnHeaderHeight > 0) { containerHeight -= columnHeaderHeight; } return containerHeight; }; WalkontableViewport.prototype.getRowHeaderWidth = function() { if (this.instance.cloneSource) { return this.instance.cloneSource.wtViewport.getRowHeaderWidth(); } if (isNaN(this.rowHeaderWidth)) { var rowHeaders = this.instance.getSetting('rowHeaders'); if (rowHeaders.length) { var TH = this.instance.wtTable.TABLE.querySelector('TH'); this.rowHeaderWidth = 0; for (var i = 0, ilen = rowHeaders.length; i < ilen; i++) { if (TH) { this.rowHeaderWidth += dom.outerWidth(TH); TH = TH.nextSibling; } else { this.rowHeaderWidth += 50; } } } else { this.rowHeaderWidth = 0; } } return this.rowHeaderWidth; }; WalkontableViewport.prototype.getViewportWidth = function() { var containerWidth = this.getWorkspaceWidth(), rowHeaderWidth; if (containerWidth === Infinity) { return containerWidth; } rowHeaderWidth = this.getRowHeaderWidth(); if (rowHeaderWidth > 0) { return containerWidth - rowHeaderWidth; } return containerWidth; }; WalkontableViewport.prototype.createRowsCalculator = function(visible) { this.rowHeaderWidth = NaN; var height; if (this.instance.wtSettings.settings.renderAllRows) { height = Infinity; } else { height = this.getViewportHeight(); } var pos = dom.getScrollTop(this.instance.wtOverlays.mainTableScrollableElement) - this.instance.wtOverlays.topOverlay.getTableParentOffset(); if (pos < 0) { pos = 0; } var fixedRowsTop = this.instance.getSetting('fixedRowsTop'); if (fixedRowsTop) { var fixedRowsHeight = this.instance.wtOverlays.topOverlay.sumCellSizes(0, fixedRowsTop); pos += fixedRowsHeight; height -= fixedRowsHeight; } var that = this; return new WalkontableViewportRowsCalculator(height, pos, this.instance.getSetting('totalRows'), function(sourceRow) { return that.instance.wtTable.getRowHeight(sourceRow); }, visible ? null : this.instance.wtSettings.settings.viewportRowCalculatorOverride, visible ? true : false); }; WalkontableViewport.prototype.createColumnsCalculator = function(visible) { this.columnHeaderHeight = NaN; var width = this.getViewportWidth(); var pos = this.instance.wtOverlays.leftOverlay.getScrollPosition() - this.instance.wtOverlays.topOverlay.getTableParentOffset(); if (pos < 0) { pos = 0; } var fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft'); if (fixedColumnsLeft) { var fixedColumnsWidth = this.instance.wtOverlays.leftOverlay.sumCellSizes(0, fixedColumnsLeft); pos += fixedColumnsWidth; width -= fixedColumnsWidth; } if (this.instance.wtTable.holder.clientWidth !== this.instance.wtTable.holder.offsetWidth) { width -= dom.getScrollbarWidth(); } var that = this; return new WalkontableViewportColumnsCalculator(width, pos, this.instance.getSetting('totalColumns'), function(sourceCol) { return that.instance.wtTable.getColumnWidth(sourceCol); }, visible ? null : this.instance.wtSettings.settings.viewportColumnCalculatorOverride, visible ? true : false, this.instance.getSetting('stretchH')); }; WalkontableViewport.prototype.createRenderCalculators = function(fastDraw) { if (fastDraw) { var proposedRowsVisibleCalculator = this.createRowsCalculator(true); var proposedColumnsVisibleCalculator = this.createColumnsCalculator(true); if (!(this.areAllProposedVisibleRowsAlreadyRendered(proposedRowsVisibleCalculator) && this.areAllProposedVisibleColumnsAlreadyRendered(proposedColumnsVisibleCalculator))) { fastDraw = false; } } if (!fastDraw) { this.rowsRenderCalculator = this.createRowsCalculator(); this.columnsRenderCalculator = this.createColumnsCalculator(); } this.rowsVisibleCalculator = null; this.columnsVisibleCalculator = null; return fastDraw; }; WalkontableViewport.prototype.createVisibleCalculators = function() { this.rowsVisibleCalculator = this.createRowsCalculator(true); this.columnsVisibleCalculator = this.createColumnsCalculator(true); }; WalkontableViewport.prototype.areAllProposedVisibleRowsAlreadyRendered = function(proposedRowsVisibleCalculator) { if (this.rowsVisibleCalculator) { if (proposedRowsVisibleCalculator.startRow < this.rowsRenderCalculator.startRow || (proposedRowsVisibleCalculator.startRow === this.rowsRenderCalculator.startRow && proposedRowsVisibleCalculator.startRow > 0)) { return false; } else if (proposedRowsVisibleCalculator.endRow > this.rowsRenderCalculator.endRow || (proposedRowsVisibleCalculator.endRow === this.rowsRenderCalculator.endRow && proposedRowsVisibleCalculator.endRow < this.instance.getSetting('totalRows') - 1)) { return false; } else { return true; } } return false; }; WalkontableViewport.prototype.areAllProposedVisibleColumnsAlreadyRendered = function(proposedColumnsVisibleCalculator) { if (this.columnsVisibleCalculator) { if (proposedColumnsVisibleCalculator.startColumn < this.columnsRenderCalculator.startColumn || (proposedColumnsVisibleCalculator.startColumn === this.columnsRenderCalculator.startColumn && proposedColumnsVisibleCalculator.startColumn > 0)) { return false; } else if (proposedColumnsVisibleCalculator.endColumn > this.columnsRenderCalculator.endColumn || (proposedColumnsVisibleCalculator.endColumn === this.columnsRenderCalculator.endColumn && proposedColumnsVisibleCalculator.endColumn < this.instance.getSetting('totalColumns') - 1)) { return false; } else { return true; } } return false; }; //# },{"./../../../dom.js":34,"./../../../eventManager.js":48,"./viewportColumnsCalculator.js":25,"./viewportRowsCalculator.js":26}],25:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableViewportColumnsCalculator: {get: function() { return WalkontableViewportColumnsCalculator; }}, __esModule: {value: true} }); ; window.WalkontableViewportColumnsCalculator = WalkontableViewportColumnsCalculator; function WalkontableViewportColumnsCalculator(width, scrollOffset, totalColumns, columnWidthFn, overrideFn, onlyFullyVisible, stretchH) { var _this = this, ratio = 1, sum = 0, needReverse = true, defaultColumnWidth = 50, startPositions = [], getColumnWidth, columnWidth, i; this.scrollOffset = scrollOffset; this.startColumn = null; this.endColumn = null; this.startPosition = null; this.count = 0; this.stretchAllRatio = 0; this.stretchLastWidth = 0; this.stretch = stretchH; this.totalTargetWidth = 0; this.needVerifyLastColumnWidth = true; this.stretchAllColumnsWidth = []; function getStretchedAllColumnWidth(column, baseWidth) { var sumRatioWidth = 0; if (!_this.stretchAllColumnsWidth[column]) { _this.stretchAllColumnsWidth[column] = Math.round(baseWidth * _this.stretchAllRatio); } if (_this.stretchAllColumnsWidth.length === totalColumns && _this.needVerifyLastColumnWidth) { _this.needVerifyLastColumnWidth = false; for (var i = 0; i < _this.stretchAllColumnsWidth.length; i++) { sumRatioWidth += _this.stretchAllColumnsWidth[i]; } if (sumRatioWidth != _this.totalTargetWidth) { _this.stretchAllColumnsWidth[_this.stretchAllColumnsWidth.length - 1] += _this.totalTargetWidth - sumRatioWidth; } } return _this.stretchAllColumnsWidth[column]; } function getStretchedLastColumnWidth(column, baseWidth) { if (column === totalColumns - 1) { return _this.stretchLastWidth; } return null; } getColumnWidth = function getColumnWidth(i) { var width = columnWidthFn(i); ratio = ratio || 1; if (width === undefined) { width = defaultColumnWidth; } return width; }; this.refreshStretching = function(totalWidth) { var sumAll = 0, columnWidth, remainingSize; for (var i = 0; i < totalColumns; i++) { columnWidth = getColumnWidth(i); sumAll += columnWidth; } this.totalTargetWidth = totalWidth; remainingSize = sumAll - totalWidth; if (this.stretch === 'all' && remainingSize < 0) { this.stretchAllRatio = totalWidth / sumAll; this.stretchAllColumnsWidth = []; this.needVerifyLastColumnWidth = true; } else if (this.stretch === 'last' && totalWidth !== Infinity) { this.stretchLastWidth = -remainingSize + getColumnWidth(totalColumns - 1); } }; this.getStretchedColumnWidth = function(column, baseWidth) { var result = null; if (this.stretch === 'all' && this.stretchAllRatio !== 0) { result = getStretchedAllColumnWidth(column, baseWidth); } else if (this.stretch === 'last' && this.stretchLastWidth !== 0) { result = getStretchedLastColumnWidth(column, baseWidth); } return result; }; for (i = 0; i < totalColumns; i++) { columnWidth = getColumnWidth(i); if (sum <= scrollOffset && !onlyFullyVisible) { this.startColumn = i; } if (sum >= scrollOffset && sum + columnWidth <= scrollOffset + width) { if (this.startColumn == null) { this.startColumn = i; } this.endColumn = i; } startPositions.push(sum); sum += columnWidth; if (!onlyFullyVisible) { this.endColumn = i; } if (sum >= scrollOffset + width) { needReverse = false; break; } } if (this.endColumn == totalColumns - 1 && needReverse) { this.startColumn = this.endColumn; while (this.startColumn > 0) { var viewportSum = startPositions[this.endColumn] + columnWidth - startPositions[this.startColumn - 1]; if (viewportSum <= width || !onlyFullyVisible) { this.startColumn--; } if (viewportSum > width) { break; } } } if (this.startColumn !== null && overrideFn) { overrideFn(this); } this.startPosition = startPositions[this.startColumn]; if (this.startPosition == void 0) { this.startPosition = null; } if (this.startColumn != null) { this.count = this.endColumn - this.startColumn + 1; } } //# },{}],26:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableViewportRowsCalculator: {get: function() { return WalkontableViewportRowsCalculator; }}, __esModule: {value: true} }); ; window.WalkontableViewportRowsCalculator = WalkontableViewportRowsCalculator; function WalkontableViewportRowsCalculator(height, scrollOffset, totalRows, rowHeightFn, overrideFn, onlyFullyVisible) { this.scrollOffset = scrollOffset; this.startRow = null; this.startPosition = null; this.endRow = null; this.count = 0; var sum = 0; var rowHeight; var needReverse = true; var defaultRowHeight = 23; var startPositions = []; for (var i = 0; i < totalRows; i++) { rowHeight = rowHeightFn(i); if (rowHeight === undefined) { rowHeight = defaultRowHeight; } if (sum <= scrollOffset && !onlyFullyVisible) { this.startRow = i; } if (sum >= scrollOffset && sum + rowHeight <= scrollOffset + height) { if (this.startRow == null) { this.startRow = i; } this.endRow = i; } startPositions.push(sum); sum += rowHeight; if (!onlyFullyVisible) { this.endRow = i; } if (sum >= scrollOffset + height) { needReverse = false; break; } } if (this.endRow == totalRows - 1 && needReverse) { this.startRow = this.endRow; while (this.startRow > 0) { var viewportSum = startPositions[this.endRow] + rowHeight - startPositions[this.startRow - 1]; if (viewportSum <= height || !onlyFullyVisible) { this.startRow--; } if (viewportSum >= height) { break; } } } if (this.startRow !== null && overrideFn) { overrideFn(this); } this.startPosition = startPositions[this.startRow]; if (this.startPosition == void 0) { this.startPosition = null; } if (this.startRow != null) { this.count = this.endRow - this.startRow + 1; } } //# },{}],27:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableCornerOverlay: {get: function() { return WalkontableCornerOverlay; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $___95_overlay_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var WalkontableOverlay = ($___95_overlay_46_js__ = require("./_overlay.js"), $___95_overlay_46_js__ && $___95_overlay_46_js__.__esModule && $___95_overlay_46_js__ || {default: $___95_overlay_46_js__}).WalkontableOverlay; ; window.WalkontableCornerOverlay = WalkontableCornerOverlay; function WalkontableCornerOverlay(instance) { this.instance = instance; this.type = 'corner'; this.init(); this.clone = this.makeClone('corner'); } WalkontableCornerOverlay.prototype = new WalkontableOverlay(); WalkontableCornerOverlay.prototype.resetFixedPosition = function() { if (!this.instance.wtTable.holder.parentNode) { return; } var elem = this.clone.wtTable.holder.parentNode, finalLeft, finalTop; if (this.trimmingContainer === window) { var box = this.instance.wtTable.hider.getBoundingClientRect(); var top = Math.ceil(box.top); var left = Math.ceil(box.left); var bottom = Math.ceil(box.bottom); var right = Math.ceil(box.right); if (left < 0 && (right - elem.offsetWidth) > 0) { finalLeft = -left + 'px'; } else { finalLeft = '0'; } if (top < 0 && (bottom - elem.offsetHeight) > 0) { finalTop = -top + "px"; } else { finalTop = "0"; } dom.setOverlayPosition(elem, finalLeft, finalTop); } var tableHeight = dom.outerHeight(this.clone.wtTable.TABLE); var tableWidth = dom.outerWidth(this.clone.wtTable.TABLE); elem.style.height = (tableHeight === 0 ? tableHeight : tableHeight + 4) + 'px'; elem.style.width = (tableWidth === 0 ? tableWidth : tableWidth + 4) + 'px'; }; //# },{"./../../../dom.js":34,"./_overlay.js":6}],28:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableLeftOverlay: {get: function() { return WalkontableLeftOverlay; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $___95_overlay_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var WalkontableOverlay = ($___95_overlay_46_js__ = require("./_overlay.js"), $___95_overlay_46_js__ && $___95_overlay_46_js__.__esModule && $___95_overlay_46_js__ || {default: $___95_overlay_46_js__}).WalkontableOverlay; ; window.WalkontableLeftOverlay = WalkontableLeftOverlay; function WalkontableLeftOverlay(instance) { this.instance = instance; this.type = 'horizontal'; this.offset = 0; this.init(); this.clone = this.makeClone('left'); } WalkontableLeftOverlay.prototype = new WalkontableOverlay(); WalkontableLeftOverlay.prototype.resetFixedPosition = function() { var finalLeft, finalTop; if (!this.instance.wtTable.holder.parentNode) { return; } var elem = this.clone.wtTable.holder.parentNode, scrollbarHeight = this.instance.wtTable.holder.clientHeight !== this.instance.wtTable.holder.offsetHeight ? dom.getScrollbarWidth() : 0, scrollbarWidth = this.instance.wtTable.holder.clientWidth !== this.instance.wtTable.holder.offsetWidth ? dom.getScrollbarWidth() : 0; if (this.instance.wtOverlays.leftOverlay.trimmingContainer !== window) { elem.style.height = this.instance.wtViewport.getWorkspaceHeight() - scrollbarHeight + 'px'; } else { var box = this.instance.wtTable.hider.getBoundingClientRect(); var left = Math.ceil(box.left); var right = Math.ceil(box.right); if (left < 0 && (right - elem.offsetWidth) > 0) { finalLeft = -left + 'px'; } else { finalLeft = '0'; } finalTop = this.instance.wtTable.hider.style.top; finalTop = finalTop === "" ? 0 : finalTop; dom.setOverlayPosition(elem, finalLeft, finalTop); } var tableWidth = dom.outerWidth(this.clone.wtTable.TABLE); var elemWidth = (tableWidth === 0 ? tableWidth : tableWidth + 4); elem.style.width = elemWidth + 'px'; this.clone.wtTable.holder.style.width = elemWidth + scrollbarWidth + 'px'; this.hideBorderOnInitialPosition(); }; WalkontableLeftOverlay.prototype.hideBorderOnInitialPosition = function() { if (this.instance.getSetting('fixedColumnsLeft') === 0 && this.instance.getSetting('rowHeaders').length > 0) { var masterParent = this.instance.wtTable.holder.parentNode; if (this.getScrollPosition() === 0) { dom.removeClass(masterParent, 'innerBorderLeft'); } else { dom.addClass(masterParent, 'innerBorderLeft'); } } }; WalkontableLeftOverlay.prototype.refresh = function(fastDraw) { this.applyToDOM(); WalkontableOverlay.prototype.refresh.call(this, fastDraw); }; WalkontableLeftOverlay.prototype.getScrollPosition = function() { return dom.getScrollLeft(this.mainTableScrollableElement); }; WalkontableLeftOverlay.prototype.setScrollPosition = function(pos) { if (this.mainTableScrollableElement === window) { window.scrollTo(pos, dom.getWindowScrollTop()); } else { this.mainTableScrollableElement.scrollLeft = pos; } }; WalkontableLeftOverlay.prototype.onScroll = function() { this.instance.getSetting('onScrollHorizontally'); }; WalkontableLeftOverlay.prototype.sumCellSizes = function(from, length) { var sum = 0, defaultColumnWidth = this.instance.wtSettings.defaultColumnWidth; while (from < length) { sum += this.instance.wtTable.getStretchedColumnWidth(from) || defaultColumnWidth; from++; } return sum; }; WalkontableLeftOverlay.prototype.applyToDOM = function() { var total = this.instance.getSetting('totalColumns'), headerSize = this.instance.wtViewport.getRowHeaderWidth(), cloneHolder = this.clone.wtTable.holder, cloneHider = this.clone.wtTable.hider, masterHider = this.hider, cloneHolderParent = cloneHolder.parentNode, scrollbarWidth = dom.getScrollbarWidth(true); masterHider.style.width = headerSize + this.sumCellSizes(0, total) + 'px'; cloneHolder.style.width = parseInt(cloneHolderParent.style.width, 10) + scrollbarWidth + 'px'; cloneHider.style.height = masterHider.style.height; cloneHolder.style.height = cloneHolderParent.style.height; if (typeof this.instance.wtViewport.columnsRenderCalculator.startPosition === 'number') { this.spreader.style.left = this.instance.wtViewport.columnsRenderCalculator.startPosition + 'px'; } else if (total === 0) { this.spreader.style.left = '0'; } else { throw new Error('Incorrect value of the columnsRenderCalculator'); } this.spreader.style.right = ''; this.syncOverlayOffset(); }; WalkontableLeftOverlay.prototype.syncOverlayOffset = function() { if (typeof this.instance.wtViewport.rowsRenderCalculator.startPosition === 'number') { this.clone.wtTable.spreader.style.top = this.instance.wtViewport.rowsRenderCalculator.startPosition + 'px'; } else { this.clone.wtTable.spreader.style.top = ''; } }; WalkontableLeftOverlay.prototype.scrollTo = function(sourceCol, beyondRendered) { var newX = this.getTableParentOffset(), sourceInstance = this.instance.cloneSource ? this.instance.cloneSource : this.instance, mainHolder = sourceInstance.wtTable.holder, scrollbarCompensation = 0; if (beyondRendered && mainHolder.offsetWidth !== mainHolder.clientWidth) { scrollbarCompensation = dom.getScrollbarWidth(); } if (beyondRendered) { newX += this.sumCellSizes(0, sourceCol + 1); newX -= this.instance.wtViewport.getViewportWidth(); } else { var fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft'); newX += this.sumCellSizes(fixedColumnsLeft, sourceCol); } newX += scrollbarCompensation; this.setScrollPosition(newX); }; WalkontableLeftOverlay.prototype.getTableParentOffset = function() { if (this.trimmingContainer === window) { return this.instance.wtTable.holderOffset.left; } else { return 0; } }; //# },{"./../../../dom.js":34,"./_overlay.js":6}],29:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { WalkontableTopOverlay: {get: function() { return WalkontableTopOverlay; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47__46__46__47_dom_46_js__, $___95_overlay_46_js__; var dom = ($___46__46__47__46__46__47__46__46__47_dom_46_js__ = require("./../../../dom.js"), $___46__46__47__46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47__46__46__47_dom_46_js__}); var WalkontableOverlay = ($___95_overlay_46_js__ = require("./_overlay.js"), $___95_overlay_46_js__ && $___95_overlay_46_js__.__esModule && $___95_overlay_46_js__ || {default: $___95_overlay_46_js__}).WalkontableOverlay; ; window.WalkontableTopOverlay = WalkontableTopOverlay; function WalkontableTopOverlay(instance) { this.instance = instance; this.type = 'vertical'; this.init(); this.clone = this.makeClone('top'); } WalkontableTopOverlay.prototype = new WalkontableOverlay(); WalkontableTopOverlay.prototype.resetFixedPosition = function() { var finalLeft, finalTop; if (!this.instance.wtTable.holder.parentNode) { return; } var elem = this.clone.wtTable.holder.parentNode, scrollbarWidth = this.instance.wtTable.holder.clientWidth !== this.instance.wtTable.holder.offsetWidth ? dom.getScrollbarWidth() : 0; if (this.instance.wtOverlays.leftOverlay.trimmingContainer !== window) { elem.style.width = this.instance.wtViewport.getWorkspaceWidth() - scrollbarWidth + 'px'; } else { var box = this.instance.wtTable.hider.getBoundingClientRect(); var top = Math.ceil(box.top); var bottom = Math.ceil(box.bottom); finalLeft = this.instance.wtTable.hider.style.left; finalLeft = finalLeft === "" ? 0 : finalLeft; if (top < 0 && (bottom - elem.offsetHeight) > 0) { finalTop = -top + "px"; } else { finalTop = "0"; } dom.setOverlayPosition(elem, finalLeft, finalTop); } this.clone.wtTable.holder.style.width = elem.style.width; var tableHeight = dom.outerHeight(this.clone.wtTable.TABLE); elem.style.height = (tableHeight === 0 ? tableHeight : tableHeight + 4) + 'px'; this.hideBorderOnInitialPosition(); }; WalkontableTopOverlay.prototype.hideBorderOnInitialPosition = function() { if (this.instance.getSetting('fixedRowsTop') === 0 && this.instance.getSetting('columnHeaders').length > 0) { var masterParent = this.instance.wtTable.holder.parentNode; if (this.getScrollPosition() === 0) { dom.removeClass(masterParent, 'innerBorderTop'); } else { dom.addClass(masterParent, 'innerBorderTop'); } } if (this.instance.getSetting('rowHeaders').length === 0) { var secondHeaderCell = this.clone.wtTable.THEAD.querySelector('th:nth-of-type(2)'); if (secondHeaderCell) { secondHeaderCell.style['border-left-width'] = 0; } } }; WalkontableTopOverlay.prototype.getScrollPosition = function() { return dom.getScrollTop(this.mainTableScrollableElement); }; WalkontableTopOverlay.prototype.setScrollPosition = function(pos) { if (this.mainTableScrollableElement === window) { window.scrollTo(dom.getWindowScrollLeft(), pos); } else { this.mainTableScrollableElement.scrollTop = pos; } }; WalkontableTopOverlay.prototype.onScroll = function() { this.instance.getSetting('onScrollVertically'); }; WalkontableTopOverlay.prototype.sumCellSizes = function(from, length) { var sum = 0, defaultRowHeight = this.instance.wtSettings.settings.defaultRowHeight; while (from < length) { sum += this.instance.wtTable.getRowHeight(from) || defaultRowHeight; from++; } return sum; }; WalkontableTopOverlay.prototype.refresh = function(fastDraw) { this.applyToDOM(); WalkontableOverlay.prototype.refresh.call(this, fastDraw); }; WalkontableTopOverlay.prototype.applyToDOM = function() { var total = this.instance.getSetting('totalRows'); var headerSize = this.instance.wtViewport.getColumnHeaderHeight(); var scrollbarWidth = dom.getScrollbarWidth(true); var totalEstimatedHeight = headerSize + this.sumCellSizes(0, total) + 1 + 'px'; this.hider.style.height = totalEstimatedHeight; this.clone.wtTable.hider.style.width = this.hider.style.width; this.clone.wtTable.holder.style.width = this.clone.wtTable.holder.parentNode.style.width; this.clone.wtTable.holder.style.height = parseInt(this.clone.wtTable.holder.parentNode.style.height, 10) + scrollbarWidth + 'px'; if (typeof this.instance.wtViewport.rowsRenderCalculator.startPosition === 'number') { this.spreader.style.top = this.instance.wtViewport.rowsRenderCalculator.startPosition + 'px'; } else if (total === 0) { this.spreader.style.top = '0'; } else { throw new Error("Incorrect value of the rowsRenderCalculator"); } this.spreader.style.bottom = ''; this.syncOverlayOffset(); }; WalkontableTopOverlay.prototype.syncOverlayOffset = function() { if (typeof this.instance.wtViewport.columnsRenderCalculator.startPosition === 'number') { this.clone.wtTable.spreader.style.left = this.instance.wtViewport.columnsRenderCalculator.startPosition + 'px'; } else { this.clone.wtTable.spreader.style.left = ''; } }; WalkontableTopOverlay.prototype.scrollTo = function(sourceRow, bottomEdge) { var newY = this.getTableParentOffset(), sourceInstance = this.instance.cloneSource ? this.instance.cloneSource : this.instance, mainHolder = sourceInstance.wtTable.holder, scrollbarCompensation = 0; if (bottomEdge && mainHolder.offsetHeight !== mainHolder.clientHeight) { scrollbarCompensation = dom.getScrollbarWidth(); } if (bottomEdge) { newY += this.sumCellSizes(0, sourceRow + 1); newY -= this.instance.wtViewport.getViewportHeight(); newY += 1; } else { var fixedRowsTop = this.instance.getSetting('fixedRowsTop'); newY += this.sumCellSizes(fixedRowsTop, sourceRow); } newY += scrollbarCompensation; this.setScrollPosition(newY); }; WalkontableTopOverlay.prototype.getTableParentOffset = function() { if (this.mainTableScrollableElement === window) { return this.instance.wtTable.holderOffset.top; } else { return 0; } }; //# },{"./../../../dom.js":34,"./_overlay.js":6}],30:[function(require,module,exports){ "use strict"; var $__shims_47_array_46_filter_46_js__, $__shims_47_array_46_indexOf_46_js__, $__shims_47_array_46_isArray_46_js__, $__shims_47_object_46_keys_46_js__, $__shims_47_classes_46_js__, $__shims_47_weakmap_46_js__, $__pluginHooks_46_js__, $__core_46_js__, $__renderers_47__95_cellDecorator_46_js__, $__cellTypes_46_js__, $___46__46__47_plugins_47_jqueryHandsontable_46_js__; var version = Handsontable.version; window.Handsontable = function(rootElement, userSettings) { var instance = new Handsontable.Core(rootElement, userSettings || {}); instance.init(); return instance; }; Handsontable.version = version; ($__shims_47_array_46_filter_46_js__ = require("./shims/array.filter.js"), $__shims_47_array_46_filter_46_js__ && $__shims_47_array_46_filter_46_js__.__esModule && $__shims_47_array_46_filter_46_js__ || {default: $__shims_47_array_46_filter_46_js__}); ($__shims_47_array_46_indexOf_46_js__ = require("./shims/array.indexOf.js"), $__shims_47_array_46_indexOf_46_js__ && $__shims_47_array_46_indexOf_46_js__.__esModule && $__shims_47_array_46_indexOf_46_js__ || {default: $__shims_47_array_46_indexOf_46_js__}); ($__shims_47_array_46_isArray_46_js__ = require("./shims/array.isArray.js"), $__shims_47_array_46_isArray_46_js__ && $__shims_47_array_46_isArray_46_js__.__esModule && $__shims_47_array_46_isArray_46_js__ || {default: $__shims_47_array_46_isArray_46_js__}); ($__shims_47_object_46_keys_46_js__ = require("./shims/object.keys.js"), $__shims_47_object_46_keys_46_js__ && $__shims_47_object_46_keys_46_js__.__esModule && $__shims_47_object_46_keys_46_js__ || {default: $__shims_47_object_46_keys_46_js__}); ($__shims_47_classes_46_js__ = require("./shims/classes.js"), $__shims_47_classes_46_js__ && $__shims_47_classes_46_js__.__esModule && $__shims_47_classes_46_js__ || {default: $__shims_47_classes_46_js__}); ($__shims_47_weakmap_46_js__ = require("./shims/weakmap.js"), $__shims_47_weakmap_46_js__ && $__shims_47_weakmap_46_js__.__esModule && $__shims_47_weakmap_46_js__ || {default: $__shims_47_weakmap_46_js__}); Handsontable.plugins = {}; var PluginHook = ($__pluginHooks_46_js__ = require("./pluginHooks.js"), $__pluginHooks_46_js__ && $__pluginHooks_46_js__.__esModule && $__pluginHooks_46_js__ || {default: $__pluginHooks_46_js__}).PluginHook; if (!Handsontable.hooks) { Handsontable.hooks = new PluginHook(); } ($__core_46_js__ = require("./core.js"), $__core_46_js__ && $__core_46_js__.__esModule && $__core_46_js__ || {default: $__core_46_js__}); ($__renderers_47__95_cellDecorator_46_js__ = require("./renderers/_cellDecorator.js"), $__renderers_47__95_cellDecorator_46_js__ && $__renderers_47__95_cellDecorator_46_js__.__esModule && $__renderers_47__95_cellDecorator_46_js__ || {default: $__renderers_47__95_cellDecorator_46_js__}); ($__cellTypes_46_js__ = require("./cellTypes.js"), $__cellTypes_46_js__ && $__cellTypes_46_js__.__esModule && $__cellTypes_46_js__ || {default: $__cellTypes_46_js__}); ($___46__46__47_plugins_47_jqueryHandsontable_46_js__ = require("./../plugins/jqueryHandsontable.js"), $___46__46__47_plugins_47_jqueryHandsontable_46_js__ && $___46__46__47_plugins_47_jqueryHandsontable_46_js__.__esModule && $___46__46__47_plugins_47_jqueryHandsontable_46_js__ || {default: $___46__46__47_plugins_47_jqueryHandsontable_46_js__}); //# },{"./../plugins/jqueryHandsontable.js":1,"./cellTypes.js":31,"./core.js":32,"./pluginHooks.js":51,"./renderers/_cellDecorator.js":77,"./shims/array.filter.js":84,"./shims/array.indexOf.js":85,"./shims/array.isArray.js":86,"./shims/classes.js":87,"./shims/object.keys.js":88,"./shims/weakmap.js":89}],31:[function(require,module,exports){ "use strict"; var $__helpers_46_js__, $__editors_46_js__, $__renderers_46_js__, $__editors_47_autocompleteEditor_46_js__, $__editors_47_checkboxEditor_46_js__, $__editors_47_dateEditor_46_js__, $__editors_47_dropdownEditor_46_js__, $__editors_47_handsontableEditor_46_js__, $__editors_47_mobileTextEditor_46_js__, $__editors_47_numericEditor_46_js__, $__editors_47_passwordEditor_46_js__, $__editors_47_selectEditor_46_js__, $__editors_47_textEditor_46_js__, $__renderers_47_autocompleteRenderer_46_js__, $__renderers_47_checkboxRenderer_46_js__, $__renderers_47_htmlRenderer_46_js__, $__renderers_47_numericRenderer_46_js__, $__renderers_47_passwordRenderer_46_js__, $__renderers_47_textRenderer_46_js__, $__validators_47_autocompleteValidator_46_js__, $__validators_47_dateValidator_46_js__, $__validators_47_numericValidator_46_js__; var helper = ($__helpers_46_js__ = require("./helpers.js"), $__helpers_46_js__ && $__helpers_46_js__.__esModule && $__helpers_46_js__ || {default: $__helpers_46_js__}); var getEditorConstructor = ($__editors_46_js__ = require("./editors.js"), $__editors_46_js__ && $__editors_46_js__.__esModule && $__editors_46_js__ || {default: $__editors_46_js__}).getEditorConstructor; var getRenderer = ($__renderers_46_js__ = require("./renderers.js"), $__renderers_46_js__ && $__renderers_46_js__.__esModule && $__renderers_46_js__ || {default: $__renderers_46_js__}).getRenderer; var AutocompleteEditor = ($__editors_47_autocompleteEditor_46_js__ = require("./editors/autocompleteEditor.js"), $__editors_47_autocompleteEditor_46_js__ && $__editors_47_autocompleteEditor_46_js__.__esModule && $__editors_47_autocompleteEditor_46_js__ || {default: $__editors_47_autocompleteEditor_46_js__}).AutocompleteEditor; var CheckboxEditor = ($__editors_47_checkboxEditor_46_js__ = require("./editors/checkboxEditor.js"), $__editors_47_checkboxEditor_46_js__ && $__editors_47_checkboxEditor_46_js__.__esModule && $__editors_47_checkboxEditor_46_js__ || {default: $__editors_47_checkboxEditor_46_js__}).CheckboxEditor; var DateEditor = ($__editors_47_dateEditor_46_js__ = require("./editors/dateEditor.js"), $__editors_47_dateEditor_46_js__ && $__editors_47_dateEditor_46_js__.__esModule && $__editors_47_dateEditor_46_js__ || {default: $__editors_47_dateEditor_46_js__}).DateEditor; var DropdownEditor = ($__editors_47_dropdownEditor_46_js__ = require("./editors/dropdownEditor.js"), $__editors_47_dropdownEditor_46_js__ && $__editors_47_dropdownEditor_46_js__.__esModule && $__editors_47_dropdownEditor_46_js__ || {default: $__editors_47_dropdownEditor_46_js__}).DropdownEditor; var HandsontableEditor = ($__editors_47_handsontableEditor_46_js__ = require("./editors/handsontableEditor.js"), $__editors_47_handsontableEditor_46_js__ && $__editors_47_handsontableEditor_46_js__.__esModule && $__editors_47_handsontableEditor_46_js__ || {default: $__editors_47_handsontableEditor_46_js__}).HandsontableEditor; var MobileTextEditor = ($__editors_47_mobileTextEditor_46_js__ = require("./editors/mobileTextEditor.js"), $__editors_47_mobileTextEditor_46_js__ && $__editors_47_mobileTextEditor_46_js__.__esModule && $__editors_47_mobileTextEditor_46_js__ || {default: $__editors_47_mobileTextEditor_46_js__}).MobileTextEditor; var NumericEditor = ($__editors_47_numericEditor_46_js__ = require("./editors/numericEditor.js"), $__editors_47_numericEditor_46_js__ && $__editors_47_numericEditor_46_js__.__esModule && $__editors_47_numericEditor_46_js__ || {default: $__editors_47_numericEditor_46_js__}).NumericEditor; var PasswordEditor = ($__editors_47_passwordEditor_46_js__ = require("./editors/passwordEditor.js"), $__editors_47_passwordEditor_46_js__ && $__editors_47_passwordEditor_46_js__.__esModule && $__editors_47_passwordEditor_46_js__ || {default: $__editors_47_passwordEditor_46_js__}).PasswordEditor; var SelectEditor = ($__editors_47_selectEditor_46_js__ = require("./editors/selectEditor.js"), $__editors_47_selectEditor_46_js__ && $__editors_47_selectEditor_46_js__.__esModule && $__editors_47_selectEditor_46_js__ || {default: $__editors_47_selectEditor_46_js__}).SelectEditor; var TextEditor = ($__editors_47_textEditor_46_js__ = require("./editors/textEditor.js"), $__editors_47_textEditor_46_js__ && $__editors_47_textEditor_46_js__.__esModule && $__editors_47_textEditor_46_js__ || {default: $__editors_47_textEditor_46_js__}).TextEditor; var AutocompleteRenderer = ($__renderers_47_autocompleteRenderer_46_js__ = require("./renderers/autocompleteRenderer.js"), $__renderers_47_autocompleteRenderer_46_js__ && $__renderers_47_autocompleteRenderer_46_js__.__esModule && $__renderers_47_autocompleteRenderer_46_js__ || {default: $__renderers_47_autocompleteRenderer_46_js__}).AutocompleteRenderer; var CheckboxRenderer = ($__renderers_47_checkboxRenderer_46_js__ = require("./renderers/checkboxRenderer.js"), $__renderers_47_checkboxRenderer_46_js__ && $__renderers_47_checkboxRenderer_46_js__.__esModule && $__renderers_47_checkboxRenderer_46_js__ || {default: $__renderers_47_checkboxRenderer_46_js__}).CheckboxRenderer; var HtmlRenderer = ($__renderers_47_htmlRenderer_46_js__ = require("./renderers/htmlRenderer.js"), $__renderers_47_htmlRenderer_46_js__ && $__renderers_47_htmlRenderer_46_js__.__esModule && $__renderers_47_htmlRenderer_46_js__ || {default: $__renderers_47_htmlRenderer_46_js__}).HtmlRenderer; var NumericRenderer = ($__renderers_47_numericRenderer_46_js__ = require("./renderers/numericRenderer.js"), $__renderers_47_numericRenderer_46_js__ && $__renderers_47_numericRenderer_46_js__.__esModule && $__renderers_47_numericRenderer_46_js__ || {default: $__renderers_47_numericRenderer_46_js__}).NumericRenderer; var PasswordRenderer = ($__renderers_47_passwordRenderer_46_js__ = require("./renderers/passwordRenderer.js"), $__renderers_47_passwordRenderer_46_js__ && $__renderers_47_passwordRenderer_46_js__.__esModule && $__renderers_47_passwordRenderer_46_js__ || {default: $__renderers_47_passwordRenderer_46_js__}).PasswordRenderer; var TextRenderer = ($__renderers_47_textRenderer_46_js__ = require("./renderers/textRenderer.js"), $__renderers_47_textRenderer_46_js__ && $__renderers_47_textRenderer_46_js__.__esModule && $__renderers_47_textRenderer_46_js__ || {default: $__renderers_47_textRenderer_46_js__}).TextRenderer; var AutocompleteValidator = ($__validators_47_autocompleteValidator_46_js__ = require("./validators/autocompleteValidator.js"), $__validators_47_autocompleteValidator_46_js__ && $__validators_47_autocompleteValidator_46_js__.__esModule && $__validators_47_autocompleteValidator_46_js__ || {default: $__validators_47_autocompleteValidator_46_js__}).AutocompleteValidator; var DateValidator = ($__validators_47_dateValidator_46_js__ = require("./validators/dateValidator.js"), $__validators_47_dateValidator_46_js__ && $__validators_47_dateValidator_46_js__.__esModule && $__validators_47_dateValidator_46_js__ || {default: $__validators_47_dateValidator_46_js__}).DateValidator; var NumericValidator = ($__validators_47_numericValidator_46_js__ = require("./validators/numericValidator.js"), $__validators_47_numericValidator_46_js__ && $__validators_47_numericValidator_46_js__.__esModule && $__validators_47_numericValidator_46_js__ || {default: $__validators_47_numericValidator_46_js__}).NumericValidator; Handsontable.mobileBrowser = helper.isMobileBrowser(); Handsontable.AutocompleteCell = { editor: getEditorConstructor('autocomplete'), renderer: getRenderer('autocomplete'), validator: Handsontable.AutocompleteValidator }; Handsontable.CheckboxCell = { editor: getEditorConstructor('checkbox'), renderer: getRenderer('checkbox') }; Handsontable.TextCell = { editor: Handsontable.mobileBrowser ? getEditorConstructor('mobile') : getEditorConstructor('text'), renderer: getRenderer('text') }; Handsontable.NumericCell = { editor: getEditorConstructor('numeric'), renderer: getRenderer('numeric'), validator: Handsontable.NumericValidator, dataType: 'number' }; Handsontable.DateCell = { editor: getEditorConstructor('date'), validator: Handsontable.DateValidator, renderer: getRenderer('autocomplete') }; Handsontable.HandsontableCell = { editor: getEditorConstructor('handsontable'), renderer: getRenderer('autocomplete') }; Handsontable.PasswordCell = { editor: getEditorConstructor('password'), renderer: getRenderer('password'), copyable: false }; Handsontable.DropdownCell = { editor: getEditorConstructor('dropdown'), renderer: getRenderer('autocomplete'), validator: Handsontable.AutocompleteValidator }; Handsontable.cellTypes = { text: Handsontable.TextCell, date: Handsontable.DateCell, numeric: Handsontable.NumericCell, checkbox: Handsontable.CheckboxCell, autocomplete: Handsontable.AutocompleteCell, handsontable: Handsontable.HandsontableCell, password: Handsontable.PasswordCell, dropdown: Handsontable.DropdownCell }; Handsontable.cellLookup = {validator: { numeric: Handsontable.NumericValidator, autocomplete: Handsontable.AutocompleteValidator }}; //# },{"./editors.js":36,"./editors/autocompleteEditor.js":38,"./editors/checkboxEditor.js":39,"./editors/dateEditor.js":40,"./editors/dropdownEditor.js":41,"./editors/handsontableEditor.js":42,"./editors/mobileTextEditor.js":43,"./editors/numericEditor.js":44,"./editors/passwordEditor.js":45,"./editors/selectEditor.js":46,"./editors/textEditor.js":47,"./helpers.js":49,"./renderers.js":76,"./renderers/autocompleteRenderer.js":78,"./renderers/checkboxRenderer.js":79,"./renderers/htmlRenderer.js":80,"./renderers/numericRenderer.js":81,"./renderers/passwordRenderer.js":82,"./renderers/textRenderer.js":83,"./validators/autocompleteValidator.js":91,"./validators/dateValidator.js":92,"./validators/numericValidator.js":93}],32:[function(require,module,exports){ "use strict"; var $__dom_46_js__, $__helpers_46_js__, $__numeral__, $__dataMap_46_js__, $__editorManager_46_js__, $__eventManager_46_js__, $__plugins_46_js__, $__renderers_46_js__, $__pluginHooks_46_js__, $__tableView_46_js__, $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__, $__3rdparty_47_walkontable_47_src_47_cellRange_46_js__, $__3rdparty_47_walkontable_47_src_47_selection_46_js__; var dom = ($__dom_46_js__ = require("./dom.js"), $__dom_46_js__ && $__dom_46_js__.__esModule && $__dom_46_js__ || {default: $__dom_46_js__}); var helper = ($__helpers_46_js__ = require("./helpers.js"), $__helpers_46_js__ && $__helpers_46_js__.__esModule && $__helpers_46_js__ || {default: $__helpers_46_js__}); var numeral = ($__numeral__ = require("numeral"), $__numeral__ && $__numeral__.__esModule && $__numeral__ || {default: $__numeral__}).default; var DataMap = ($__dataMap_46_js__ = require("./dataMap.js"), $__dataMap_46_js__ && $__dataMap_46_js__.__esModule && $__dataMap_46_js__ || {default: $__dataMap_46_js__}).DataMap; var EditorManager = ($__editorManager_46_js__ = require("./editorManager.js"), $__editorManager_46_js__ && $__editorManager_46_js__.__esModule && $__editorManager_46_js__ || {default: $__editorManager_46_js__}).EditorManager; var eventManagerObject = ($__eventManager_46_js__ = require("./eventManager.js"), $__eventManager_46_js__ && $__eventManager_46_js__.__esModule && $__eventManager_46_js__ || {default: $__eventManager_46_js__}).eventManager; var getPlugin = ($__plugins_46_js__ = require("./plugins.js"), $__plugins_46_js__ && $__plugins_46_js__.__esModule && $__plugins_46_js__ || {default: $__plugins_46_js__}).getPlugin; var getRenderer = ($__renderers_46_js__ = require("./renderers.js"), $__renderers_46_js__ && $__renderers_46_js__.__esModule && $__renderers_46_js__ || {default: $__renderers_46_js__}).getRenderer; var PluginHook = ($__pluginHooks_46_js__ = require("./pluginHooks.js"), $__pluginHooks_46_js__ && $__pluginHooks_46_js__.__esModule && $__pluginHooks_46_js__ || {default: $__pluginHooks_46_js__}).PluginHook; var TableView = ($__tableView_46_js__ = require("./tableView.js"), $__tableView_46_js__ && $__tableView_46_js__.__esModule && $__tableView_46_js__ || {default: $__tableView_46_js__}).TableView; var WalkontableCellCoords = ($__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ = require("./3rdparty/walkontable/src/cellCoords.js"), $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ && $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__.__esModule && $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ || {default: $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__}).WalkontableCellCoords; var WalkontableCellRange = ($__3rdparty_47_walkontable_47_src_47_cellRange_46_js__ = require("./3rdparty/walkontable/src/cellRange.js"), $__3rdparty_47_walkontable_47_src_47_cellRange_46_js__ && $__3rdparty_47_walkontable_47_src_47_cellRange_46_js__.__esModule && $__3rdparty_47_walkontable_47_src_47_cellRange_46_js__ || {default: $__3rdparty_47_walkontable_47_src_47_cellRange_46_js__}).WalkontableCellRange; var WalkontableSelection = ($__3rdparty_47_walkontable_47_src_47_selection_46_js__ = require("./3rdparty/walkontable/src/selection.js"), $__3rdparty_47_walkontable_47_src_47_selection_46_js__ && $__3rdparty_47_walkontable_47_src_47_selection_46_js__.__esModule && $__3rdparty_47_walkontable_47_src_47_selection_46_js__ || {default: $__3rdparty_47_walkontable_47_src_47_selection_46_js__}).WalkontableSelection; Handsontable.activeGuid = null; Handsontable.Core = function Core(rootElement, userSettings) { var priv, datamap, grid, selection, editorManager, instance = this, GridSettings = function() {}, eventManager = eventManagerObject(instance); helper.extend(GridSettings.prototype, DefaultSettings.prototype); helper.extend(GridSettings.prototype, userSettings); helper.extend(GridSettings.prototype, expandType(userSettings)); this.rootElement = rootElement; this.isHotTableEnv = dom.isChildOfWebComponentTable(this.rootElement); Handsontable.eventManager.isHotTableEnv = this.isHotTableEnv; this.container = document.createElement('DIV'); rootElement.insertBefore(this.container, rootElement.firstChild); this.guid = 'ht_' + helper.randomString(); if (!this.rootElement.id || this.rootElement.id.substring(0, 3) === "ht_") { this.rootElement.id = this.guid; } priv = { cellSettings: [], columnSettings: [], columnsSettingConflicts: ['data', 'width'], settings: new GridSettings(), selRange: null, isPopulated: null, scrollable: null, firstRun: true }; grid = { alter: function(action, index, amount, source, keepEmptyRows) { var delta; amount = amount || 1; switch (action) { case "insert_row": delta = datamap.createRow(index, amount); if (delta) { if (selection.isSelected() && priv.selRange.from.row >= index) { priv.selRange.from.row = priv.selRange.from.row + delta; selection.transformEnd(delta, 0); } else { selection.refreshBorders(); } } break; case "insert_col": delta = datamap.createCol(index, amount); if (delta) { if (Array.isArray(instance.getSettings().colHeaders)) { var spliceArray = [index, 0]; spliceArray.length += delta; Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArray); } if (selection.isSelected() && priv.selRange.from.col >= index) { priv.selRange.from.col = priv.selRange.from.col + delta; selection.transformEnd(0, delta); } else { selection.refreshBorders(); } } break; case "remove_row": index = instance.runHooks('modifyCol', index); datamap.removeRow(index, amount); priv.cellSettings.splice(index, amount); var fixedRowsTop = instance.getSettings().fixedRowsTop; if (fixedRowsTop >= index + 1) { instance.getSettings().fixedRowsTop -= Math.min(amount, fixedRowsTop - index); } grid.adjustRowsAndCols(); selection.refreshBorders(); break; case "remove_col": datamap.removeCol(index, amount); for (var row = 0, len = datamap.getAll().length; row < len; row++) { if (row in priv.cellSettings) { priv.cellSettings[row].splice(index, amount); } } var fixedColumnsLeft = instance.getSettings().fixedColumnsLeft; if (fixedColumnsLeft >= index + 1) { instance.getSettings().fixedColumnsLeft -= Math.min(amount, fixedColumnsLeft - index); } if (Array.isArray(instance.getSettings().colHeaders)) { if (typeof index == 'undefined') { index = -1; } instance.getSettings().colHeaders.splice(index, amount); } grid.adjustRowsAndCols(); selection.refreshBorders(); break; default: throw new Error('There is no such action "' + action + '"'); break; } if (!keepEmptyRows) { grid.adjustRowsAndCols(); } }, adjustRowsAndCols: function() { var r, rlen, emptyRows, emptyCols; rlen = instance.countRows(); if (rlen < priv.settings.minRows) { for (r = 0; r < priv.settings.minRows - rlen; r++) { datamap.createRow(instance.countRows(), 1, true); } } emptyRows = instance.countEmptyRows(true); if (emptyRows < priv.settings.minSpareRows) { for (; emptyRows < priv.settings.minSpareRows && instance.countRows() < priv.settings.maxRows; emptyRows++) { datamap.createRow(instance.countRows(), 1, true); } } emptyCols = instance.countEmptyCols(true); if (!priv.settings.columns && instance.countCols() < priv.settings.minCols) { for (; instance.countCols() < priv.settings.minCols; emptyCols++) { datamap.createCol(instance.countCols(), 1, true); } } if (!priv.settings.columns && instance.dataType === 'array' && emptyCols < priv.settings.minSpareCols) { for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) { datamap.createCol(instance.countCols(), 1, true); } } var rowCount = instance.countRows(); var colCount = instance.countCols(); if (rowCount === 0 || colCount === 0) { selection.deselect(); } if (selection.isSelected()) { var selectionChanged; var fromRow = priv.selRange.from.row; var fromCol = priv.selRange.from.col; var toRow = priv.selRange.to.row; var toCol = priv.selRange.to.col; if (fromRow > rowCount - 1) { fromRow = rowCount - 1; selectionChanged = true; if (toRow > fromRow) { toRow = fromRow; } } else if (toRow > rowCount - 1) { toRow = rowCount - 1; selectionChanged = true; if (fromRow > toRow) { fromRow = toRow; } } if (fromCol > colCount - 1) { fromCol = colCount - 1; selectionChanged = true; if (toCol > fromCol) { toCol = fromCol; } } else if (toCol > colCount - 1) { toCol = colCount - 1; selectionChanged = true; if (fromCol > toCol) { fromCol = toCol; } } if (selectionChanged) { instance.selectCell(fromRow, fromCol, toRow, toCol); } } }, populateFromArray: function(start, input, end, source, method, direction, deltas) { var r, rlen, c, clen, setData = [], current = {}; rlen = input.length; if (rlen === 0) { return false; } var repeatCol, repeatRow, cmax, rmax; switch (method) { case 'shift_down': repeatCol = end ? end.col - start.col + 1 : 0; repeatRow = end ? end.row - start.row + 1 : 0; input = helper.translateRowsToColumns(input); for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) { if (c < clen) { for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) { input[c].push(input[c][r % rlen]); } input[c].unshift(start.col + c, start.row, 0); instance.spliceCol.apply(instance, input[c]); } else { input[c % clen][0] = start.col + c; instance.spliceCol.apply(instance, input[c % clen]); } } break; case 'shift_right': repeatCol = end ? end.col - start.col + 1 : 0; repeatRow = end ? end.row - start.row + 1 : 0; for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) { if (r < rlen) { for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) { input[r].push(input[r][c % clen]); } input[r].unshift(start.row + r, start.col, 0); instance.spliceRow.apply(instance, input[r]); } else { input[r % rlen][0] = start.row + r; instance.spliceRow.apply(instance, input[r % rlen]); } } break; case 'overwrite': default: current.row = start.row; current.col = start.col; var iterators = { row: 0, col: 0 }, selected = { row: (end && start) ? (end.row - start.row + 1) : 1, col: (end && start) ? (end.col - start.col + 1) : 1 }, pushData = true; if (['up', 'left'].indexOf(direction) !== -1) { iterators = { row: Math.ceil(selected.row / rlen) || 1, col: Math.ceil(selected.col / input[0].length) || 1 }; } else if (['down', 'right'].indexOf(direction) !== -1) { iterators = { row: 1, col: 1 }; } for (r = 0; r < rlen; r++) { if ((end && current.row > end.row) || (!priv.settings.allowInsertRow && current.row > instance.countRows() - 1) || (current.row >= priv.settings.maxRows)) { break; } current.col = start.col; clen = input[r] ? input[r].length : 0; for (c = 0; c < clen; c++) { if ((end && current.col > end.col) || (!priv.settings.allowInsertColumn && current.col > instance.countCols() - 1) || (current.col >= priv.settings.maxCols)) { break; } if (!instance.getCellMeta(current.row, current.col).readOnly) { var result, value = input[r][c], orgValue = instance.getDataAtCell(current.row, current.col), index = { row: r, col: c }, valueSchema, orgValueSchema; if (source === 'autofill') { result = instance.runHooks('beforeAutofillInsidePopulate', index, direction, input, deltas, iterators, selected); if (result) { iterators = typeof(result.iterators) !== 'undefined' ? result.iterators : iterators; value = typeof(result.value) !== 'undefined' ? result.value : value; } } if (value !== null && typeof value === 'object') { if (orgValue === null || typeof orgValue !== 'object') { pushData = false; } else { orgValueSchema = Handsontable.helper.duckSchema(orgValue[0] || orgValue); valueSchema = Handsontable.helper.duckSchema(value[0] || value); if (Handsontable.helper.isObjectEquals(orgValueSchema, valueSchema)) { value = Handsontable.helper.deepClone(value); } else { pushData = false; } } } else if (orgValue !== null && typeof orgValue === 'object') { pushData = false; } if (pushData) { setData.push([current.row, current.col, value]); } pushData = true; } current.col++; if (end && c === clen - 1) { c = -1; if (['down', 'right'].indexOf(direction) !== -1) { iterators.col++; } else if (['up', 'left'].indexOf(direction) !== -1) { if (iterators.col > 1) { iterators.col--; } } } } current.row++; iterators.col = 1; if (end && r === rlen - 1) { r = -1; if (['down', 'right'].indexOf(direction) !== -1) { iterators.row++; } else if (['up', 'left'].indexOf(direction) !== -1) { if (iterators.row > 1) { iterators.row--; } } } } instance.setDataAtCell(setData, null, null, source || 'populateFromArray'); break; } } }; this.selection = selection = { inProgress: false, selectedHeader: { cols: false, rows: false }, setSelectedHeaders: function(rows, cols) { instance.selection.selectedHeader.rows = rows; instance.selection.selectedHeader.cols = cols; }, begin: function() { instance.selection.inProgress = true; }, finish: function() { var sel = instance.getSelected(); Handsontable.hooks.run(instance, "afterSelectionEnd", sel[0], sel[1], sel[2], sel[3]); Handsontable.hooks.run(instance, "afterSelectionEndByProp", sel[0], instance.colToProp(sel[1]), sel[2], instance.colToProp(sel[3])); instance.selection.inProgress = false; }, isInProgress: function() { return instance.selection.inProgress; }, setRangeStart: function(coords, keepEditorOpened) { Handsontable.hooks.run(instance, "beforeSetRangeStart", coords); priv.selRange = new WalkontableCellRange(coords, coords, coords); selection.setRangeEnd(coords, null, keepEditorOpened); }, setRangeEnd: function(coords, scrollToCell, keepEditorOpened) { if (priv.selRange === null) { return; } var disableVisualSelection; Handsontable.hooks.run(instance, "beforeSetRangeEnd", coords); instance.selection.begin(); priv.selRange.to = new WalkontableCellCoords(coords.row, coords.col); if (!priv.settings.multiSelect) { priv.selRange.from = coords; } instance.view.wt.selections.current.clear(); disableVisualSelection = instance.getCellMeta(priv.selRange.highlight.row, priv.selRange.highlight.col).disableVisualSelection; if (typeof disableVisualSelection === 'string') { disableVisualSelection = [disableVisualSelection]; } if (disableVisualSelection === false || Array.isArray(disableVisualSelection) && disableVisualSelection.indexOf('current') === -1) { instance.view.wt.selections.current.add(priv.selRange.highlight); } instance.view.wt.selections.area.clear(); if ((disableVisualSelection === false || Array.isArray(disableVisualSelection) && disableVisualSelection.indexOf('area') === -1) && selection.isMultiple()) { instance.view.wt.selections.area.add(priv.selRange.from); instance.view.wt.selections.area.add(priv.selRange.to); } if (priv.settings.currentRowClassName || priv.settings.currentColClassName) { instance.view.wt.selections.highlight.clear(); instance.view.wt.selections.highlight.add(priv.selRange.from); instance.view.wt.selections.highlight.add(priv.selRange.to); } Handsontable.hooks.run(instance, "afterSelection", priv.selRange.from.row, priv.selRange.from.col, priv.selRange.to.row, priv.selRange.to.col); Handsontable.hooks.run(instance, "afterSelectionByProp", priv.selRange.from.row, datamap.colToProp(priv.selRange.from.col), priv.selRange.to.row, datamap.colToProp(priv.selRange.to.col)); if (scrollToCell !== false && instance.view.mainViewIsActive()) { if (priv.selRange.from && !selection.isMultiple()) { instance.view.scrollViewport(priv.selRange.from); } else { instance.view.scrollViewport(coords); } } selection.refreshBorders(null, keepEditorOpened); }, refreshBorders: function(revertOriginal, keepEditor) { if (!keepEditor) { editorManager.destroyEditor(revertOriginal); } instance.view.render(); if (selection.isSelected() && !keepEditor) { editorManager.prepareEditor(); } }, isMultiple: function() { var isMultiple = !(priv.selRange.to.col === priv.selRange.from.col && priv.selRange.to.row === priv.selRange.from.row), modifier = Handsontable.hooks.run(instance, 'afterIsMultipleSelection', isMultiple); if (isMultiple) { return modifier; } }, transformStart: function(rowDelta, colDelta, force, keepEditorOpened) { var delta = new WalkontableCellCoords(rowDelta, colDelta), rowTransformDir = 0, colTransformDir = 0, totalRows, totalCols, coords; instance.runHooks('modifyTransformStart', delta); totalRows = instance.countRows(); totalCols = instance.countCols(); if (priv.selRange.highlight.row + rowDelta > totalRows - 1) { if (force && priv.settings.minSpareRows > 0) { instance.alter("insert_row", totalRows); } else if (priv.settings.autoWrapCol) { delta.row = 1 - totalRows; delta.col = priv.selRange.highlight.col + delta.col == totalCols - 1 ? 1 - totalCols : 1; } } else if (priv.settings.autoWrapCol && priv.selRange.highlight.row + delta.row < 0 && priv.selRange.highlight.col + delta.col >= 0) { delta.row = totalRows - 1; delta.col = priv.selRange.highlight.col + delta.col == 0 ? totalCols - 1 : -1; } if (priv.selRange.highlight.col + delta.col > totalCols - 1) { if (force && priv.settings.minSpareCols > 0) { instance.alter("insert_col", totalCols); } else if (priv.settings.autoWrapRow) { delta.row = priv.selRange.highlight.row + delta.row == totalRows - 1 ? 1 - totalRows : 1; delta.col = 1 - totalCols; } } else if (priv.settings.autoWrapRow && priv.selRange.highlight.col + delta.col < 0 && priv.selRange.highlight.row + delta.row >= 0) { delta.row = priv.selRange.highlight.row + delta.row == 0 ? totalRows - 1 : -1; delta.col = totalCols - 1; } coords = new WalkontableCellCoords(priv.selRange.highlight.row + delta.row, priv.selRange.highlight.col + delta.col); if (coords.row < 0) { rowTransformDir = -1; coords.row = 0; } else if (coords.row > 0 && coords.row >= totalRows) { rowTransformDir = 1; coords.row = totalRows - 1; } if (coords.col < 0) { colTransformDir = -1; coords.col = 0; } else if (coords.col > 0 && coords.col >= totalCols) { colTransformDir = 1; coords.col = totalCols - 1; } instance.runHooks('afterModifyTransformStart', coords, rowTransformDir, colTransformDir); selection.setRangeStart(coords, keepEditorOpened); }, transformEnd: function(rowDelta, colDelta) { var delta = new WalkontableCellCoords(rowDelta, colDelta), rowTransformDir = 0, colTransformDir = 0, totalRows, totalCols, coords; instance.runHooks('modifyTransformEnd', delta); totalRows = instance.countRows(); totalCols = instance.countCols(); coords = new WalkontableCellCoords(priv.selRange.to.row + delta.row, priv.selRange.to.col + delta.col); if (coords.row < 0) { rowTransformDir = -1; coords.row = 0; } else if (coords.row > 0 && coords.row >= totalRows) { rowTransformDir = 1; coords.row = totalRows - 1; } if (coords.col < 0) { colTransformDir = -1; coords.col = 0; } else if (coords.col > 0 && coords.col >= totalCols) { colTransformDir = 1; coords.col = totalCols - 1; } instance.runHooks('afterModifyTransformEnd', coords, rowTransformDir, colTransformDir); selection.setRangeEnd(coords, true); }, isSelected: function() { return (priv.selRange !== null); }, inInSelection: function(coords) { if (!selection.isSelected()) { return false; } return priv.selRange.includes(coords); }, deselect: function() { if (!selection.isSelected()) { return; } instance.selection.inProgress = false; priv.selRange = null; instance.view.wt.selections.current.clear(); instance.view.wt.selections.area.clear(); if (priv.settings.currentRowClassName || priv.settings.currentColClassName) { instance.view.wt.selections.highlight.clear(); } editorManager.destroyEditor(); selection.refreshBorders(); Handsontable.hooks.run(instance, 'afterDeselect'); }, selectAll: function() { if (!priv.settings.multiSelect) { return; } selection.setRangeStart(new WalkontableCellCoords(0, 0)); selection.setRangeEnd(new WalkontableCellCoords(instance.countRows() - 1, instance.countCols() - 1), false); }, empty: function() { if (!selection.isSelected()) { return; } var topLeft = priv.selRange.getTopLeftCorner(); var bottomRight = priv.selRange.getBottomRightCorner(); var r, c, changes = []; for (r = topLeft.row; r <= bottomRight.row; r++) { for (c = topLeft.col; c <= bottomRight.col; c++) { if (!instance.getCellMeta(r, c).readOnly) { changes.push([r, c, '']); } } } instance.setDataAtCell(changes); } }; this.init = function() { Handsontable.hooks.run(instance, 'beforeInit'); if (Handsontable.mobileBrowser) { dom.addClass(instance.rootElement, 'mobile'); } this.updateSettings(priv.settings, true); this.view = new TableView(this); editorManager = new EditorManager(instance, priv, selection, datamap); this.forceFullRender = true; this.view.render(); if (typeof priv.firstRun === 'object') { Handsontable.hooks.run(instance, 'afterChange', priv.firstRun[0], priv.firstRun[1]); priv.firstRun = false; } Handsontable.hooks.run(instance, 'afterInit'); }; function ValidatorsQueue() { var resolved = false; return { validatorsInQueue: 0, addValidatorToQueue: function() { this.validatorsInQueue++; resolved = false; }, removeValidatorFormQueue: function() { this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1; this.checkIfQueueIsEmpty(); }, onQueueEmpty: function() {}, checkIfQueueIsEmpty: function() { if (this.validatorsInQueue == 0 && resolved == false) { resolved = true; this.onQueueEmpty(); } } }; } function validateChanges(changes, source, callback) { var waitingForValidator = new ValidatorsQueue(); waitingForValidator.onQueueEmpty = resolve; for (var i = changes.length - 1; i >= 0; i--) { if (changes[i] === null) { changes.splice(i, 1); } else { var row = changes[i][0]; var col = datamap.propToCol(changes[i][1]); var logicalCol = instance.runHooks('modifyCol', col); var cellProperties = instance.getCellMeta(row, logicalCol); if (cellProperties.type === 'numeric' && typeof changes[i][3] === 'string') { if (changes[i][3].length > 0 && (/^-?[\d\s]*(\.|\,)?\d*$/.test(changes[i][3]) || cellProperties.format)) { var len = changes[i][3].length; if (typeof cellProperties.language == 'undefined') { numeral.language('en'); } else if (changes[i][3].indexOf(".") === len - 3 && changes[i][3].indexOf(",") === -1) { numeral.language('en'); } else { numeral.language(cellProperties.language); } if (numeral.validate(changes[i][3])) { changes[i][3] = numeral().unformat(changes[i][3]); } } } if (instance.getCellValidator(cellProperties)) { waitingForValidator.addValidatorToQueue(); instance.validateCell(changes[i][3], cellProperties, (function(i, cellProperties) { return function(result) { if (typeof result !== 'boolean') { throw new Error("Validation error: result is not boolean"); } if (result === false && cellProperties.allowInvalid === false) { changes.splice(i, 1); cellProperties.valid = true; --i; } waitingForValidator.removeValidatorFormQueue(); }; })(i, cellProperties), source); } } } waitingForValidator.checkIfQueueIsEmpty(); function resolve() { var beforeChangeResult; if (changes.length) { beforeChangeResult = Handsontable.hooks.run(instance, "beforeChange", changes, source); if (typeof beforeChangeResult === 'function') { console.warn("Your beforeChange callback returns a function. It's not supported since Handsontable 0.12.1 (and the returned function will not be executed)."); } else if (beforeChangeResult === false) { changes.splice(0, changes.length); } } callback(); } } function applyChanges(changes, source) { var i = changes.length - 1; if (i < 0) { return; } for (; 0 <= i; i--) { if (changes[i] === null) { changes.splice(i, 1); continue; } if (changes[i][2] == null && changes[i][3] == null) { continue; } if (priv.settings.allowInsertRow) { while (changes[i][0] > instance.countRows() - 1) { datamap.createRow(); } } if (instance.dataType === 'array' && priv.settings.allowInsertColumn) { while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) { datamap.createCol(); } } datamap.set(changes[i][0], changes[i][1], changes[i][3]); } instance.forceFullRender = true; grid.adjustRowsAndCols(); Handsontable.hooks.run(instance, 'beforeChangeRender', changes, source); selection.refreshBorders(null, true); Handsontable.hooks.run(instance, 'afterChange', changes, source || 'edit'); } this.validateCell = function(value, cellProperties, callback, source) { var validator = instance.getCellValidator(cellProperties); function done(valid) { var col = cellProperties.col, row = cellProperties.row, td = instance.getCell(row, col, true); if (td) { instance.view.wt.wtSettings.settings.cellRenderer(row, col, td); } callback(valid); } if (Object.prototype.toString.call(validator) === '[object RegExp]') { validator = (function(validator) { return function(value, callback) { callback(validator.test(value)); }; })(validator); } if (typeof validator == 'function') { value = Handsontable.hooks.run(instance, "beforeValidate", value, cellProperties.row, cellProperties.prop, source); instance._registerTimeout(setTimeout(function() { validator.call(cellProperties, value, function(valid) { valid = Handsontable.hooks.run(instance, "afterValidate", valid, value, cellProperties.row, cellProperties.prop, source); cellProperties.valid = valid; done(valid); Handsontable.hooks.run(instance, "postAfterValidate", valid, value, cellProperties.row, cellProperties.prop, source); }); }, 0)); } else { cellProperties.valid = true; done(cellProperties.valid); } }; function setDataInputToArray(row, propOrCol, value) { if (typeof row === "object") { return row; } else { return [[row, propOrCol, value]]; } } this.setDataAtCell = function(row, col, value, source) { var input = setDataInputToArray(row, col, value), i, ilen, changes = [], prop; for (i = 0, ilen = input.length; i < ilen; i++) { if (typeof input[i] !== 'object') { throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter'); } if (typeof input[i][1] !== 'number') { throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`'); } prop = datamap.colToProp(input[i][1]); changes.push([input[i][0], prop, datamap.get(input[i][0], prop), input[i][2]]); } if (!source && typeof row === "object") { source = col; } validateChanges(changes, source, function() { applyChanges(changes, source); }); }; this.setDataAtRowProp = function(row, prop, value, source) { var input = setDataInputToArray(row, prop, value), i, ilen, changes = []; for (i = 0, ilen = input.length; i < ilen; i++) { changes.push([input[i][0], input[i][1], datamap.get(input[i][0], input[i][1]), input[i][2]]); } if (!source && typeof row === "object") { source = prop; } validateChanges(changes, source, function() { applyChanges(changes, source); }); }; this.listen = function() { Handsontable.activeGuid = instance.guid; if (document.activeElement && document.activeElement !== document.body) { document.activeElement.blur(); } else if (!document.activeElement) { document.body.focus(); } }; this.unlisten = function() { Handsontable.activeGuid = null; }; this.isListening = function() { return Handsontable.activeGuid === instance.guid; }; this.destroyEditor = function(revertOriginal) { selection.refreshBorders(revertOriginal); }; this.populateFromArray = function(row, col, input, endRow, endCol, source, method, direction, deltas) { var c; if (!(typeof input === 'object' && typeof input[0] === 'object')) { throw new Error("populateFromArray parameter `input` must be an array of arrays"); } c = typeof endRow === 'number' ? new WalkontableCellCoords(endRow, endCol) : null; return grid.populateFromArray(new WalkontableCellCoords(row, col), input, c, source, method, direction, deltas); }; this.spliceCol = function(col, index, amount) { return datamap.spliceCol.apply(datamap, arguments); }; this.spliceRow = function(row, index, amount) { return datamap.spliceRow.apply(datamap, arguments); }; this.getSelected = function() { if (selection.isSelected()) { return [priv.selRange.from.row, priv.selRange.from.col, priv.selRange.to.row, priv.selRange.to.col]; } }; this.getSelectedRange = function() { if (selection.isSelected()) { return priv.selRange; } }; this.render = function() { if (instance.view) { instance.forceFullRender = true; selection.refreshBorders(null, true); } }; this.loadData = function(data) { if (typeof data === 'object' && data !== null) { if (!(data.push && data.splice)) { data = [data]; } } else if (data === null) { data = []; var row; for (var r = 0, rlen = priv.settings.startRows; r < rlen; r++) { row = []; for (var c = 0, clen = priv.settings.startCols; c < clen; c++) { row.push(null); } data.push(row); } } else { throw new Error("loadData only accepts array of objects or array of arrays (" + typeof data + " given)"); } priv.isPopulated = false; GridSettings.prototype.data = data; if (Array.isArray(priv.settings.dataSchema) || Array.isArray(data[0])) { instance.dataType = 'array'; } else if (typeof priv.settings.dataSchema === 'function') { instance.dataType = 'function'; } else { instance.dataType = 'object'; } datamap = new DataMap(instance, priv, GridSettings); clearCellSettingCache(); grid.adjustRowsAndCols(); Handsontable.hooks.run(instance, 'afterLoadData'); if (priv.firstRun) { priv.firstRun = [null, 'loadData']; } else { Handsontable.hooks.run(instance, 'afterChange', null, 'loadData'); instance.render(); } priv.isPopulated = true; function clearCellSettingCache() { priv.cellSettings.length = 0; } }; this.getData = function(r, c, r2, c2) { if (typeof r === 'undefined') { return datamap.getAll(); } else { return datamap.getRange(new WalkontableCellCoords(r, c), new WalkontableCellCoords(r2, c2), datamap.DESTINATION_RENDERER); } }; this.getCopyableData = function(startRow, startCol, endRow, endCol) { return datamap.getCopyableText(new WalkontableCellCoords(startRow, startCol), new WalkontableCellCoords(endRow, endCol)); }; this.getSchema = function() { return datamap.getSchema(); }; this.updateSettings = function(settings, init) { var i, clen; if (typeof settings.rows !== "undefined") { throw new Error("'rows' setting is no longer supported. do you mean startRows, minRows or maxRows?"); } if (typeof settings.cols !== "undefined") { throw new Error("'cols' setting is no longer supported. do you mean startCols, minCols or maxCols?"); } for (i in settings) { if (i === 'data') { continue; } else { if (Handsontable.hooks.hooks[i] !== void 0 || Handsontable.hooks.legacy[i] !== void 0) { if (typeof settings[i] === 'function' || Array.isArray(settings[i])) { instance.addHook(i, settings[i]); } } else { if (!init && settings.hasOwnProperty(i)) { GridSettings.prototype[i] = settings[i]; } } } } if (settings.data === void 0 && priv.settings.data === void 0) { instance.loadData(null); } else if (settings.data !== void 0) { instance.loadData(settings.data); } else if (settings.columns !== void 0) { datamap.createMap(); } clen = instance.countCols(); priv.cellSettings.length = 0; if (clen > 0) { var proto, column; for (i = 0; i < clen; i++) { priv.columnSettings[i] = helper.columnFactory(GridSettings, priv.columnsSettingConflicts); proto = priv.columnSettings[i].prototype; if (GridSettings.prototype.columns) { column = GridSettings.prototype.columns[i]; helper.extend(proto, column); helper.extend(proto, expandType(column)); } } } if (typeof settings.cell !== 'undefined') { for (i in settings.cell) { if (settings.cell.hasOwnProperty(i)) { var cell = settings.cell[i]; instance.setCellMetaObject(cell.row, cell.col, cell); } } } Handsontable.hooks.run(instance, 'afterCellMetaReset'); if (typeof settings.className !== "undefined") { if (GridSettings.prototype.className) { dom.removeClass(instance.rootElement, GridSettings.prototype.className); } if (settings.className) { dom.addClass(instance.rootElement, settings.className); } } if (typeof settings.height != 'undefined') { var height = settings.height; if (typeof height == 'function') { height = height(); } instance.rootElement.style.height = height + 'px'; } if (typeof settings.width != 'undefined') { var width = settings.width; if (typeof width == 'function') { width = width(); } instance.rootElement.style.width = width + 'px'; } if (height) { instance.rootElement.style.overflow = 'hidden'; } if (!init) { Handsontable.hooks.run(instance, 'afterUpdateSettings'); } grid.adjustRowsAndCols(); if (instance.view && !priv.firstRun) { instance.forceFullRender = true; selection.refreshBorders(null, true); } }; this.getValue = function() { var sel = instance.getSelected(); if (GridSettings.prototype.getValue) { if (typeof GridSettings.prototype.getValue === 'function') { return GridSettings.prototype.getValue.call(instance); } else if (sel) { return instance.getData()[sel[0]][GridSettings.prototype.getValue]; } } else if (sel) { return instance.getDataAtCell(sel[0], sel[1]); } }; function expandType(obj) { if (!obj.hasOwnProperty('type')) { return; } var type, expandedType = {}; if (typeof obj.type === 'object') { type = obj.type; } else if (typeof obj.type === 'string') { type = Handsontable.cellTypes[obj.type]; if (type === void 0) { throw new Error('You declared cell type "' + obj.type + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes'); } } for (var i in type) { if (type.hasOwnProperty(i) && !obj.hasOwnProperty(i)) { expandedType[i] = type[i]; } } return expandedType; } this.getSettings = function() { return priv.settings; }; this.clear = function() { selection.selectAll(); selection.empty(); }; this.alter = function(action, index, amount, source, keepEmptyRows) { grid.alter(action, index, amount, source, keepEmptyRows); }; this.getCell = function(row, col, topmost) { return instance.view.getCellAtCoords(new WalkontableCellCoords(row, col), topmost); }; this.getCoords = function(elem) { return this.view.wt.wtTable.getCoords.call(this.view.wt.wtTable, elem); }; this.colToProp = function(col) { return datamap.colToProp(col); }; this.propToCol = function(prop) { return datamap.propToCol(prop); }; this.getDataAtCell = function(row, col) { return datamap.get(row, datamap.colToProp(col)); }; this.getDataAtRowProp = function(row, prop) { return datamap.get(row, prop); }; this.getDataAtCol = function(col) { var out = []; return out.concat.apply(out, datamap.getRange(new WalkontableCellCoords(0, col), new WalkontableCellCoords(priv.settings.data.length - 1, col), datamap.DESTINATION_RENDERER)); }; this.getDataAtProp = function(prop) { var out = [], range; range = datamap.getRange(new WalkontableCellCoords(0, datamap.propToCol(prop)), new WalkontableCellCoords(priv.settings.data.length - 1, datamap.propToCol(prop)), datamap.DESTINATION_RENDERER); return out.concat.apply(out, range); }; this.getSourceDataAtCol = function(col) { var out = [], data = priv.settings.data; for (var i = 0; i < data.length; i++) { out.push(data[i][col]); } return out; }; this.getSourceDataAtRow = function(row) { return priv.settings.data[row]; }; this.getDataAtRow = function(row) { var data = datamap.getRange(new WalkontableCellCoords(row, 0), new WalkontableCellCoords(row, this.countCols() - 1), datamap.DESTINATION_RENDERER); return data[0]; }; this.removeCellMeta = function(row, col, key) { var cellMeta = instance.getCellMeta(row, col); if (cellMeta[key] != undefined) { delete priv.cellSettings[row][col][key]; } }; this.setCellMetaObject = function(row, col, prop) { if (typeof prop === 'object') { for (var key in prop) { if (prop.hasOwnProperty(key)) { var value = prop[key]; this.setCellMeta(row, col, key, value); } } } }; this.setCellMeta = function(row, col, key, val) { if (!priv.cellSettings[row]) { priv.cellSettings[row] = []; } if (!priv.cellSettings[row][col]) { priv.cellSettings[row][col] = new priv.columnSettings[col](); } priv.cellSettings[row][col][key] = val; Handsontable.hooks.run(instance, 'afterSetCellMeta', row, col, key, val); }; this.getCellMeta = function(row, col) { var prop = datamap.colToProp(col), cellProperties; row = translateRowIndex(row); col = translateColIndex(col); if (!priv.columnSettings[col]) { priv.columnSettings[col] = helper.columnFactory(GridSettings, priv.columnsSettingConflicts); } if (!priv.cellSettings[row]) { priv.cellSettings[row] = []; } if (!priv.cellSettings[row][col]) { priv.cellSettings[row][col] = new priv.columnSettings[col](); } cellProperties = priv.cellSettings[row][col]; cellProperties.row = row; cellProperties.col = col; cellProperties.prop = prop; cellProperties.instance = instance; Handsontable.hooks.run(instance, 'beforeGetCellMeta', row, col, cellProperties); helper.extend(cellProperties, expandType(cellProperties)); if (cellProperties.cells) { var settings = cellProperties.cells.call(cellProperties, row, col, prop); if (settings) { helper.extend(cellProperties, settings); helper.extend(cellProperties, expandType(settings)); } } Handsontable.hooks.run(instance, 'afterGetCellMeta', row, col, cellProperties); return cellProperties; }; function translateRowIndex(row) { return Handsontable.hooks.run(instance, 'modifyRow', row); } function translateColIndex(col) { return Handsontable.hooks.run(instance, 'modifyCol', col); } var rendererLookup = helper.cellMethodLookupFactory('renderer'); this.getCellRenderer = function(row, col) { var renderer = rendererLookup.call(this, row, col); return getRenderer(renderer); }; this.getCellEditor = helper.cellMethodLookupFactory('editor'); this.getCellValidator = helper.cellMethodLookupFactory('validator'); this.validateCells = function(callback) { var waitingForValidator = new ValidatorsQueue(); waitingForValidator.onQueueEmpty = callback; var i = instance.countRows() - 1; while (i >= 0) { var j = instance.countCols() - 1; while (j >= 0) { waitingForValidator.addValidatorToQueue(); instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), function() { waitingForValidator.removeValidatorFormQueue(); }, 'validateCells'); j--; } i--; } waitingForValidator.checkIfQueueIsEmpty(); }; this.getRowHeader = function(row) { if (row === void 0) { var out = []; for (var i = 0, ilen = instance.countRows(); i < ilen; i++) { out.push(instance.getRowHeader(i)); } return out; } else if (Array.isArray(priv.settings.rowHeaders) && priv.settings.rowHeaders[row] !== void 0) { return priv.settings.rowHeaders[row]; } else if (typeof priv.settings.rowHeaders === 'function') { return priv.settings.rowHeaders(row); } else if (priv.settings.rowHeaders && typeof priv.settings.rowHeaders !== 'string' && typeof priv.settings.rowHeaders !== 'number') { return row + 1; } else { return priv.settings.rowHeaders; } }; this.hasRowHeaders = function() { return !!priv.settings.rowHeaders; }; this.hasColHeaders = function() { if (priv.settings.colHeaders !== void 0 && priv.settings.colHeaders !== null) { return !!priv.settings.colHeaders; } for (var i = 0, ilen = instance.countCols(); i < ilen; i++) { if (instance.getColHeader(i)) { return true; } } return false; }; this.getColHeader = function(col) { if (col === void 0) { var out = []; for (var i = 0, ilen = instance.countCols(); i < ilen; i++) { out.push(instance.getColHeader(i)); } return out; } else { var baseCol = col; col = Handsontable.hooks.run(instance, 'modifyCol', col); if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) { return priv.settings.columns[col].title; } else if (Array.isArray(priv.settings.colHeaders) && priv.settings.colHeaders[col] !== void 0) { return priv.settings.colHeaders[col]; } else if (typeof priv.settings.colHeaders === 'function') { return priv.settings.colHeaders(col); } else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') { return helper.spreadsheetColumnLabel(baseCol); } else { return priv.settings.colHeaders; } } }; this._getColWidthFromSettings = function(col) { var cellProperties = instance.getCellMeta(0, col); var width = cellProperties.width; if (width === void 0 || width === priv.settings.width) { width = cellProperties.colWidths; } if (width !== void 0 && width !== null) { switch (typeof width) { case 'object': width = width[col]; break; case 'function': width = width(col); break; } if (typeof width === 'string') { width = parseInt(width, 10); } } return width; }; this.getColWidth = function(col) { var width = instance._getColWidthFromSettings(col); if (!width) { width = 50; } width = Handsontable.hooks.run(instance, 'modifyColWidth', width, col); return width; }; this._getRowHeightFromSettings = function(row) { var height = priv.settings.rowHeights; if (height !== void 0 && height !== null) { switch (typeof height) { case 'object': height = height[row]; break; case 'function': height = height(row); break; } if (typeof height === 'string') { height = parseInt(height, 10); } } return height; }; this.getRowHeight = function(row) { var height = instance._getRowHeightFromSettings(row); height = Handsontable.hooks.run(instance, 'modifyRowHeight', height, row); return height; }; this.countRows = function() { return priv.settings.data.length; }; this.countCols = function() { if (instance.dataType === 'object' || instance.dataType === 'function') { if (priv.settings.columns && priv.settings.columns.length) { return priv.settings.columns.length; } else { return datamap.colToPropCache.length; } } else if (instance.dataType === 'array') { if (priv.settings.columns && priv.settings.columns.length) { return priv.settings.columns.length; } else if (priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length) { return priv.settings.data[0].length; } else { return 0; } } }; this.rowOffset = function() { return instance.view.wt.wtTable.getFirstRenderedRow(); }; this.colOffset = function() { return instance.view.wt.wtTable.getFirstRenderedColumn(); }; this.countRenderedRows = function() { return instance.view.wt.drawn ? instance.view.wt.wtTable.getRenderedRowsCount() : -1; }; this.countVisibleRows = function() { return instance.view.wt.drawn ? instance.view.wt.wtTable.getVisibleRowsCount() : -1; }; this.countRenderedCols = function() { return instance.view.wt.drawn ? instance.view.wt.wtTable.getRenderedColumnsCount() : -1; }; this.countVisibleCols = function() { return instance.view.wt.drawn ? instance.view.wt.wtTable.getVisibleColumnsCount() : -1; }; this.countEmptyRows = function(ending) { var i = instance.countRows() - 1, empty = 0, row; while (i >= 0) { row = Handsontable.hooks.run(this, 'modifyRow', i); if (instance.isEmptyRow(row)) { empty++; } else if (ending) { break; } i--; } return empty; }; this.countEmptyCols = function(ending) { if (instance.countRows() < 1) { return 0; } var i = instance.countCols() - 1, empty = 0; while (i >= 0) { if (instance.isEmptyCol(i)) { empty++; } else if (ending) { break; } i--; } return empty; }; this.isEmptyRow = function(row) { return priv.settings.isEmptyRow.call(instance, row); }; this.isEmptyCol = function(col) { return priv.settings.isEmptyCol.call(instance, col); }; this.selectCell = function(row, col, endRow, endCol, scrollToCell, changeListener) { var coords; changeListener = typeof changeListener === 'undefined' || changeListener === true; if (typeof row !== 'number' || row < 0 || row >= instance.countRows()) { return false; } if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) { return false; } if (typeof endRow !== 'undefined') { if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) { return false; } if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) { return false; } } coords = new WalkontableCellCoords(row, col); priv.selRange = new WalkontableCellRange(coords, coords, coords); if (document.activeElement && document.activeElement !== document.documentElement && document.activeElement !== document.body) { document.activeElement.blur(); } if (changeListener) { instance.listen(); } if (typeof endRow === 'undefined') { selection.setRangeEnd(priv.selRange.from, scrollToCell); } else { selection.setRangeEnd(new WalkontableCellCoords(endRow, endCol), scrollToCell); } instance.selection.finish(); return true; }; this.selectCellByProp = function(row, prop, endRow, endProp, scrollToCell) { arguments[1] = datamap.propToCol(arguments[1]); if (typeof arguments[3] !== "undefined") { arguments[3] = datamap.propToCol(arguments[3]); } return instance.selectCell.apply(instance, arguments); }; this.deselectCell = function() { selection.deselect(); }; this.destroy = function() { instance._clearTimeouts(); if (instance.view) { instance.view.destroy(); } dom.empty(instance.rootElement); eventManager.clear(); Handsontable.hooks.run(instance, 'afterDestroy'); Handsontable.hooks.destroy(instance); for (var i in instance) { if (instance.hasOwnProperty(i)) { if (typeof instance[i] === "function") { if (i !== "runHooks") { instance[i] = postMortem; } } else if (i !== "guid") { instance[i] = null; } } } priv = null; datamap = null; grid = null; selection = null; editorManager = null; instance = null; GridSettings = null; }; function postMortem() { throw new Error("This method cannot be called because this Handsontable instance has been destroyed"); } this.getActiveEditor = function() { return editorManager.getActiveEditor(); }; this.getPlugin = function(pluginName) { return getPlugin(this, pluginName); }; this.getInstance = function() { return instance; }; this.addHook = function(key, fn) { Handsontable.hooks.add(key, fn, instance); }; this.addHookOnce = function(key, fn) { Handsontable.hooks.once(key, fn, instance); }; this.removeHook = function(key, fn) { Handsontable.hooks.remove(key, fn, instance); }; this.runHooks = function(key, p1, p2, p3, p4, p5, p6) { return Handsontable.hooks.run(instance, key, p1, p2, p3, p4, p5, p6); }; this.timeouts = []; this._registerTimeout = function(handle) { this.timeouts.push(handle); }; this._clearTimeouts = function() { for (var i = 0, ilen = this.timeouts.length; i < ilen; i++) { clearTimeout(this.timeouts[i]); } }; this.version = Handsontable.version; }; var DefaultSettings = function() {}; DefaultSettings.prototype = { data: void 0, dataSchema: void 0, width: void 0, height: void 0, startRows: 5, startCols: 5, rowHeaders: null, colHeaders: null, colWidths: void 0, columns: void 0, cells: void 0, cell: [], comments: false, customBorders: false, minRows: 0, minCols: 0, maxRows: Infinity, maxCols: Infinity, minSpareRows: 0, minSpareCols: 0, allowInsertRow: true, allowInsertColumn: true, allowRemoveRow: true, allowRemoveColumn: true, multiSelect: true, fillHandle: true, fixedRowsTop: 0, fixedColumnsLeft: 0, outsideClickDeselects: true, enterBeginsEditing: true, enterMoves: { row: 1, col: 0 }, tabMoves: { row: 0, col: 1 }, autoWrapRow: false, autoWrapCol: false, copyRowsLimit: 1000, copyColsLimit: 1000, pasteMode: 'overwrite', persistentState: false, currentRowClassName: void 0, currentColClassName: void 0, stretchH: 'none', isEmptyRow: function(row) { var col, colLen, value, meta; for (col = 0, colLen = this.countCols(); col < colLen; col++) { value = this.getDataAtCell(row, col); if (value !== '' && value !== null && typeof value !== 'undefined') { if (typeof value === 'object') { meta = this.getCellMeta(row, col); return helper.isObjectEquals(this.getSchema()[meta.prop], value); } return false; } } return true; }, isEmptyCol: function(col) { var row, rowLen, value; for (row = 0, rowLen = this.countRows(); row < rowLen; row++) { value = this.getDataAtCell(row, col); if (value !== '' && value !== null && typeof value !== 'undefined') { return false; } } return true; }, observeDOMVisibility: true, allowInvalid: true, invalidCellClassName: 'htInvalid', placeholder: false, placeholderCellClassName: 'htPlaceholder', readOnlyCellClassName: 'htDimmed', renderer: void 0, commentedCellClassName: 'htCommentCell', fragmentSelection: false, readOnly: false, search: false, type: 'text', copyable: true, editor: void 0, autoComplete: void 0, debug: false, wordWrap: true, noWordWrapClassName: 'htNoWrap', contextMenu: void 0, undo: void 0, columnSorting: void 0, manualColumnMove: void 0, manualColumnResize: void 0, manualRowMove: void 0, manualRowResize: void 0, mergeCells: false, viewportRowRenderingOffset: 10, viewportColumnRenderingOffset: 10, groups: void 0, validator: void 0, disableVisualSelection: false, manualColumnFreeze: void 0, trimWhitespace: true, settings: void 0, source: void 0, title: void 0, checkedTemplate: void 0, uncheckedTemplate: void 0, format: void 0, className: void 0 }; Handsontable.DefaultSettings = DefaultSettings; //# },{"./3rdparty/walkontable/src/cellCoords.js":8,"./3rdparty/walkontable/src/cellRange.js":9,"./3rdparty/walkontable/src/selection.js":20,"./dataMap.js":33,"./dom.js":34,"./editorManager.js":35,"./eventManager.js":48,"./helpers.js":49,"./pluginHooks.js":51,"./plugins.js":52,"./renderers.js":76,"./tableView.js":90,"numeral":"numeral"}],33:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { DataMap: {get: function() { return DataMap; }}, __esModule: {value: true} }); var $__helpers_46_js__, $__multiMap_46_js__, $__3rdparty_47_sheetclip_46_js__; var helper = ($__helpers_46_js__ = require("./helpers.js"), $__helpers_46_js__ && $__helpers_46_js__.__esModule && $__helpers_46_js__ || {default: $__helpers_46_js__}); var MultiMap = ($__multiMap_46_js__ = require("./multiMap.js"), $__multiMap_46_js__ && $__multiMap_46_js__.__esModule && $__multiMap_46_js__ || {default: $__multiMap_46_js__}).MultiMap; var SheetClip = ($__3rdparty_47_sheetclip_46_js__ = require("./3rdparty/sheetclip.js"), $__3rdparty_47_sheetclip_46_js__ && $__3rdparty_47_sheetclip_46_js__.__esModule && $__3rdparty_47_sheetclip_46_js__ || {default: $__3rdparty_47_sheetclip_46_js__}).default; ; Handsontable.DataMap = DataMap; function DataMap(instance, priv, GridSettings) { this.instance = instance; this.priv = priv; this.GridSettings = GridSettings; this.dataSource = this.instance.getSettings().data; if (this.dataSource[0]) { this.duckSchema = this.recursiveDuckSchema(this.dataSource[0]); } else { this.duckSchema = {}; } this.createMap(); } DataMap.prototype.DESTINATION_RENDERER = 1; DataMap.prototype.DESTINATION_CLIPBOARD_GENERATOR = 2; DataMap.prototype.recursiveDuckSchema = function(object) { return Handsontable.helper.duckSchema(object); }; DataMap.prototype.recursiveDuckColumns = function(schema, lastCol, parent) { var prop, i; if (typeof lastCol === 'undefined') { lastCol = 0; parent = ''; } if (typeof schema === "object" && !Array.isArray(schema)) { for (i in schema) { if (schema.hasOwnProperty(i)) { if (schema[i] === null) { prop = parent + i; this.colToPropCache.push(prop); this.propToColCache.set(prop, lastCol); lastCol++; } else { lastCol = this.recursiveDuckColumns(schema[i], lastCol, i + '.'); } } } } return lastCol; }; DataMap.prototype.createMap = function() { var i, ilen, schema = this.getSchema(); if (typeof schema === "undefined") { throw new Error("trying to create `columns` definition but you didnt' provide `schema` nor `data`"); } this.colToPropCache = []; this.propToColCache = new MultiMap(); var columns = this.instance.getSettings().columns; if (columns) { for (i = 0, ilen = columns.length; i < ilen; i++) { if (typeof columns[i].data != 'undefined') { this.colToPropCache[i] = columns[i].data; this.propToColCache.set(columns[i].data, i); } } } else { this.recursiveDuckColumns(schema); } }; DataMap.prototype.colToProp = function(col) { col = Handsontable.hooks.run(this.instance, 'modifyCol', col); if (this.colToPropCache && typeof this.colToPropCache[col] !== 'undefined') { return this.colToPropCache[col]; } return col; }; DataMap.prototype.propToCol = function(prop) { var col; if (typeof this.propToColCache.get(prop) !== 'undefined') { col = this.propToColCache.get(prop); } else { col = prop; } col = Handsontable.hooks.run(this.instance, 'modifyCol', col); return col; }; DataMap.prototype.getSchema = function() { var schema = this.instance.getSettings().dataSchema; if (schema) { if (typeof schema === 'function') { return schema(); } return schema; } return this.duckSchema; }; DataMap.prototype.createRow = function(index, amount, createdAutomatically) { var row, colCount = this.instance.countCols(), numberOfCreatedRows = 0, currentIndex; if (!amount) { amount = 1; } if (typeof index !== 'number' || index >= this.instance.countRows()) { index = this.instance.countRows(); } currentIndex = index; var maxRows = this.instance.getSettings().maxRows; while (numberOfCreatedRows < amount && this.instance.countRows() < maxRows) { if (this.instance.dataType === 'array') { row = []; for (var c = 0; c < colCount; c++) { row.push(null); } } else if (this.instance.dataType === 'function') { row = this.instance.getSettings().dataSchema(index); } else { row = {}; helper.deepExtend(row, this.getSchema()); } if (index === this.instance.countRows()) { this.dataSource.push(row); } else { this.dataSource.splice(index, 0, row); } numberOfCreatedRows++; currentIndex++; } Handsontable.hooks.run(this.instance, 'afterCreateRow', index, numberOfCreatedRows, createdAutomatically); this.instance.forceFullRender = true; return numberOfCreatedRows; }; DataMap.prototype.createCol = function(index, amount, createdAutomatically) { if (this.instance.dataType === 'object' || this.instance.getSettings().columns) { throw new Error("Cannot create new column. When data source in an object, " + "you can only have as much columns as defined in first data row, data schema or in the 'columns' setting." + "If you want to be able to add new columns, you have to use array datasource."); } var rlen = this.instance.countRows(), data = this.dataSource, constructor, numberOfCreatedCols = 0, currentIndex; if (!amount) { amount = 1; } currentIndex = index; var maxCols = this.instance.getSettings().maxCols; while (numberOfCreatedCols < amount && this.instance.countCols() < maxCols) { constructor = helper.columnFactory(this.GridSettings, this.priv.columnsSettingConflicts); if (typeof index !== 'number' || index >= this.instance.countCols()) { for (var r = 0; r < rlen; r++) { if (typeof data[r] === 'undefined') { data[r] = []; } data[r].push(null); } this.priv.columnSettings.push(constructor); } else { for (var r = 0; r < rlen; r++) { data[r].splice(currentIndex, 0, null); } this.priv.columnSettings.splice(currentIndex, 0, constructor); } numberOfCreatedCols++; currentIndex++; } Handsontable.hooks.run(this.instance, 'afterCreateCol', index, numberOfCreatedCols, createdAutomatically); this.instance.forceFullRender = true; return numberOfCreatedCols; }; DataMap.prototype.removeRow = function(index, amount) { if (!amount) { amount = 1; } if (typeof index !== 'number') { index = -amount; } index = (this.instance.countRows() + index) % this.instance.countRows(); var logicRows = this.physicalRowsToLogical(index, amount); var actionWasNotCancelled = Handsontable.hooks.run(this.instance, 'beforeRemoveRow', index, amount); if (actionWasNotCancelled === false) { return; } var data = this.dataSource; var newData = data.filter(function(row, index) { return logicRows.indexOf(index) == -1; }); data.length = 0; Array.prototype.push.apply(data, newData); Handsontable.hooks.run(this.instance, 'afterRemoveRow', index, amount); this.instance.forceFullRender = true; }; DataMap.prototype.removeCol = function(index, amount) { if (this.instance.dataType === 'object' || this.instance.getSettings().columns) { throw new Error("cannot remove column with object data source or columns option specified"); } if (!amount) { amount = 1; } if (typeof index !== 'number') { index = -amount; } index = (this.instance.countCols() + index) % this.instance.countCols(); var actionWasNotCancelled = Handsontable.hooks.run(this.instance, 'beforeRemoveCol', index, amount); if (actionWasNotCancelled === false) { return; } var data = this.dataSource; for (var r = 0, rlen = this.instance.countRows(); r < rlen; r++) { data[r].splice(index, amount); } this.priv.columnSettings.splice(index, amount); Handsontable.hooks.run(this.instance, 'afterRemoveCol', index, amount); this.instance.forceFullRender = true; }; DataMap.prototype.spliceCol = function(col, index, amount) { var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : []; var colData = this.instance.getDataAtCol(col); var removed = colData.slice(index, index + amount); var after = colData.slice(index + amount); helper.extendArray(elements, after); var i = 0; while (i < amount) { elements.push(null); i++; } helper.to2dArray(elements); this.instance.populateFromArray(index, col, elements, null, null, 'spliceCol'); return removed; }; DataMap.prototype.spliceRow = function(row, index, amount) { var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : []; var rowData = this.instance.getSourceDataAtRow(row); var removed = rowData.slice(index, index + amount); var after = rowData.slice(index + amount); helper.extendArray(elements, after); var i = 0; while (i < amount) { elements.push(null); i++; } this.instance.populateFromArray(row, index, [elements], null, null, 'spliceRow'); return removed; }; DataMap.prototype.get = function(row, prop) { row = Handsontable.hooks.run(this.instance, 'modifyRow', row); if (typeof prop === 'string' && prop.indexOf('.') > -1) { var sliced = prop.split("."); var out = this.dataSource[row]; if (!out) { return null; } for (var i = 0, ilen = sliced.length; i < ilen; i++) { out = out[sliced[i]]; if (typeof out === 'undefined') { return null; } } return out; } else if (typeof prop === 'function') { return prop(this.dataSource.slice(row, row + 1)[0]); } else { return this.dataSource[row] ? this.dataSource[row][prop] : null; } }; var copyableLookup = helper.cellMethodLookupFactory('copyable', false); DataMap.prototype.getCopyable = function(row, prop) { if (copyableLookup.call(this.instance, row, this.propToCol(prop))) { return this.get(row, prop); } return ''; }; DataMap.prototype.set = function(row, prop, value, source) { row = Handsontable.hooks.run(this.instance, 'modifyRow', row, source || "datamapGet"); if (typeof prop === 'string' && prop.indexOf('.') > -1) { var sliced = prop.split("."); var out = this.dataSource[row]; for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) { if (typeof out[sliced[i]] === 'undefined') { out[sliced[i]] = {}; } out = out[sliced[i]]; } out[sliced[i]] = value; } else if (typeof prop === 'function') { prop(this.dataSource.slice(row, row + 1)[0], value); } else { this.dataSource[row][prop] = value; } }; DataMap.prototype.physicalRowsToLogical = function(index, amount) { var totalRows = this.instance.countRows(); var physicRow = (totalRows + index) % totalRows; var logicRows = []; var rowsToRemove = amount; var row; while (physicRow < totalRows && rowsToRemove) { row = Handsontable.hooks.run(this.instance, 'modifyRow', physicRow); logicRows.push(row); rowsToRemove--; physicRow++; } return logicRows; }; DataMap.prototype.clear = function() { for (var r = 0; r < this.instance.countRows(); r++) { for (var c = 0; c < this.instance.countCols(); c++) { this.set(r, this.colToProp(c), ''); } } }; DataMap.prototype.getAll = function() { return this.dataSource; }; DataMap.prototype.getRange = function(start, end, destination) { var r, rlen, c, clen, output = [], row; var getFn = destination === this.DESTINATION_CLIPBOARD_GENERATOR ? this.getCopyable : this.get; rlen = Math.max(start.row, end.row); clen = Math.max(start.col, end.col); for (r = Math.min(start.row, end.row); r <= rlen; r++) { row = []; for (c = Math.min(start.col, end.col); c <= clen; c++) { row.push(getFn.call(this, r, this.colToProp(c))); } output.push(row); } return output; }; DataMap.prototype.getText = function(start, end) { return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_RENDERER)); }; DataMap.prototype.getCopyableText = function(start, end) { return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_CLIPBOARD_GENERATOR)); }; //# },{"./3rdparty/sheetclip.js":5,"./helpers.js":49,"./multiMap.js":50}],34:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { enableImmediatePropagation: {get: function() { return enableImmediatePropagation; }}, closest: {get: function() { return closest; }}, isChildOf: {get: function() { return isChildOf; }}, isChildOfWebComponentTable: {get: function() { return isChildOfWebComponentTable; }}, polymerWrap: {get: function() { return polymerWrap; }}, polymerUnwrap: {get: function() { return polymerUnwrap; }}, isWebComponentSupportedNatively: {get: function() { return isWebComponentSupportedNatively; }}, index: {get: function() { return index; }}, hasClass: {get: function() { return hasClass; }}, addClass: {get: function() { return addClass; }}, removeClass: {get: function() { return removeClass; }}, removeTextNodes: {get: function() { return removeTextNodes; }}, empty: {get: function() { return empty; }}, HTML_CHARACTERS: {get: function() { return HTML_CHARACTERS; }}, fastInnerHTML: {get: function() { return fastInnerHTML; }}, fastInnerText: {get: function() { return fastInnerText; }}, isVisible: {get: function() { return isVisible; }}, offset: {get: function() { return offset; }}, getWindowScrollTop: {get: function() { return getWindowScrollTop; }}, getWindowScrollLeft: {get: function() { return getWindowScrollLeft; }}, getScrollTop: {get: function() { return getScrollTop; }}, getScrollLeft: {get: function() { return getScrollLeft; }}, getScrollableElement: {get: function() { return getScrollableElement; }}, getTrimmingContainer: {get: function() { return getTrimmingContainer; }}, getStyle: {get: function() { return getStyle; }}, getComputedStyle: {get: function() { return getComputedStyle; }}, outerWidth: {get: function() { return outerWidth; }}, outerHeight: {get: function() { return outerHeight; }}, innerHeight: {get: function() { return innerHeight; }}, innerWidth: {get: function() { return innerWidth; }}, addEvent: {get: function() { return addEvent; }}, removeEvent: {get: function() { return removeEvent; }}, hasCaptionProblem: {get: function() { return hasCaptionProblem; }}, getCaretPosition: {get: function() { return getCaretPosition; }}, getSelectionEndPosition: {get: function() { return getSelectionEndPosition; }}, setCaretPosition: {get: function() { return setCaretPosition; }}, getScrollbarWidth: {get: function() { return getScrollbarWidth; }}, isIE8: {get: function() { return isIE8; }}, isIE9: {get: function() { return isIE9; }}, isSafari: {get: function() { return isSafari; }}, setOverlayPosition: {get: function() { return setOverlayPosition; }}, getCssTransform: {get: function() { return getCssTransform; }}, resetCssTransform: {get: function() { return resetCssTransform; }}, __esModule: {value: true} }); function enableImmediatePropagation(event) { if (event != null && event.isImmediatePropagationEnabled == null) { event.stopImmediatePropagation = function() { this.isImmediatePropagationEnabled = false; this.cancelBubble = true; }; event.isImmediatePropagationEnabled = true; event.isImmediatePropagationStopped = function() { return !this.isImmediatePropagationEnabled; }; } } function closest(element, nodes, until) { while (element != null && element !== until) { if (element.nodeType === Node.ELEMENT_NODE && (nodes.indexOf(element.nodeName) > -1 || nodes.indexOf(element) > -1)) { return element; } if (element.host && element.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { element = element.host; } else { element = element.parentNode; } } return null; } function isChildOf(child, parent) { var node = child.parentNode; var queriedParents = []; if (typeof parent === "string") { queriedParents = Array.prototype.slice.call(document.querySelectorAll(parent), 0); } else { queriedParents.push(parent); } while (node != null) { if (queriedParents.indexOf(node) > -1) { return true; } node = node.parentNode; } return false; } function isChildOfWebComponentTable(element) { var hotTableName = 'hot-table', result = false, parentNode; parentNode = polymerWrap(element); function isHotTable(element) { return element.nodeType === Node.ELEMENT_NODE && element.nodeName === hotTableName.toUpperCase(); } while (parentNode != null) { if (isHotTable(parentNode)) { result = true; break; } else if (parentNode.host && parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { result = isHotTable(parentNode.host); if (result) { break; } parentNode = parentNode.host; } parentNode = parentNode.parentNode; } return result; } function polymerWrap(element) { return typeof Polymer !== 'undefined' && typeof wrap === 'function' ? wrap(element) : element; } function polymerUnwrap(element) { return typeof Polymer !== 'undefined' && typeof unwrap === 'function' ? unwrap(element) : element; } function isWebComponentSupportedNatively() { var test = document.createElement('div'); return test.createShadowRoot && test.createShadowRoot.toString().match(/\[native code\]/) ? true : false; } function index(elem) { var i = 0; if (elem.previousSibling) { while (elem = elem.previousSibling) { ++i; } } return i; } var classListSupport = document.documentElement.classList ? true : false; var _hasClass, _addClass, _removeClass; function filterEmptyClassNames(classNames) { var len = 0, result = []; if (!classNames || !classNames.length) { return result; } while (classNames[len]) { result.push(classNames[len]); len++; } return result; } if (classListSupport) { var isSupportMultipleClassesArg = (function() { var element = document.createElement('div'); element.classList.add('test', 'test2'); return element.classList.contains('test2'); }()); _hasClass = function _hasClass(element, className) { if (className === '') { return false; } return element.classList.contains(className); }; _addClass = function _addClass(element, className) { var len = 0; if (typeof className === 'string') { className = className.split(' '); } className = filterEmptyClassNames(className); if (isSupportMultipleClassesArg) { element.classList.add.apply(element.classList, className); } else { while (className && className[len]) { element.classList.add(className[len]); len++; } } }; _removeClass = function _removeClass(element, className) { var len = 0; if (typeof className === 'string') { className = className.split(' '); } className = filterEmptyClassNames(className); if (isSupportMultipleClassesArg) { element.classList.remove.apply(element.classList, className); } else { while (className && className[len]) { element.classList.remove(className[len]); len++; } } }; } else { var createClassNameRegExp = function createClassNameRegExp(className) { return new RegExp('(\\s|^)' + className + '(\\s|$)'); }; _hasClass = function _hasClass(element, className) { return element.className.match(createClassNameRegExp(className)) ? true : false; }; _addClass = function _addClass(element, className) { var len = 0, _className = element.className; if (typeof className === 'string') { className = className.split(' '); } if (_className === '') { _className = className.join(' '); } else { while (className && className[len]) { if (!createClassNameRegExp(className[len]).test(_className)) { _className += ' ' + className[len]; } len++; } } element.className = _className; }; _removeClass = function _removeClass(element, className) { var len = 0, _className = element.className; if (typeof className === 'string') { className = className.split(' '); } while (className && className[len]) { _className = _className.replace(createClassNameRegExp(className[len]), ' ').trim(); len++; } if (element.className !== _className) { element.className = _className; } }; } function hasClass(element, className) { return _hasClass(element, className); } function addClass(element, className) { return _addClass(element, className); } function removeClass(element, className) { return _removeClass(element, className); } function removeTextNodes(elem, parent) { if (elem.nodeType === 3) { parent.removeChild(elem); } else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(elem.nodeName) > -1) { var childs = elem.childNodes; for (var i = childs.length - 1; i >= 0; i--) { removeTextNodes(childs[i], elem); } } } function empty(element) { var child; while (child = element.lastChild) { element.removeChild(child); } } var HTML_CHARACTERS = /(<(.*)>|&(.*);)/; function fastInnerHTML(element, content) { if (HTML_CHARACTERS.test(content)) { element.innerHTML = content; } else { fastInnerText(element, content); } } var textContextSupport = document.createTextNode('test').textContent ? true : false; function fastInnerText(element, content) { var child = element.firstChild; if (child && child.nodeType === 3 && child.nextSibling === null) { if (textContextSupport) { child.textContent = content; } else { child.data = content; } } else { empty(element); element.appendChild(document.createTextNode(content)); } } function isVisible(elem) { var next = elem; while (polymerUnwrap(next) !== document.documentElement) { if (next === null) { return false; } else if (next.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { if (next.host) { if (next.host.impl) { return isVisible(next.host.impl); } else if (next.host) { return isVisible(next.host); } else { throw new Error("Lost in Web Components world"); } } else { return false; } } else if (next.style.display === 'none') { return false; } next = next.parentNode; } return true; } function offset(elem) { var offsetLeft, offsetTop, lastElem, docElem, box; docElem = document.documentElement; if (hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') { box = elem.getBoundingClientRect(); return { top: box.top + (window.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0), left: box.left + (window.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0) }; } offsetLeft = elem.offsetLeft; offsetTop = elem.offsetTop; lastElem = elem; while (elem = elem.offsetParent) { if (elem === document.body) { break; } offsetLeft += elem.offsetLeft; offsetTop += elem.offsetTop; lastElem = elem; } if (lastElem && lastElem.style.position === 'fixed') { offsetLeft += window.pageXOffset || docElem.scrollLeft; offsetTop += window.pageYOffset || docElem.scrollTop; } return { left: offsetLeft, top: offsetTop }; } function getWindowScrollTop() { var res = window.scrollY; if (res == void 0) { res = document.documentElement.scrollTop; } return res; } function getWindowScrollLeft() { var res = window.scrollX; if (res == void 0) { res = document.documentElement.scrollLeft; } return res; } function getScrollTop(elem) { if (elem === window) { return getWindowScrollTop(elem); } else { return elem.scrollTop; } } function getScrollLeft(elem) { if (elem === window) { return getWindowScrollLeft(elem); } else { return elem.scrollLeft; } } function getScrollableElement(element) { var el = element.parentNode, props = ['auto', 'scroll'], overflow, overflowX, overflowY, computedStyle = '', computedOverflow = '', computedOverflowY = '', computedOverflowX = ''; while (el && el.style && document.body !== el) { overflow = el.style.overflow; overflowX = el.style.overflowX; overflowY = el.style.overflowY; if (overflow == 'scroll' || overflowX == 'scroll' || overflowY == 'scroll') { return el; } else if (window.getComputedStyle) { computedStyle = window.getComputedStyle(el); computedOverflow = computedStyle.getPropertyValue('overflow'); computedOverflowY = computedStyle.getPropertyValue('overflow-y'); computedOverflowX = computedStyle.getPropertyValue('overflow-x'); if (computedOverflow === 'scroll' || computedOverflowX === 'scroll' || computedOverflowY === 'scroll') { return el; } } if (el.clientHeight <= el.scrollHeight && (props.indexOf(overflowY) !== -1 || props.indexOf(overflow) !== -1 || props.indexOf(computedOverflow) !== -1 || props.indexOf(computedOverflowY) !== -1)) { return el; } if (el.clientWidth <= el.scrollWidth && (props.indexOf(overflowX) !== -1 || props.indexOf(overflow) !== -1 || props.indexOf(computedOverflow) !== -1 || props.indexOf(computedOverflowX) !== -1)) { return el; } el = el.parentNode; } return window; } function getTrimmingContainer(base) { var el = base.parentNode; while (el && el.style && document.body !== el) { if (el.style.overflow !== 'visible' && el.style.overflow !== '') { return el; } else if (window.getComputedStyle) { var computedStyle = window.getComputedStyle(el); if (computedStyle.getPropertyValue('overflow') !== 'visible' && computedStyle.getPropertyValue('overflow') !== '') { return el; } } el = el.parentNode; } return window; } function getStyle(elem, prop) { if (!elem) { return; } else if (elem === window) { if (prop === 'width') { return window.innerWidth + 'px'; } else if (prop === 'height') { return window.innerHeight + 'px'; } return; } var styleProp = elem.style[prop], computedStyle; if (styleProp !== "" && styleProp !== void 0) { return styleProp; } else { computedStyle = getComputedStyle(elem); if (computedStyle[prop] !== "" && computedStyle[prop] !== void 0) { return computedStyle[prop]; } return void 0; } } function getComputedStyle(elem) { return elem.currentStyle || document.defaultView.getComputedStyle(elem); } function outerWidth(elem) { return elem.offsetWidth; } function outerHeight(elem) { if (hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') { return elem.offsetHeight + elem.firstChild.offsetHeight; } else { return elem.offsetHeight; } } function innerHeight(elem) { return elem.clientHeight || elem.innerHeight; } function innerWidth(elem) { return elem.clientWidth || elem.innerWidth; } function addEvent(element, event, callback) { if (window.addEventListener) { element.addEventListener(event, callback, false); } else { element.attachEvent('on' + event, callback); } } function removeEvent(element, event, callback) { if (window.removeEventListener) { element.removeEventListener(event, callback, false); } else { element.detachEvent('on' + event, callback); } } var _hasCaptionProblem; function detectCaptionProblem() { var TABLE = document.createElement('TABLE'); TABLE.style.borderSpacing = 0; TABLE.style.borderWidth = 0; TABLE.style.padding = 0; var TBODY = document.createElement('TBODY'); TABLE.appendChild(TBODY); TBODY.appendChild(document.createElement('TR')); TBODY.firstChild.appendChild(document.createElement('TD')); TBODY.firstChild.firstChild.innerHTML = '<tr><td>t<br>t</td></tr>'; var CAPTION = document.createElement('CAPTION'); CAPTION.innerHTML = 'c<br>c<br>c<br>c'; CAPTION.style.padding = 0; CAPTION.style.margin = 0; TABLE.insertBefore(CAPTION, TBODY); document.body.appendChild(TABLE); _hasCaptionProblem = (TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight); document.body.removeChild(TABLE); } function hasCaptionProblem() { if (_hasCaptionProblem === void 0) { detectCaptionProblem(); } return _hasCaptionProblem; } function getCaretPosition(el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; } function getSelectionEndPosition(el) { if (el.selectionEnd) { return el.selectionEnd; } else if (document.selection) { var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(); return re.text.indexOf(r.text) + r.text.length; } } function setCaretPosition(el, pos, endPos) { if (endPos === void 0) { endPos = pos; } if (el.setSelectionRange) { el.focus(); el.setSelectionRange(pos, endPos); } else if (el.createTextRange) { var range = el.createTextRange(); range.collapse(true); range.moveEnd('character', endPos); range.moveStart('character', pos); range.select(); } } var cachedScrollbarWidth; function walkontableCalculateScrollbarWidth() { var inner = document.createElement('p'); inner.style.width = "100%"; inner.style.height = "200px"; var outer = document.createElement('div'); outer.style.position = "absolute"; outer.style.top = "0px"; outer.style.left = "0px"; outer.style.visibility = "hidden"; outer.style.width = "200px"; outer.style.height = "150px"; outer.style.overflow = "hidden"; outer.appendChild(inner); (document.body || document.documentElement).appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if (w1 == w2) { w2 = outer.clientWidth; } (document.body || document.documentElement).removeChild(outer); return (w1 - w2); } function getScrollbarWidth() { if (cachedScrollbarWidth === void 0) { cachedScrollbarWidth = walkontableCalculateScrollbarWidth(); } return cachedScrollbarWidth; } var _isIE8 = !(document.createTextNode('test').textContent); function isIE8() { return isIE8; } var _isIE9 = !!(document.documentMode); function isIE9() { return _isIE9; } var _isSafari = (/Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor)); function isSafari() { return _isSafari; } function setOverlayPosition(overlayElem, left, top) { if (_isIE8 || _isIE9) { overlayElem.style.top = top; overlayElem.style.left = left; } else if (_isSafari) { overlayElem.style['-webkit-transform'] = 'translate3d(' + left + ',' + top + ',0)'; } else { overlayElem.style['transform'] = 'translate3d(' + left + ',' + top + ',0)'; } } function getCssTransform(elem) { var transform; if (elem.style['transform'] && (transform = elem.style['transform']) != "") { return ['transform', transform]; } else if (elem.style['-webkit-transform'] && (transform = elem.style['-webkit-transform']) != "") { return ['-webkit-transform', transform]; } else { return -1; } } function resetCssTransform(elem) { if (elem['transform'] && elem['transform'] != "") { elem['transform'] = ""; } else if (elem['-webkit-transform'] && elem['-webkit-transform'] != "") { elem['-webkit-transform'] = ""; } } window.Handsontable = window.Handsontable || {}; Handsontable.Dom = { addClass: addClass, addEvent: addEvent, closest: closest, empty: empty, enableImmediatePropagation: enableImmediatePropagation, fastInnerHTML: fastInnerHTML, fastInnerText: fastInnerText, getCaretPosition: getCaretPosition, getComputedStyle: getComputedStyle, getCssTransform: getCssTransform, getScrollableElement: getScrollableElement, getScrollbarWidth: getScrollbarWidth, getScrollLeft: getScrollLeft, getScrollTop: getScrollTop, getStyle: getStyle, getSelectionEndPosition: getSelectionEndPosition, getWindowScrollLeft: getWindowScrollLeft, getWindowScrollTop: getWindowScrollTop, hasCaptionProblem: hasCaptionProblem, hasClass: hasClass, HTML_CHARACTERS: HTML_CHARACTERS, index: index, innerHeight: innerHeight, innerWidth: innerWidth, isChildOf: isChildOf, isChildOfWebComponentTable: isChildOfWebComponentTable, isIE8: isIE8, isIE9: isIE9, isSafari: isSafari, isVisible: isVisible, isWebComponentSupportedNatively: isWebComponentSupportedNatively, offset: offset, outerHeight: outerHeight, outerWidth: outerWidth, polymerUnwrap: polymerUnwrap, polymerWrap: polymerWrap, removeClass: removeClass, removeEvent: removeEvent, removeTextNodes: removeTextNodes, resetCssTransform: resetCssTransform, setCaretPosition: setCaretPosition, setOverlayPosition: setOverlayPosition }; //# },{}],35:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { EditorManager: {get: function() { return EditorManager; }}, __esModule: {value: true} }); var $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__, $__helpers_46_js__, $__dom_46_js__, $__editors_46_js__, $__eventManager_46_js__; var WalkontableCellCoords = ($__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ = require("./3rdparty/walkontable/src/cellCoords.js"), $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ && $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__.__esModule && $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ || {default: $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__}).WalkontableCellCoords; var helper = ($__helpers_46_js__ = require("./helpers.js"), $__helpers_46_js__ && $__helpers_46_js__.__esModule && $__helpers_46_js__ || {default: $__helpers_46_js__}); var dom = ($__dom_46_js__ = require("./dom.js"), $__dom_46_js__ && $__dom_46_js__.__esModule && $__dom_46_js__ || {default: $__dom_46_js__}); var getEditor = ($__editors_46_js__ = require("./editors.js"), $__editors_46_js__ && $__editors_46_js__.__esModule && $__editors_46_js__ || {default: $__editors_46_js__}).getEditor; var eventManagerObject = ($__eventManager_46_js__ = require("./eventManager.js"), $__eventManager_46_js__ && $__eventManager_46_js__.__esModule && $__eventManager_46_js__ || {default: $__eventManager_46_js__}).eventManager; ; Handsontable.EditorManager = EditorManager; function EditorManager(instance, priv, selection) { var _this = this, keyCodes = helper.keyCode, destroyed = false, eventManager, activeEditor; eventManager = eventManagerObject(instance); function moveSelectionAfterEnter(shiftKey) { var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves; if (shiftKey) { selection.transformStart(-enterMoves.row, -enterMoves.col); } else { selection.transformStart(enterMoves.row, enterMoves.col, true); } } function moveSelectionUp(shiftKey) { if (shiftKey) { selection.transformEnd(-1, 0); } else { selection.transformStart(-1, 0); } } function moveSelectionDown(shiftKey) { if (shiftKey) { selection.transformEnd(1, 0); } else { selection.transformStart(1, 0); } } function moveSelectionRight(shiftKey) { if (shiftKey) { selection.transformEnd(0, 1); } else { selection.transformStart(0, 1); } } function moveSelectionLeft(shiftKey) { if (shiftKey) { selection.transformEnd(0, -1); } else { selection.transformStart(0, -1); } } function onKeyDown(event) { var ctrlDown, rangeModifier; if (!instance.isListening()) { return; } Handsontable.hooks.run(instance, 'beforeKeyDown', event); if (destroyed) { return; } dom.enableImmediatePropagation(event); if (event.isImmediatePropagationStopped()) { return; } priv.lastKeyCode = event.keyCode; if (!selection.isSelected()) { return; } ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; if (activeEditor && !activeEditor.isWaiting()) { if (!helper.isMetaKey(event.keyCode) && !ctrlDown && !_this.isEditorOpened()) { _this.openEditor("", event); return; } } rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart; switch (event.keyCode) { case keyCodes.A: if (ctrlDown) { selection.selectAll(); event.preventDefault(); helper.stopPropagation(event); } break; case keyCodes.ARROW_UP: if (_this.isEditorOpened() && activeEditor && !activeEditor.isWaiting()) { _this.closeEditorAndSaveChanges(ctrlDown); } moveSelectionUp(event.shiftKey); event.preventDefault(); helper.stopPropagation(event); break; case keyCodes.ARROW_DOWN: if (_this.isEditorOpened() && activeEditor && !activeEditor.isWaiting()) { _this.closeEditorAndSaveChanges(ctrlDown); } moveSelectionDown(event.shiftKey); event.preventDefault(); helper.stopPropagation(event); break; case keyCodes.ARROW_RIGHT: if (_this.isEditorOpened() && activeEditor && !activeEditor.isWaiting()) { _this.closeEditorAndSaveChanges(ctrlDown); } moveSelectionRight(event.shiftKey); event.preventDefault(); helper.stopPropagation(event); break; case keyCodes.ARROW_LEFT: if (_this.isEditorOpened() && activeEditor && !activeEditor.isWaiting()) { _this.closeEditorAndSaveChanges(ctrlDown); } moveSelectionLeft(event.shiftKey); event.preventDefault(); helper.stopPropagation(event); break; case keyCodes.TAB: var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves; if (event.shiftKey) { selection.transformStart(-tabMoves.row, -tabMoves.col); } else { selection.transformStart(tabMoves.row, tabMoves.col, true); } event.preventDefault(); helper.stopPropagation(event); break; case keyCodes.BACKSPACE: case keyCodes.DELETE: selection.empty(event); _this.prepareEditor(); event.preventDefault(); break; case keyCodes.F2: _this.openEditor(null, event); event.preventDefault(); break; case keyCodes.ENTER: if (_this.isEditorOpened()) { if (activeEditor && activeEditor.state !== Handsontable.EditorState.WAITING) { _this.closeEditorAndSaveChanges(ctrlDown); } moveSelectionAfterEnter(event.shiftKey); } else { if (instance.getSettings().enterBeginsEditing) { _this.openEditor(null, event); } else { moveSelectionAfterEnter(event.shiftKey); } } event.preventDefault(); event.stopImmediatePropagation(); break; case keyCodes.ESCAPE: if (_this.isEditorOpened()) { _this.closeEditorAndRestoreOriginalValue(ctrlDown); } event.preventDefault(); break; case keyCodes.HOME: if (event.ctrlKey || event.metaKey) { rangeModifier(new WalkontableCellCoords(0, priv.selRange.from.col)); } else { rangeModifier(new WalkontableCellCoords(priv.selRange.from.row, 0)); } event.preventDefault(); helper.stopPropagation(event); break; case keyCodes.END: if (event.ctrlKey || event.metaKey) { rangeModifier(new WalkontableCellCoords(instance.countRows() - 1, priv.selRange.from.col)); } else { rangeModifier(new WalkontableCellCoords(priv.selRange.from.row, instance.countCols() - 1)); } event.preventDefault(); helper.stopPropagation(event); break; case keyCodes.PAGE_UP: selection.transformStart(-instance.countVisibleRows(), 0); event.preventDefault(); helper.stopPropagation(event); break; case keyCodes.PAGE_DOWN: selection.transformStart(instance.countVisibleRows(), 0); event.preventDefault(); helper.stopPropagation(event); break; } } function init() { instance.addHook('afterDocumentKeyDown', onKeyDown); eventManager.addEventListener(document.documentElement, 'keydown', function(event) { instance.runHooks('afterDocumentKeyDown', event); }); function onDblClick(event, coords, elem) { if (elem.nodeName == "TD") { _this.openEditor(); } } instance.view.wt.update('onCellDblClick', onDblClick); instance.addHook('afterDestroy', function() { destroyed = true; }); } this.destroyEditor = function(revertOriginal) { this.closeEditor(revertOriginal); }; this.getActiveEditor = function() { return activeEditor; }; this.prepareEditor = function() { var row, col, prop, td, originalValue, cellProperties, editorClass; if (activeEditor && activeEditor.isWaiting()) { this.closeEditor(false, false, function(dataSaved) { if (dataSaved) { _this.prepareEditor(); } }); return; } row = priv.selRange.highlight.row; col = priv.selRange.highlight.col; prop = instance.colToProp(col); td = instance.getCell(row, col); originalValue = instance.getDataAtCell(row, col); cellProperties = instance.getCellMeta(row, col); editorClass = instance.getCellEditor(cellProperties); if (editorClass) { activeEditor = Handsontable.editors.getEditor(editorClass, instance); activeEditor.prepare(row, col, prop, td, originalValue, cellProperties); } else { activeEditor = void 0; } }; this.isEditorOpened = function() { return activeEditor && activeEditor.isOpened(); }; this.openEditor = function(initialValue, event) { if (activeEditor && !activeEditor.cellProperties.readOnly) { activeEditor.beginEditing(initialValue, event); } else if (activeEditor && activeEditor.cellProperties.readOnly) { if (event && event.keyCode === helper.keyCode.ENTER) { moveSelectionAfterEnter(); } } }; this.closeEditor = function(restoreOriginalValue, ctrlDown, callback) { if (!activeEditor) { if (callback) { callback(false); } } else { activeEditor.finishEditing(restoreOriginalValue, ctrlDown, callback); } }; this.closeEditorAndSaveChanges = function(ctrlDown) { return this.closeEditor(false, ctrlDown); }; this.closeEditorAndRestoreOriginalValue = function(ctrlDown) { return this.closeEditor(true, ctrlDown); }; init(); } //# },{"./3rdparty/walkontable/src/cellCoords.js":8,"./dom.js":34,"./editors.js":36,"./eventManager.js":48,"./helpers.js":49}],36:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { registerEditor: {get: function() { return registerEditor; }}, getEditor: {get: function() { return getEditor; }}, hasEditor: {get: function() { return hasEditor; }}, getEditorConstructor: {get: function() { return getEditorConstructor; }}, __esModule: {value: true} }); var $__helpers_46_js__; var helper = ($__helpers_46_js__ = require("./helpers.js"), $__helpers_46_js__ && $__helpers_46_js__.__esModule && $__helpers_46_js__ || {default: $__helpers_46_js__}); ; var registeredEditorNames = {}, registeredEditorClasses = new WeakMap(); Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.registerEditor = registerEditor; Handsontable.editors.getEditor = getEditor; function RegisteredEditor(editorClass) { var Clazz, instances; instances = {}; Clazz = editorClass; this.getConstructor = function() { return editorClass; }; this.getInstance = function(hotInstance) { if (!(hotInstance.guid in instances)) { instances[hotInstance.guid] = new Clazz(hotInstance); } return instances[hotInstance.guid]; }; } function registerEditor(editorName, editorClass) { var editor = new RegisteredEditor(editorClass); if (typeof editorName === "string") { registeredEditorNames[editorName] = editor; } registeredEditorClasses.set(editorClass, editor); } function getEditor(editorName, hotInstance) { var editor; if (typeof editorName == 'function') { if (!(registeredEditorClasses.get(editorName))) { registerEditor(null, editorName); } editor = registeredEditorClasses.get(editorName); } else if (typeof editorName == 'string') { editor = registeredEditorNames[editorName]; } else { throw Error('Only strings and functions can be passed as "editor" parameter '); } if (!editor) { throw Error('No editor registered under name "' + editorName + '"'); } return editor.getInstance(hotInstance); } function getEditorConstructor(editorName) { var editor; if (typeof editorName == 'string') { editor = registeredEditorNames[editorName]; } else { throw Error('Only strings and functions can be passed as "editor" parameter '); } if (!editor) { throw Error('No editor registered under name "' + editorName + '"'); } return editor.getConstructor(); } function hasEditor(editorName) { return registeredEditorNames[editorName] ? true : false; } //# },{"./helpers.js":49}],37:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { BaseEditor: {get: function() { return BaseEditor; }}, __esModule: {value: true} }); var $___46__46__47_helpers_46_js__, $___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__; var helper = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}); var WalkontableCellCoords = ($___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ = require("./../3rdparty/walkontable/src/cellCoords.js"), $___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ && $___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__.__esModule && $___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ || {default: $___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__}).WalkontableCellCoords; ; Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.BaseEditor = BaseEditor; Handsontable.EditorState = { VIRGIN: 'STATE_VIRGIN', EDITING: 'STATE_EDITING', WAITING: 'STATE_WAITING', FINISHED: 'STATE_FINISHED' }; function BaseEditor(instance) { this.instance = instance; this.state = Handsontable.EditorState.VIRGIN; this._opened = false; this._closeCallback = null; this.init(); } BaseEditor.prototype._fireCallbacks = function(result) { if (this._closeCallback) { this._closeCallback(result); this._closeCallback = null; } }; BaseEditor.prototype.init = function() {}; BaseEditor.prototype.getValue = function() { throw Error('Editor getValue() method unimplemented'); }; BaseEditor.prototype.setValue = function(newValue) { throw Error('Editor setValue() method unimplemented'); }; BaseEditor.prototype.open = function() { throw Error('Editor open() method unimplemented'); }; BaseEditor.prototype.close = function() { throw Error('Editor close() method unimplemented'); }; BaseEditor.prototype.prepare = function(row, col, prop, td, originalValue, cellProperties) { this.TD = td; this.row = row; this.col = col; this.prop = prop; this.originalValue = originalValue; this.cellProperties = cellProperties; this.state = Handsontable.EditorState.VIRGIN; }; BaseEditor.prototype.extend = function() { var baseClass = this.constructor; function Editor() { baseClass.apply(this, arguments); } function inherit(Child, Parent) { function Bridge() {} Bridge.prototype = Parent.prototype; Child.prototype = new Bridge(); Child.prototype.constructor = Child; return Child; } return inherit(Editor, baseClass); }; BaseEditor.prototype.saveValue = function(val, ctrlDown) { var sel, tmp; if (ctrlDown) { sel = this.instance.getSelected(); if (sel[0] > sel[2]) { tmp = sel[0]; sel[0] = sel[2]; sel[2] = tmp; } if (sel[1] > sel[3]) { tmp = sel[1]; sel[1] = sel[3]; sel[3] = tmp; } this.instance.populateFromArray(sel[0], sel[1], val, sel[2], sel[3], 'edit'); } else { this.instance.populateFromArray(this.row, this.col, val, null, null, 'edit'); } }; BaseEditor.prototype.beginEditing = function(initialValue, event) { if (this.state != Handsontable.EditorState.VIRGIN) { return; } this.instance.view.scrollViewport(new WalkontableCellCoords(this.row, this.col)); this.instance.view.render(); this.state = Handsontable.EditorState.EDITING; initialValue = typeof initialValue == 'string' ? initialValue : this.originalValue; this.setValue(helper.stringify(initialValue)); this.open(event); this._opened = true; this.focus(); this.instance.view.render(); }; BaseEditor.prototype.finishEditing = function(restoreOriginalValue, ctrlDown, callback) { var _this = this, val; if (callback) { var previousCloseCallback = this._closeCallback; this._closeCallback = function(result) { if (previousCloseCallback) { previousCloseCallback(result); } callback(result); }; } if (this.isWaiting()) { return; } if (this.state == Handsontable.EditorState.VIRGIN) { this.instance._registerTimeout(setTimeout(function() { _this._fireCallbacks(true); }, 0)); return; } if (this.state == Handsontable.EditorState.EDITING) { if (restoreOriginalValue) { this.cancelChanges(); this.instance.view.render(); return; } if (this.instance.getSettings().trimWhitespace) { val = [[typeof this.getValue() === 'string' ? String.prototype.trim.call(this.getValue() || '') : this.getValue()]]; } else { val = [[this.getValue()]]; } this.state = Handsontable.EditorState.WAITING; this.saveValue(val, ctrlDown); if (this.instance.getCellValidator(this.cellProperties)) { this.instance.addHookOnce('postAfterValidate', function(result) { _this.state = Handsontable.EditorState.FINISHED; _this.discardEditor(result); }); } else { this.state = Handsontable.EditorState.FINISHED; this.discardEditor(true); } } }; BaseEditor.prototype.cancelChanges = function() { this.state = Handsontable.EditorState.FINISHED; this.discardEditor(); }; BaseEditor.prototype.discardEditor = function(result) { if (this.state !== Handsontable.EditorState.FINISHED) { return; } if (result === false && this.cellProperties.allowInvalid !== true) { this.instance.selectCell(this.row, this.col); this.focus(); this.state = Handsontable.EditorState.EDITING; this._fireCallbacks(false); } else { this.close(); this._opened = false; this.state = Handsontable.EditorState.VIRGIN; this._fireCallbacks(true); } }; BaseEditor.prototype.isOpened = function() { return this._opened; }; BaseEditor.prototype.isWaiting = function() { return this.state === Handsontable.EditorState.WAITING; }; //# },{"./../3rdparty/walkontable/src/cellCoords.js":8,"./../helpers.js":49}],38:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { AutocompleteEditor: {get: function() { return AutocompleteEditor; }}, __esModule: {value: true} }); var $___46__46__47_helpers_46_js__, $___46__46__47_dom_46_js__, $___46__46__47_editors_46_js__, $__handsontableEditor_46_js__; var helper = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}); var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var $__0 = ($___46__46__47_editors_46_js__ = require("./../editors.js"), $___46__46__47_editors_46_js__ && $___46__46__47_editors_46_js__.__esModule && $___46__46__47_editors_46_js__ || {default: $___46__46__47_editors_46_js__}), getEditorConstructor = $__0.getEditorConstructor, registerEditor = $__0.registerEditor; var HandsontableEditor = ($__handsontableEditor_46_js__ = require("./handsontableEditor.js"), $__handsontableEditor_46_js__ && $__handsontableEditor_46_js__.__esModule && $__handsontableEditor_46_js__ || {default: $__handsontableEditor_46_js__}).HandsontableEditor; var AutocompleteEditor = HandsontableEditor.prototype.extend(); ; Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.AutocompleteEditor = AutocompleteEditor; AutocompleteEditor.prototype.init = function() { HandsontableEditor.prototype.init.apply(this, arguments); this.query = null; this.choices = []; }; AutocompleteEditor.prototype.createElements = function() { HandsontableEditor.prototype.createElements.apply(this, arguments); dom.addClass(this.htContainer, 'autocompleteEditor'); dom.addClass(this.htContainer, window.navigator.platform.indexOf('Mac') !== -1 ? 'htMacScroll' : ''); }; var skipOne = false; function onBeforeKeyDown(event) { skipOne = false; var editor = this.getActiveEditor(); var keyCodes = helper.keyCode; if (helper.isPrintableChar(event.keyCode) || event.keyCode === keyCodes.BACKSPACE || event.keyCode === keyCodes.DELETE || event.keyCode === keyCodes.INSERT) { var timeOffset = 0; if (event.keyCode === keyCodes.C && (event.ctrlKey || event.metaKey)) { return; } if (!editor.isOpened()) { timeOffset += 10; } editor.instance._registerTimeout(setTimeout(function() { editor.queryChoices(editor.TEXTAREA.value); skipOne = true; }, timeOffset)); } } AutocompleteEditor.prototype.prepare = function() { this.instance.addHook('beforeKeyDown', onBeforeKeyDown); HandsontableEditor.prototype.prepare.apply(this, arguments); }; AutocompleteEditor.prototype.open = function() { HandsontableEditor.prototype.open.apply(this, arguments); var choicesListHot = this.htEditor.getInstance(); var that = this; this.TEXTAREA.style.visibility = 'visible'; this.focus(); choicesListHot.updateSettings({ 'colWidths': [dom.outerWidth(this.TEXTAREA) - 2], width: dom.outerWidth(this.TEXTAREA) + dom.getScrollbarWidth() + 2, afterRenderer: function(TD, row, col, prop, value) { var caseSensitive = this.getCellMeta(row, col).filteringCaseSensitive === true, indexOfMatch, match; if (value) { indexOfMatch = caseSensitive ? value.indexOf(this.query) : value.toLowerCase().indexOf(that.query.toLowerCase()); if (indexOfMatch != -1) { match = value.substr(indexOfMatch, that.query.length); TD.innerHTML = value.replace(match, '<strong>' + match + '</strong>'); } } } }); this.htEditor.view.wt.wtTable.holder.parentNode.style['padding-right'] = dom.getScrollbarWidth() + 2 + 'px'; if (skipOne) { skipOne = false; } that.instance._registerTimeout(setTimeout(function() { that.queryChoices(that.TEXTAREA.value); }, 0)); }; AutocompleteEditor.prototype.close = function() { HandsontableEditor.prototype.close.apply(this, arguments); }; AutocompleteEditor.prototype.queryChoices = function(query) { this.query = query; if (typeof this.cellProperties.source == 'function') { var that = this; this.cellProperties.source(query, function(choices) { that.updateChoicesList(choices); }); } else if (Array.isArray(this.cellProperties.source)) { var choices; if (!query || this.cellProperties.filter === false) { choices = this.cellProperties.source; } else { var filteringCaseSensitive = this.cellProperties.filteringCaseSensitive === true; var lowerCaseQuery = query.toLowerCase(); choices = this.cellProperties.source.filter(function(choice) { if (filteringCaseSensitive) { return choice.indexOf(query) != -1; } else { return choice.toLowerCase().indexOf(lowerCaseQuery) != -1; } }); } this.updateChoicesList(choices); } else { this.updateChoicesList([]); } }; AutocompleteEditor.prototype.updateChoicesList = function(choices) { var pos = dom.getCaretPosition(this.TEXTAREA), endPos = dom.getSelectionEndPosition(this.TEXTAREA); var orderByRelevance = AutocompleteEditor.sortByRelevance(this.getValue(), choices, this.cellProperties.filteringCaseSensitive); var highlightIndex; if (this.cellProperties.filter != false) { var sorted = []; for (var i = 0, choicesCount = orderByRelevance.length; i < choicesCount; i++) { sorted.push(choices[orderByRelevance[i]]); } highlightIndex = 0; choices = sorted; } else { highlightIndex = orderByRelevance[0]; } this.choices = choices; this.htEditor.loadData(helper.pivot([choices])); this.updateDropdownHeight(); if (this.cellProperties.strict === true) { this.highlightBestMatchingChoice(highlightIndex); } this.instance.listen(); this.TEXTAREA.focus(); dom.setCaretPosition(this.TEXTAREA, pos, (pos != endPos ? endPos : void 0)); }; AutocompleteEditor.prototype.updateDropdownHeight = function() { this.htEditor.updateSettings({height: this.getDropdownHeight()}); this.htEditor.view.wt.wtTable.alignOverlaysWithTrimmingContainer(); }; AutocompleteEditor.prototype.finishEditing = function(restoreOriginalValue) { if (!restoreOriginalValue) { this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); } HandsontableEditor.prototype.finishEditing.apply(this, arguments); }; AutocompleteEditor.prototype.highlightBestMatchingChoice = function(index) { if (typeof index === "number") { this.htEditor.selectCell(index, 0); } else { this.htEditor.deselectCell(); } }; AutocompleteEditor.sortByRelevance = function(value, choices, caseSensitive) { var choicesRelevance = [], currentItem, valueLength = value.length, valueIndex, charsLeft, result = [], i, choicesCount; if (valueLength === 0) { for (i = 0, choicesCount = choices.length; i < choicesCount; i++) { result.push(i); } return result; } for (i = 0, choicesCount = choices.length; i < choicesCount; i++) { currentItem = choices[i]; if (caseSensitive) { valueIndex = currentItem.indexOf(value); } else { valueIndex = currentItem.toLowerCase().indexOf(value.toLowerCase()); } if (valueIndex == -1) { continue; } charsLeft = currentItem.length - valueIndex - valueLength; choicesRelevance.push({ baseIndex: i, index: valueIndex, charsLeft: charsLeft, value: currentItem }); } choicesRelevance.sort(function(a, b) { if (b.index === -1) { return -1; } if (a.index === -1) { return 1; } if (a.index < b.index) { return -1; } else if (b.index < a.index) { return 1; } else if (a.index === b.index) { if (a.charsLeft < b.charsLeft) { return -1; } else if (a.charsLeft > b.charsLeft) { return 1; } else { return 0; } } }); for (i = 0, choicesCount = choicesRelevance.length; i < choicesCount; i++) { result.push(choicesRelevance[i].baseIndex); } return result; }; AutocompleteEditor.prototype.getDropdownHeight = function() { var firstRowHeight = this.htEditor.getInstance().getRowHeight(0) || 23; return this.choices.length >= 10 ? 10 * firstRowHeight : this.choices.length * firstRowHeight + 8; }; registerEditor('autocomplete', AutocompleteEditor); //# },{"./../dom.js":34,"./../editors.js":36,"./../helpers.js":49,"./handsontableEditor.js":42}],39:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { CheckboxEditor: {get: function() { return CheckboxEditor; }}, __esModule: {value: true} }); var $___46__46__47_editors_46_js__, $___95_baseEditor_46_js__; var registerEditor = ($___46__46__47_editors_46_js__ = require("./../editors.js"), $___46__46__47_editors_46_js__ && $___46__46__47_editors_46_js__.__esModule && $___46__46__47_editors_46_js__ || {default: $___46__46__47_editors_46_js__}).registerEditor; var BaseEditor = ($___95_baseEditor_46_js__ = require("./_baseEditor.js"), $___95_baseEditor_46_js__ && $___95_baseEditor_46_js__.__esModule && $___95_baseEditor_46_js__ || {default: $___95_baseEditor_46_js__}).BaseEditor; var CheckboxEditor = BaseEditor.prototype.extend(); ; Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.CheckboxEditor = CheckboxEditor; CheckboxEditor.prototype.beginEditing = function() { var checkbox = this.TD.querySelector('input[type="checkbox"]'); if (checkbox) { checkbox.click(); } }; CheckboxEditor.prototype.finishEditing = function() {}; CheckboxEditor.prototype.init = function() {}; CheckboxEditor.prototype.open = function() {}; CheckboxEditor.prototype.close = function() {}; CheckboxEditor.prototype.getValue = function() {}; CheckboxEditor.prototype.setValue = function() {}; CheckboxEditor.prototype.focus = function() {}; registerEditor('checkbox', CheckboxEditor); //# },{"./../editors.js":36,"./_baseEditor.js":37}],40:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { DateEditor: {get: function() { return DateEditor; }}, __esModule: {value: true} }); var $___46__46__47_helpers_46_js__, $___46__46__47_dom_46_js__, $___46__46__47_editors_46_js__, $__textEditor_46_js__, $___46__46__47_eventManager_46_js__, $__moment__, $__pikaday__; var helper = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}); var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var $__0 = ($___46__46__47_editors_46_js__ = require("./../editors.js"), $___46__46__47_editors_46_js__ && $___46__46__47_editors_46_js__.__esModule && $___46__46__47_editors_46_js__ || {default: $___46__46__47_editors_46_js__}), getEditor = $__0.getEditor, registerEditor = $__0.registerEditor; var TextEditor = ($__textEditor_46_js__ = require("./textEditor.js"), $__textEditor_46_js__ && $__textEditor_46_js__.__esModule && $__textEditor_46_js__ || {default: $__textEditor_46_js__}).TextEditor; var eventManagerObject = ($___46__46__47_eventManager_46_js__ = require("./../eventManager.js"), $___46__46__47_eventManager_46_js__ && $___46__46__47_eventManager_46_js__.__esModule && $___46__46__47_eventManager_46_js__ || {default: $___46__46__47_eventManager_46_js__}).eventManager; var moment = ($__moment__ = require("moment"), $__moment__ && $__moment__.__esModule && $__moment__ || {default: $__moment__}).default; var Pikaday = ($__pikaday__ = require("pikaday"), $__pikaday__ && $__pikaday__.__esModule && $__pikaday__ || {default: $__pikaday__}).default; var DateEditor = TextEditor.prototype.extend(); ; Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.DateEditor = DateEditor; DateEditor.prototype.init = function() { if (typeof moment !== 'function') { throw new Error("You need to include moment.js to your project."); } if (typeof Pikaday !== 'function') { throw new Error("You need to include Pikaday to your project."); } TextEditor.prototype.init.apply(this, arguments); this.isCellEdited = false; var that = this; this.instance.addHook('afterDestroy', function() { that.parentDestroyed = true; that.destroyElements(); }); }; DateEditor.prototype.createElements = function() { var that = this; TextEditor.prototype.createElements.apply(this, arguments); this.defaultDateFormat = 'DD/MM/YYYY'; this.datePicker = document.createElement('DIV'); this.datePickerStyle = this.datePicker.style; this.datePickerStyle.position = 'absolute'; this.datePickerStyle.top = 0; this.datePickerStyle.left = 0; this.datePickerStyle.zIndex = 9999; dom.addClass(this.datePicker, 'htDatepickerHolder'); document.body.appendChild(this.datePicker); var htInput = this.TEXTAREA; var defaultOptions = { format: that.defaultDateFormat, field: htInput, trigger: htInput, container: that.datePicker, reposition: false, bound: false, onSelect: function(dateStr) { if (!isNaN(dateStr.getTime())) { dateStr = moment(dateStr).format(that.cellProperties.dateFormat || that.defaultDateFormat); } that.setValue(dateStr); that.hideDatepicker(); }, onClose: function() { if (!that.parentDestroyed) { that.finishEditing(false); } } }; this.$datePicker = new Pikaday(defaultOptions); var eventManager = eventManagerObject(this); eventManager.addEventListener(this.datePicker, 'mousedown', function(event) { helper.stopPropagation(event); }); this.hideDatepicker(); }; DateEditor.prototype.destroyElements = function() { this.$datePicker.destroy(); }; DateEditor.prototype.prepare = function() { this._opened = false; TextEditor.prototype.prepare.apply(this, arguments); }; DateEditor.prototype.open = function(event) { TextEditor.prototype.open.call(this); this.showDatepicker(event); }; DateEditor.prototype.close = function() { var that = this; this._opened = false; this.instance._registerTimeout(setTimeout(function() { that.instance.selection.refreshBorders(); }, 0)); TextEditor.prototype.close.apply(this, arguments); }; DateEditor.prototype.finishEditing = function(isCancelled, ctrlDown) { if (isCancelled) { var value = this.originalValue; if (value !== void 0) { this.setValue(value); } } this.hideDatepicker(); TextEditor.prototype.finishEditing.apply(this, arguments); }; DateEditor.prototype.showDatepicker = function(event) { var offset = this.TD.getBoundingClientRect(), dateFormat = this.cellProperties.dateFormat || this.defaultDateFormat, datePickerConfig = this.$datePicker.config(), dateStr, isMouseDown = this.instance.view.isMouseDown(), isMeta = event ? helper.isMetaKey(event.keyCode) : false; this.datePickerStyle.top = (window.pageYOffset + offset.top + dom.outerHeight(this.TD)) + 'px'; this.datePickerStyle.left = (window.pageXOffset + offset.left) + 'px'; this.$datePicker._onInputFocus = function() {}; datePickerConfig.format = dateFormat; if (this.originalValue) { dateStr = this.originalValue; if (moment(dateStr, dateFormat, true).isValid()) { this.$datePicker.setMoment(moment(dateStr, dateFormat), true); } if (!isMeta) { if (!isMouseDown) { this.setValue(''); } } } else { if (this.cellProperties.defaultDate) { dateStr = this.cellProperties.defaultDate; datePickerConfig.defaultDate = dateStr; if (moment(dateStr, dateFormat, true).isValid()) { this.$datePicker.setMoment(moment(dateStr, dateFormat), true); } if (!isMeta) { if (!isMouseDown) { this.setValue(''); } } } } this.datePickerStyle.display = 'block'; this.$datePicker.show(); }; DateEditor.prototype.hideDatepicker = function() { this.datePickerStyle.display = 'none'; this.$datePicker.hide(); }; registerEditor('date', DateEditor); //# },{"./../dom.js":34,"./../editors.js":36,"./../eventManager.js":48,"./../helpers.js":49,"./textEditor.js":47,"moment":"moment","pikaday":"pikaday"}],41:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { DropdownEditor: {get: function() { return DropdownEditor; }}, __esModule: {value: true} }); var $___46__46__47_editors_46_js__, $__autocompleteEditor_46_js__; var $__0 = ($___46__46__47_editors_46_js__ = require("./../editors.js"), $___46__46__47_editors_46_js__ && $___46__46__47_editors_46_js__.__esModule && $___46__46__47_editors_46_js__ || {default: $___46__46__47_editors_46_js__}), getEditor = $__0.getEditor, registerEditor = $__0.registerEditor; var AutocompleteEditor = ($__autocompleteEditor_46_js__ = require("./autocompleteEditor.js"), $__autocompleteEditor_46_js__ && $__autocompleteEditor_46_js__.__esModule && $__autocompleteEditor_46_js__ || {default: $__autocompleteEditor_46_js__}).AutocompleteEditor; var DropdownEditor = AutocompleteEditor.prototype.extend(); ; Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.DropdownEditor = DropdownEditor; DropdownEditor.prototype.prepare = function() { AutocompleteEditor.prototype.prepare.apply(this, arguments); this.cellProperties.filter = false; this.cellProperties.strict = true; }; registerEditor('dropdown', DropdownEditor); //# },{"./../editors.js":36,"./autocompleteEditor.js":38}],42:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { HandsontableEditor: {get: function() { return HandsontableEditor; }}, __esModule: {value: true} }); var $___46__46__47_helpers_46_js__, $___46__46__47_dom_46_js__, $___46__46__47_editors_46_js__, $__textEditor_46_js__; var helper = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}); var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var $__0 = ($___46__46__47_editors_46_js__ = require("./../editors.js"), $___46__46__47_editors_46_js__ && $___46__46__47_editors_46_js__.__esModule && $___46__46__47_editors_46_js__ || {default: $___46__46__47_editors_46_js__}), getEditor = $__0.getEditor, registerEditor = $__0.registerEditor; var TextEditor = ($__textEditor_46_js__ = require("./textEditor.js"), $__textEditor_46_js__ && $__textEditor_46_js__.__esModule && $__textEditor_46_js__ || {default: $__textEditor_46_js__}).TextEditor; var HandsontableEditor = TextEditor.prototype.extend(); ; Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.HandsontableEditor = HandsontableEditor; HandsontableEditor.prototype.createElements = function() { TextEditor.prototype.createElements.apply(this, arguments); var DIV = document.createElement('DIV'); DIV.className = 'handsontableEditor'; this.TEXTAREA_PARENT.appendChild(DIV); this.htContainer = DIV; this.htEditor = new Handsontable(DIV); this.assignHooks(); }; HandsontableEditor.prototype.prepare = function(td, row, col, prop, value, cellProperties) { TextEditor.prototype.prepare.apply(this, arguments); var parent = this; var options = { startRows: 0, startCols: 0, minRows: 0, minCols: 0, className: 'listbox', copyPaste: false, cells: function() { return {readOnly: true}; }, fillHandle: false, afterOnCellMouseDown: function() { var value = this.getValue(); if (value !== void 0) { parent.setValue(value); } parent.instance.destroyEditor(); } }; if (this.cellProperties.handsontable) { helper.extend(options, cellProperties.handsontable); } if (this.htEditor) { this.htEditor.destroy(); } this.htEditor = new Handsontable(this.htContainer, options); }; var onBeforeKeyDown = function(event) { if (event != null && event.isImmediatePropagationEnabled == null) { event.stopImmediatePropagation = function() { this.isImmediatePropagationEnabled = false; this.cancelBubble = true; }; event.isImmediatePropagationEnabled = true; event.isImmediatePropagationStopped = function() { return !this.isImmediatePropagationEnabled; }; } if (event.isImmediatePropagationStopped()) { return; } var editor = this.getActiveEditor(); var innerHOT = editor.htEditor.getInstance(); var rowToSelect; if (event.keyCode == helper.keyCode.ARROW_DOWN) { if (!innerHOT.getSelected()) { rowToSelect = 0; } else { var selectedRow = innerHOT.getSelected()[0]; var lastRow = innerHOT.countRows() - 1; rowToSelect = Math.min(lastRow, selectedRow + 1); } } else if (event.keyCode == helper.keyCode.ARROW_UP) { if (innerHOT.getSelected()) { var selectedRow = innerHOT.getSelected()[0]; rowToSelect = selectedRow - 1; } } if (rowToSelect !== void 0) { if (rowToSelect < 0) { innerHOT.deselectCell(); } else { innerHOT.selectCell(rowToSelect, 0); } event.preventDefault(); event.stopImmediatePropagation(); editor.instance.listen(); editor.TEXTAREA.focus(); } }; HandsontableEditor.prototype.open = function() { this.instance.addHook('beforeKeyDown', onBeforeKeyDown); TextEditor.prototype.open.apply(this, arguments); this.htEditor.render(); if (this.cellProperties.strict) { this.htEditor.selectCell(0, 0); this.TEXTAREA.style.visibility = 'hidden'; } else { this.htEditor.deselectCell(); this.TEXTAREA.style.visibility = 'visible'; } dom.setCaretPosition(this.TEXTAREA, 0, this.TEXTAREA.value.length); }; HandsontableEditor.prototype.close = function() { this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); this.instance.listen(); TextEditor.prototype.close.apply(this, arguments); }; HandsontableEditor.prototype.focus = function() { this.instance.listen(); TextEditor.prototype.focus.apply(this, arguments); }; HandsontableEditor.prototype.beginEditing = function(initialValue) { var onBeginEditing = this.instance.getSettings().onBeginEditing; if (onBeginEditing && onBeginEditing() === false) { return; } TextEditor.prototype.beginEditing.apply(this, arguments); }; HandsontableEditor.prototype.finishEditing = function(isCancelled, ctrlDown) { if (this.htEditor.isListening()) { this.instance.listen(); } if (this.htEditor.getSelected()) { var value = this.htEditor.getInstance().getValue(); if (value !== void 0) { this.setValue(value); } } return TextEditor.prototype.finishEditing.apply(this, arguments); }; HandsontableEditor.prototype.assignHooks = function() { var _this = this; this.instance.addHook('afterDestroy', function() { if (_this.htEditor) { _this.htEditor.destroy(); } }); }; registerEditor('handsontable', HandsontableEditor); //# },{"./../dom.js":34,"./../editors.js":36,"./../helpers.js":49,"./textEditor.js":47}],43:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { MobileTextEditor: {get: function() { return MobileTextEditor; }}, __esModule: {value: true} }); var $___46__46__47_helpers_46_js__, $___46__46__47_dom_46_js__, $___46__46__47_editors_46_js__, $___95_baseEditor_46_js__, $___46__46__47_eventManager_46_js__; var helper = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}); var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var $__0 = ($___46__46__47_editors_46_js__ = require("./../editors.js"), $___46__46__47_editors_46_js__ && $___46__46__47_editors_46_js__.__esModule && $___46__46__47_editors_46_js__ || {default: $___46__46__47_editors_46_js__}), getEditor = $__0.getEditor, registerEditor = $__0.registerEditor; var BaseEditor = ($___95_baseEditor_46_js__ = require("./_baseEditor.js"), $___95_baseEditor_46_js__ && $___95_baseEditor_46_js__.__esModule && $___95_baseEditor_46_js__ || {default: $___95_baseEditor_46_js__}).BaseEditor; var eventManagerObject = ($___46__46__47_eventManager_46_js__ = require("./../eventManager.js"), $___46__46__47_eventManager_46_js__ && $___46__46__47_eventManager_46_js__.__esModule && $___46__46__47_eventManager_46_js__ || {default: $___46__46__47_eventManager_46_js__}).eventManager; var MobileTextEditor = BaseEditor.prototype.extend(), domDimensionsCache = {}; ; Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.MobileTextEditor = MobileTextEditor; var createControls = function() { this.controls = {}; this.controls.leftButton = document.createElement('DIV'); this.controls.leftButton.className = 'leftButton'; this.controls.rightButton = document.createElement('DIV'); this.controls.rightButton.className = 'rightButton'; this.controls.upButton = document.createElement('DIV'); this.controls.upButton.className = 'upButton'; this.controls.downButton = document.createElement('DIV'); this.controls.downButton.className = 'downButton'; for (var button in this.controls) { if (this.controls.hasOwnProperty(button)) { this.positionControls.appendChild(this.controls[button]); } } }; MobileTextEditor.prototype.valueChanged = function() { return this.initValue != this.getValue(); }; MobileTextEditor.prototype.init = function() { var that = this; this.eventManager = eventManagerObject(this.instance); this.createElements(); this.bindEvents(); this.instance.addHook('afterDestroy', function() { that.destroy(); }); }; MobileTextEditor.prototype.getValue = function() { return this.TEXTAREA.value; }; MobileTextEditor.prototype.setValue = function(newValue) { this.initValue = newValue; this.TEXTAREA.value = newValue; }; MobileTextEditor.prototype.createElements = function() { this.editorContainer = document.createElement('DIV'); this.editorContainer.className = "htMobileEditorContainer"; this.cellPointer = document.createElement('DIV'); this.cellPointer.className = "cellPointer"; this.moveHandle = document.createElement('DIV'); this.moveHandle.className = "moveHandle"; this.inputPane = document.createElement('DIV'); this.inputPane.className = "inputs"; this.positionControls = document.createElement('DIV'); this.positionControls.className = "positionControls"; this.TEXTAREA = document.createElement('TEXTAREA'); dom.addClass(this.TEXTAREA, 'handsontableInput'); this.inputPane.appendChild(this.TEXTAREA); this.editorContainer.appendChild(this.cellPointer); this.editorContainer.appendChild(this.moveHandle); this.editorContainer.appendChild(this.inputPane); this.editorContainer.appendChild(this.positionControls); createControls.call(this); document.body.appendChild(this.editorContainer); }; MobileTextEditor.prototype.onBeforeKeyDown = function(event) { var instance = this; var that = instance.getActiveEditor(); dom.enableImmediatePropagation(event); if (event.target !== that.TEXTAREA || event.isImmediatePropagationStopped()) { return; } var keyCodes = helper.keyCode; switch (event.keyCode) { case keyCodes.ENTER: that.close(); event.preventDefault(); break; case keyCodes.BACKSPACE: event.stopImmediatePropagation(); break; } }; MobileTextEditor.prototype.open = function() { this.instance.addHook('beforeKeyDown', this.onBeforeKeyDown); dom.addClass(this.editorContainer, 'active'); dom.removeClass(this.cellPointer, 'hidden'); this.updateEditorPosition(); }; MobileTextEditor.prototype.focus = function() { this.TEXTAREA.focus(); dom.setCaretPosition(this.TEXTAREA, this.TEXTAREA.value.length); }; MobileTextEditor.prototype.close = function() { this.TEXTAREA.blur(); this.instance.removeHook('beforeKeyDown', this.onBeforeKeyDown); dom.removeClass(this.editorContainer, 'active'); }; MobileTextEditor.prototype.scrollToView = function() { var coords = this.instance.getSelectedRange().highlight; this.instance.view.scrollViewport(coords); }; MobileTextEditor.prototype.hideCellPointer = function() { if (!dom.hasClass(this.cellPointer, 'hidden')) { dom.addClass(this.cellPointer, 'hidden'); } }; MobileTextEditor.prototype.updateEditorPosition = function(x, y) { if (x && y) { x = parseInt(x, 10); y = parseInt(y, 10); this.editorContainer.style.top = y + "px"; this.editorContainer.style.left = x + "px"; } else { var selection = this.instance.getSelected(), selectedCell = this.instance.getCell(selection[0], selection[1]); if (!domDimensionsCache.cellPointer) { domDimensionsCache.cellPointer = { height: dom.outerHeight(this.cellPointer), width: dom.outerWidth(this.cellPointer) }; } if (!domDimensionsCache.editorContainer) { domDimensionsCache.editorContainer = {width: dom.outerWidth(this.editorContainer)}; } if (selectedCell !== undefined) { var scrollLeft = this.instance.view.wt.wtOverlays.leftOverlay.trimmingContainer == window ? 0 : dom.getScrollLeft(this.instance.view.wt.wtOverlays.leftOverlay.holder); var scrollTop = this.instance.view.wt.wtOverlays.topOverlay.trimmingContainer == window ? 0 : dom.getScrollTop(this.instance.view.wt.wtOverlays.topOverlay.holder); var selectedCellOffset = dom.offset(selectedCell), selectedCellWidth = dom.outerWidth(selectedCell), currentScrollPosition = { x: scrollLeft, y: scrollTop }; this.editorContainer.style.top = parseInt(selectedCellOffset.top + dom.outerHeight(selectedCell) - currentScrollPosition.y + domDimensionsCache.cellPointer.height, 10) + "px"; this.editorContainer.style.left = parseInt((window.innerWidth / 2) - (domDimensionsCache.editorContainer.width / 2), 10) + "px"; if (selectedCellOffset.left + selectedCellWidth / 2 > parseInt(this.editorContainer.style.left, 10) + domDimensionsCache.editorContainer.width) { this.editorContainer.style.left = window.innerWidth - domDimensionsCache.editorContainer.width + "px"; } else if (selectedCellOffset.left + selectedCellWidth / 2 < parseInt(this.editorContainer.style.left, 10) + 20) { this.editorContainer.style.left = 0 + "px"; } this.cellPointer.style.left = parseInt(selectedCellOffset.left - (domDimensionsCache.cellPointer.width / 2) - dom.offset(this.editorContainer).left + (selectedCellWidth / 2) - currentScrollPosition.x, 10) + "px"; } } }; MobileTextEditor.prototype.updateEditorData = function() { var selected = this.instance.getSelected(), selectedValue = this.instance.getDataAtCell(selected[0], selected[1]); this.row = selected[0]; this.col = selected[1]; this.setValue(selectedValue); this.updateEditorPosition(); }; MobileTextEditor.prototype.prepareAndSave = function() { var val; if (!this.valueChanged()) { return true; } if (this.instance.getSettings().trimWhitespace) { val = [[String.prototype.trim.call(this.getValue())]]; } else { val = [[this.getValue()]]; } this.saveValue(val); }; MobileTextEditor.prototype.bindEvents = function() { var that = this; this.eventManager.addEventListener(this.controls.leftButton, "touchend", function(event) { that.prepareAndSave(); that.instance.selection.transformStart(0, -1, null, true); that.updateEditorData(); event.preventDefault(); }); this.eventManager.addEventListener(this.controls.rightButton, "touchend", function(event) { that.prepareAndSave(); that.instance.selection.transformStart(0, 1, null, true); that.updateEditorData(); event.preventDefault(); }); this.eventManager.addEventListener(this.controls.upButton, "touchend", function(event) { that.prepareAndSave(); that.instance.selection.transformStart(-1, 0, null, true); that.updateEditorData(); event.preventDefault(); }); this.eventManager.addEventListener(this.controls.downButton, "touchend", function(event) { that.prepareAndSave(); that.instance.selection.transformStart(1, 0, null, true); that.updateEditorData(); event.preventDefault(); }); this.eventManager.addEventListener(this.moveHandle, "touchstart", function(event) { if (event.touches.length == 1) { var touch = event.touches[0], onTouchPosition = { x: that.editorContainer.offsetLeft, y: that.editorContainer.offsetTop }, onTouchOffset = { x: touch.pageX - onTouchPosition.x, y: touch.pageY - onTouchPosition.y }; that.eventManager.addEventListener(this, "touchmove", function(event) { var touch = event.touches[0]; that.updateEditorPosition(touch.pageX - onTouchOffset.x, touch.pageY - onTouchOffset.y); that.hideCellPointer(); event.preventDefault(); }); } }); this.eventManager.addEventListener(document.body, "touchend", function(event) { if (!dom.isChildOf(event.target, that.editorContainer) && !dom.isChildOf(event.target, that.instance.rootElement)) { that.close(); } }); this.eventManager.addEventListener(this.instance.view.wt.wtOverlays.leftOverlay.holder, "scroll", function(event) { if (that.instance.view.wt.wtOverlays.leftOverlay.trimmingContainer != window) { that.hideCellPointer(); } }); this.eventManager.addEventListener(this.instance.view.wt.wtOverlays.topOverlay.holder, "scroll", function(event) { if (that.instance.view.wt.wtOverlays.topOverlay.trimmingContainer != window) { that.hideCellPointer(); } }); }; MobileTextEditor.prototype.destroy = function() { this.eventManager.clear(); this.editorContainer.parentNode.removeChild(this.editorContainer); }; registerEditor('mobile', MobileTextEditor); //# },{"./../dom.js":34,"./../editors.js":36,"./../eventManager.js":48,"./../helpers.js":49,"./_baseEditor.js":37}],44:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { NumericEditor: {get: function() { return NumericEditor; }}, __esModule: {value: true} }); var $__numeral__, $___46__46__47_editors_46_js__, $__textEditor_46_js__; var numeral = ($__numeral__ = require("numeral"), $__numeral__ && $__numeral__.__esModule && $__numeral__ || {default: $__numeral__}).default; var $__1 = ($___46__46__47_editors_46_js__ = require("./../editors.js"), $___46__46__47_editors_46_js__ && $___46__46__47_editors_46_js__.__esModule && $___46__46__47_editors_46_js__ || {default: $___46__46__47_editors_46_js__}), getEditor = $__1.getEditor, registerEditor = $__1.registerEditor; var TextEditor = ($__textEditor_46_js__ = require("./textEditor.js"), $__textEditor_46_js__ && $__textEditor_46_js__.__esModule && $__textEditor_46_js__ || {default: $__textEditor_46_js__}).TextEditor; var NumericEditor = TextEditor.prototype.extend(); ; Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.NumericEditor = NumericEditor; NumericEditor.prototype.beginEditing = function(initialValue) { var BaseEditor = TextEditor.prototype; if (typeof(initialValue) === 'undefined' && this.originalValue) { var value = '' + this.originalValue; if (typeof this.cellProperties.language !== 'undefined') { numeral.language(this.cellProperties.language); } var decimalDelimiter = numeral.languageData().delimiters.decimal; value = value.replace('.', decimalDelimiter); BaseEditor.beginEditing.apply(this, [value]); } else { BaseEditor.beginEditing.apply(this, arguments); } }; registerEditor('numeric', NumericEditor); //# },{"./../editors.js":36,"./textEditor.js":47,"numeral":"numeral"}],45:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { PasswordEditor: {get: function() { return PasswordEditor; }}, __esModule: {value: true} }); var $___46__46__47_dom_46_js__, $___46__46__47_editors_46_js__, $__textEditor_46_js__; var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var $__0 = ($___46__46__47_editors_46_js__ = require("./../editors.js"), $___46__46__47_editors_46_js__ && $___46__46__47_editors_46_js__.__esModule && $___46__46__47_editors_46_js__ || {default: $___46__46__47_editors_46_js__}), getEditor = $__0.getEditor, registerEditor = $__0.registerEditor; var TextEditor = ($__textEditor_46_js__ = require("./textEditor.js"), $__textEditor_46_js__ && $__textEditor_46_js__.__esModule && $__textEditor_46_js__ || {default: $__textEditor_46_js__}).TextEditor; var PasswordEditor = TextEditor.prototype.extend(); ; Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.PasswordEditor = PasswordEditor; PasswordEditor.prototype.createElements = function() { TextEditor.prototype.createElements.apply(this, arguments); this.TEXTAREA = document.createElement('input'); this.TEXTAREA.setAttribute('type', 'password'); this.TEXTAREA.className = 'handsontableInput'; this.textareaStyle = this.TEXTAREA.style; this.textareaStyle.width = 0; this.textareaStyle.height = 0; dom.empty(this.TEXTAREA_PARENT); this.TEXTAREA_PARENT.appendChild(this.TEXTAREA); }; registerEditor('password', PasswordEditor); //# },{"./../dom.js":34,"./../editors.js":36,"./textEditor.js":47}],46:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { SelectEditor: {get: function() { return SelectEditor; }}, __esModule: {value: true} }); var $___46__46__47_dom_46_js__, $___46__46__47_helpers_46_js__, $___46__46__47_editors_46_js__, $___95_baseEditor_46_js__; var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var helper = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}); var $__0 = ($___46__46__47_editors_46_js__ = require("./../editors.js"), $___46__46__47_editors_46_js__ && $___46__46__47_editors_46_js__.__esModule && $___46__46__47_editors_46_js__ || {default: $___46__46__47_editors_46_js__}), getEditor = $__0.getEditor, registerEditor = $__0.registerEditor; var BaseEditor = ($___95_baseEditor_46_js__ = require("./_baseEditor.js"), $___95_baseEditor_46_js__ && $___95_baseEditor_46_js__.__esModule && $___95_baseEditor_46_js__ || {default: $___95_baseEditor_46_js__}).BaseEditor; var SelectEditor = BaseEditor.prototype.extend(); ; Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.SelectEditor = SelectEditor; SelectEditor.prototype.init = function() { this.select = document.createElement('SELECT'); dom.addClass(this.select, 'htSelectEditor'); this.select.style.display = 'none'; this.instance.rootElement.appendChild(this.select); }; SelectEditor.prototype.prepare = function() { BaseEditor.prototype.prepare.apply(this, arguments); var selectOptions = this.cellProperties.selectOptions; var options; if (typeof selectOptions == 'function') { options = this.prepareOptions(selectOptions(this.row, this.col, this.prop)); } else { options = this.prepareOptions(selectOptions); } dom.empty(this.select); for (var option in options) { if (options.hasOwnProperty(option)) { var optionElement = document.createElement('OPTION'); optionElement.value = option; dom.fastInnerHTML(optionElement, options[option]); this.select.appendChild(optionElement); } } }; SelectEditor.prototype.prepareOptions = function(optionsToPrepare) { var preparedOptions = {}; if (Array.isArray(optionsToPrepare)) { for (var i = 0, len = optionsToPrepare.length; i < len; i++) { preparedOptions[optionsToPrepare[i]] = optionsToPrepare[i]; } } else if (typeof optionsToPrepare == 'object') { preparedOptions = optionsToPrepare; } return preparedOptions; }; SelectEditor.prototype.getValue = function() { return this.select.value; }; SelectEditor.prototype.setValue = function(value) { this.select.value = value; }; var onBeforeKeyDown = function(event) { var instance = this; var editor = instance.getActiveEditor(); if (event != null && event.isImmediatePropagationEnabled == null) { event.stopImmediatePropagation = function() { this.isImmediatePropagationEnabled = false; }; event.isImmediatePropagationEnabled = true; event.isImmediatePropagationStopped = function() { return !this.isImmediatePropagationEnabled; }; } switch (event.keyCode) { case helper.keyCode.ARROW_UP: var previousOptionIndex = editor.select.selectedIndex - 1; if (previousOptionIndex >= 0) { editor.select[previousOptionIndex].selected = true; } event.stopImmediatePropagation(); event.preventDefault(); break; case helper.keyCode.ARROW_DOWN: var nextOptionIndex = editor.select.selectedIndex + 1; if (nextOptionIndex <= editor.select.length - 1) { editor.select[nextOptionIndex].selected = true; } event.stopImmediatePropagation(); event.preventDefault(); break; } }; SelectEditor.prototype.checkEditorSection = function() { if (this.row < this.instance.getSettings().fixedRowsTop) { if (this.col < this.instance.getSettings().fixedColumnsLeft) { return 'corner'; } else { return 'top'; } } else { if (this.col < this.instance.getSettings().fixedColumnsLeft) { return 'left'; } } }; SelectEditor.prototype.open = function() { var width = dom.outerWidth(this.TD); var height = dom.outerHeight(this.TD); var rootOffset = dom.offset(this.instance.rootElement); var tdOffset = dom.offset(this.TD); var editorSection = this.checkEditorSection(); var cssTransformOffset; switch (editorSection) { case 'top': cssTransformOffset = dom.getCssTransform(this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.holder.parentNode); break; case 'left': cssTransformOffset = dom.getCssTransform(this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.holder.parentNode); break; case 'corner': cssTransformOffset = dom.getCssTransform(this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.holder.parentNode); break; } var selectStyle = this.select.style; if (cssTransformOffset && cssTransformOffset != -1) { selectStyle[cssTransformOffset[0]] = cssTransformOffset[1]; } else { dom.resetCssTransform(this.select); } selectStyle.height = height + 'px'; selectStyle.minWidth = width + 'px'; selectStyle.top = tdOffset.top - rootOffset.top + 'px'; selectStyle.left = tdOffset.left - rootOffset.left + 'px'; selectStyle.margin = '0px'; selectStyle.display = ''; this.instance.addHook('beforeKeyDown', onBeforeKeyDown); }; SelectEditor.prototype.close = function() { this.select.style.display = 'none'; this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; SelectEditor.prototype.focus = function() { this.select.focus(); }; registerEditor('select', SelectEditor); //# },{"./../dom.js":34,"./../editors.js":36,"./../helpers.js":49,"./_baseEditor.js":37}],47:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { TextEditor: {get: function() { return TextEditor; }}, __esModule: {value: true} }); var $___46__46__47_dom_46_js__, $___46__46__47_helpers_46_js__, $___46__46__47_3rdparty_47_autoResize_46_js__, $___95_baseEditor_46_js__, $___46__46__47_eventManager_46_js__, $___46__46__47_editors_46_js__; var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var helper = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}); var autoResize = ($___46__46__47_3rdparty_47_autoResize_46_js__ = require("./../3rdparty/autoResize.js"), $___46__46__47_3rdparty_47_autoResize_46_js__ && $___46__46__47_3rdparty_47_autoResize_46_js__.__esModule && $___46__46__47_3rdparty_47_autoResize_46_js__ || {default: $___46__46__47_3rdparty_47_autoResize_46_js__}).autoResize; var BaseEditor = ($___95_baseEditor_46_js__ = require("./_baseEditor.js"), $___95_baseEditor_46_js__ && $___95_baseEditor_46_js__.__esModule && $___95_baseEditor_46_js__ || {default: $___95_baseEditor_46_js__}).BaseEditor; var eventManagerObject = ($___46__46__47_eventManager_46_js__ = require("./../eventManager.js"), $___46__46__47_eventManager_46_js__ && $___46__46__47_eventManager_46_js__.__esModule && $___46__46__47_eventManager_46_js__ || {default: $___46__46__47_eventManager_46_js__}).eventManager; var $__3 = ($___46__46__47_editors_46_js__ = require("./../editors.js"), $___46__46__47_editors_46_js__ && $___46__46__47_editors_46_js__.__esModule && $___46__46__47_editors_46_js__ || {default: $___46__46__47_editors_46_js__}), getEditor = $__3.getEditor, registerEditor = $__3.registerEditor; var TextEditor = BaseEditor.prototype.extend(); ; Handsontable.editors = Handsontable.editors || {}; Handsontable.editors.TextEditor = TextEditor; TextEditor.prototype.init = function() { var that = this; this.createElements(); this.eventManager = eventManagerObject(this); this.bindEvents(); this.autoResize = autoResize(); this.instance.addHook('afterDestroy', function() { that.destroy(); }); }; TextEditor.prototype.getValue = function() { return this.TEXTAREA.value; }; TextEditor.prototype.setValue = function(newValue) { this.TEXTAREA.value = newValue; }; var onBeforeKeyDown = function onBeforeKeyDown(event) { var instance = this, that = instance.getActiveEditor(), keyCodes, ctrlDown; keyCodes = helper.keyCode; ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; dom.enableImmediatePropagation(event); if (event.target !== that.TEXTAREA || event.isImmediatePropagationStopped()) { return; } if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) { event.stopImmediatePropagation(); return; } switch (event.keyCode) { case keyCodes.ARROW_RIGHT: if (dom.getCaretPosition(that.TEXTAREA) !== that.TEXTAREA.value.length) { event.stopImmediatePropagation(); } break; case keyCodes.ARROW_LEFT: if (dom.getCaretPosition(that.TEXTAREA) !== 0) { event.stopImmediatePropagation(); } break; case keyCodes.ENTER: var selected = that.instance.getSelected(); var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]); if ((ctrlDown && !isMultipleSelection) || event.altKey) { if (that.isOpened()) { var caretPosition = dom.getCaretPosition(that.TEXTAREA), value = that.getValue(); var newValue = value.slice(0, caretPosition) + '\n' + value.slice(caretPosition); that.setValue(newValue); dom.setCaretPosition(that.TEXTAREA, caretPosition + 1); } else { that.beginEditing(that.originalValue + '\n'); } event.stopImmediatePropagation(); } event.preventDefault(); break; case keyCodes.A: case keyCodes.X: case keyCodes.C: case keyCodes.V: if (ctrlDown) { event.stopImmediatePropagation(); } break; case keyCodes.BACKSPACE: case keyCodes.DELETE: case keyCodes.HOME: case keyCodes.END: event.stopImmediatePropagation(); break; } that.autoResize.resize(String.fromCharCode(event.keyCode)); }; TextEditor.prototype.open = function() { this.refreshDimensions(); this.instance.addHook('beforeKeyDown', onBeforeKeyDown); }; TextEditor.prototype.close = function() { this.textareaParentStyle.display = 'none'; this.autoResize.unObserve(); if (document.activeElement === this.TEXTAREA) { this.instance.listen(); } this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; TextEditor.prototype.focus = function() { this.TEXTAREA.focus(); dom.setCaretPosition(this.TEXTAREA, this.TEXTAREA.value.length); }; TextEditor.prototype.createElements = function() { this.TEXTAREA = document.createElement('TEXTAREA'); dom.addClass(this.TEXTAREA, 'handsontableInput'); this.textareaStyle = this.TEXTAREA.style; this.textareaStyle.width = 0; this.textareaStyle.height = 0; this.TEXTAREA_PARENT = document.createElement('DIV'); dom.addClass(this.TEXTAREA_PARENT, 'handsontableInputHolder'); this.textareaParentStyle = this.TEXTAREA_PARENT.style; this.textareaParentStyle.top = 0; this.textareaParentStyle.left = 0; this.textareaParentStyle.display = 'none'; this.TEXTAREA_PARENT.appendChild(this.TEXTAREA); this.instance.rootElement.appendChild(this.TEXTAREA_PARENT); var that = this; this.instance._registerTimeout(setTimeout(function() { that.refreshDimensions(); }, 0)); }; TextEditor.prototype.checkEditorSection = function() { if (this.row < this.instance.getSettings().fixedRowsTop) { if (this.col < this.instance.getSettings().fixedColumnsLeft) { return 'corner'; } else { return 'top'; } } else { if (this.col < this.instance.getSettings().fixedColumnsLeft) { return 'left'; } } }; TextEditor.prototype.getEditedCell = function() { var editorSection = this.checkEditorSection(), editedCell; switch (editorSection) { case 'top': editedCell = this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.getCell({ row: this.row, col: this.col }); this.textareaParentStyle.zIndex = 101; break; case 'corner': editedCell = this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.getCell({ row: this.row, col: this.col }); this.textareaParentStyle.zIndex = 103; break; case 'left': editedCell = this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.getCell({ row: this.row, col: this.col }); this.textareaParentStyle.zIndex = 102; break; default: editedCell = this.instance.getCell(this.row, this.col); this.textareaParentStyle.zIndex = ""; break; } return editedCell != -1 && editedCell != -2 ? editedCell : void 0; }; TextEditor.prototype.refreshDimensions = function() { if (this.state !== Handsontable.EditorState.EDITING) { return; } this.TD = this.getEditedCell(); if (!this.TD) { return; } var currentOffset = dom.offset(this.TD), containerOffset = dom.offset(this.instance.rootElement), scrollableContainer = dom.getScrollableElement(this.TD), editTop = currentOffset.top - containerOffset.top - 1 - (scrollableContainer.scrollTop || 0), editLeft = currentOffset.left - containerOffset.left - 1 - (scrollableContainer.scrollLeft || 0), settings = this.instance.getSettings(), rowHeadersCount = settings.rowHeaders ? 1 : 0, colHeadersCount = settings.colHeaders ? 1 : 0, editorSection = this.checkEditorSection(), backgroundColor = this.TD.style.backgroundColor, cssTransformOffset; switch (editorSection) { case 'top': cssTransformOffset = dom.getCssTransform(this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.holder.parentNode); break; case 'left': cssTransformOffset = dom.getCssTransform(this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.holder.parentNode); break; case 'corner': cssTransformOffset = dom.getCssTransform(this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.holder.parentNode); break; } if (editTop < 0) { editTop = 0; } if (editLeft < 0) { editLeft = 0; } if (colHeadersCount && this.instance.getSelected()[0] === 0) { editTop += 1; } if (rowHeadersCount && this.instance.getSelected()[1] === 0) { editLeft += 1; } if (cssTransformOffset && cssTransformOffset != -1) { this.textareaParentStyle[cssTransformOffset[0]] = cssTransformOffset[1]; } else { dom.resetCssTransform(this.textareaParentStyle); } this.textareaParentStyle.top = editTop + 'px'; this.textareaParentStyle.left = editLeft + 'px'; var cellTopOffset = this.TD.offsetTop - this.instance.view.wt.wtOverlays.topOverlay.getScrollPosition(), cellLeftOffset = this.TD.offsetLeft - this.instance.view.wt.wtOverlays.leftOverlay.getScrollPosition(); var width = dom.innerWidth(this.TD) - 8, maxWidth = this.instance.view.maximumVisibleElementWidth(cellLeftOffset) - 10, height = this.TD.scrollHeight + 1, maxHeight = this.instance.view.maximumVisibleElementHeight(cellTopOffset) - 2; if (parseInt(this.TD.style.borderTopWidth, 10) > 0) { height -= 1; } if (parseInt(this.TD.style.borderLeftWidth, 10) > 0) { if (rowHeadersCount > 0) { width -= 1; } } this.TEXTAREA.style.fontSize = dom.getComputedStyle(this.TD).fontSize; this.TEXTAREA.style.fontFamily = dom.getComputedStyle(this.TD).fontFamily; this.TEXTAREA.style.backgroundColor = ''; this.TEXTAREA.style.backgroundColor = backgroundColor ? backgroundColor : dom.getComputedStyle(this.TEXTAREA).backgroundColor; this.autoResize.init(this.TEXTAREA, { minHeight: Math.min(height, maxHeight), maxHeight: maxHeight, minWidth: Math.min(width, maxWidth), maxWidth: maxWidth }, true); this.textareaParentStyle.display = 'block'; }; TextEditor.prototype.bindEvents = function() { var editor = this; this.eventManager.addEventListener(this.TEXTAREA, 'cut', function(event) { helper.stopPropagation(event); }); this.eventManager.addEventListener(this.TEXTAREA, 'paste', function(event) { helper.stopPropagation(event); }); this.instance.addHook('afterScrollVertically', function() { editor.refreshDimensions(); }); this.instance.addHook('afterColumnResize', function() { editor.refreshDimensions(); editor.focus(); }); this.instance.addHook('afterRowResize', function() { editor.refreshDimensions(); editor.focus(); }); this.instance.addHook('afterDestroy', function() { editor.eventManager.clear(); }); }; TextEditor.prototype.destroy = function() { this.eventManager.clear(); }; registerEditor('text', TextEditor); //# },{"./../3rdparty/autoResize.js":2,"./../dom.js":34,"./../editors.js":36,"./../eventManager.js":48,"./../helpers.js":49,"./_baseEditor.js":37}],48:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { eventManager: {get: function() { return eventManager; }}, __esModule: {value: true} }); var $__dom_46_js__; var dom = ($__dom_46_js__ = require("./dom.js"), $__dom_46_js__ && $__dom_46_js__.__esModule && $__dom_46_js__ || {default: $__dom_46_js__}); ; window.Handsontable = window.Handsontable || {}; Handsontable.countEventManagerListeners = 0; Handsontable.eventManager = eventManager; function eventManager(instance) { if (!instance) { throw new Error('instance not defined'); } if (!instance.eventListeners) { instance.eventListeners = []; } function extendEvent(event) { var componentName = 'HOT-TABLE', isHotTableSpotted, fromElement, realTarget, target, len; event.isTargetWebComponent = false; event.realTarget = event.target; if (!Handsontable.eventManager.isHotTableEnv) { return event; } event = dom.polymerWrap(event); len = event.path.length; while (len--) { if (event.path[len].nodeName === componentName) { isHotTableSpotted = true; } else if (isHotTableSpotted && event.path[len].shadowRoot) { target = event.path[len]; break; } if (len === 0 && !target) { target = event.path[len]; } } if (!target) { target = event.target; } event.isTargetWebComponent = true; if (dom.isWebComponentSupportedNatively()) { event.realTarget = event.srcElement || event.toElement; } else if (instance instanceof Handsontable.Core || instance instanceof Walkontable) { if (instance instanceof Handsontable.Core) { fromElement = instance.view.wt.wtTable.TABLE; } else if (instance instanceof Walkontable) { fromElement = instance.wtTable.TABLE.parentNode.parentNode; } realTarget = dom.closest(event.target, [componentName], fromElement); if (realTarget) { event.realTarget = fromElement.querySelector(componentName) || event.target; } else { event.realTarget = event.target; } } Object.defineProperty(event, 'target', { get: function() { return dom.polymerWrap(target); }, enumerable: true, configurable: true }); return event; } function addEvent(element, event, callback) { var callbackProxy; callbackProxy = function callbackProxy(event) { if (event.target == void 0 && event.srcElement != void 0) { if (event.definePoperty) { event.definePoperty('target', {value: event.srcElement}); } else { event.target = event.srcElement; } } if (event.preventDefault == void 0) { if (event.definePoperty) { event.definePoperty('preventDefault', {value: function() { this.returnValue = false; }}); } else { event.preventDefault = function() { this.returnValue = false; }; } } event = extendEvent(event); callback.call(this, event); }; instance.eventListeners.push({ element: element, event: event, callback: callback, callbackProxy: callbackProxy }); if (window.addEventListener) { element.addEventListener(event, callbackProxy, false); } else { element.attachEvent('on' + event, callbackProxy); } Handsontable.countEventManagerListeners++; return function _removeEvent() { removeEvent(element, event, callback); }; } function removeEvent(element, event, callback) { var len = instance.eventListeners.length, tmpEvent; while (len--) { tmpEvent = instance.eventListeners[len]; if (tmpEvent.event == event && tmpEvent.element == element) { if (callback && callback != tmpEvent.callback) { continue; } instance.eventListeners.splice(len, 1); if (tmpEvent.element.removeEventListener) { tmpEvent.element.removeEventListener(tmpEvent.event, tmpEvent.callbackProxy, false); } else { tmpEvent.element.detachEvent('on' + tmpEvent.event, tmpEvent.callbackProxy); } Handsontable.countEventManagerListeners--; } } } function clearEvents() { var len = instance.eventListeners.length, event; while (len--) { event = instance.eventListeners[len]; if (event) { removeEvent(event.element, event.event, event.callback); } } } function fireEvent(element, type) { var options = { bubbles: true, cancelable: (type !== "mousemove"), view: window, detail: 0, screenX: 0, screenY: 0, clientX: 1, clientY: 1, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, button: 0, relatedTarget: undefined }; var event; if (document.createEvent) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, options.relatedTarget || document.body.parentNode); } else { event = document.createEventObject(); } if (element.dispatchEvent) { element.dispatchEvent(event); } else { element.fireEvent('on' + type, event); } } return { addEventListener: addEvent, removeEventListener: removeEvent, clear: clearEvents, fireEvent: fireEvent }; } //# },{"./dom.js":34}],49:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { isPrintableChar: {get: function() { return isPrintableChar; }}, isMetaKey: {get: function() { return isMetaKey; }}, isCtrlKey: {get: function() { return isCtrlKey; }}, stringify: {get: function() { return stringify; }}, toUpperCaseFirst: {get: function() { return toUpperCaseFirst; }}, duckSchema: {get: function() { return duckSchema; }}, spreadsheetColumnLabel: {get: function() { return spreadsheetColumnLabel; }}, createSpreadsheetData: {get: function() { return createSpreadsheetData; }}, createSpreadsheetObjectData: {get: function() { return createSpreadsheetObjectData; }}, isNumeric: {get: function() { return isNumeric; }}, randomString: {get: function() { return randomString; }}, inherit: {get: function() { return inherit; }}, extend: {get: function() { return extend; }}, deepExtend: {get: function() { return deepExtend; }}, deepClone: {get: function() { return deepClone; }}, isObjectEquals: {get: function() { return isObjectEquals; }}, getPrototypeOf: {get: function() { return getPrototypeOf; }}, columnFactory: {get: function() { return columnFactory; }}, translateRowsToColumns: {get: function() { return translateRowsToColumns; }}, to2dArray: {get: function() { return to2dArray; }}, extendArray: {get: function() { return extendArray; }}, isInput: {get: function() { return isInput; }}, isOutsideInput: {get: function() { return isOutsideInput; }}, keyCode: {get: function() { return keyCode; }}, isObject: {get: function() { return isObject; }}, pivot: {get: function() { return pivot; }}, proxy: {get: function() { return proxy; }}, cellMethodLookupFactory: {get: function() { return cellMethodLookupFactory; }}, isMobileBrowser: {get: function() { return isMobileBrowser; }}, isTouchSupported: {get: function() { return isTouchSupported; }}, stopPropagation: {get: function() { return stopPropagation; }}, pageX: {get: function() { return pageX; }}, pageY: {get: function() { return pageY; }}, defineGetter: {get: function() { return defineGetter; }}, __esModule: {value: true} }); var $__dom_46_js__; var dom = ($__dom_46_js__ = require("./dom.js"), $__dom_46_js__ && $__dom_46_js__.__esModule && $__dom_46_js__ || {default: $__dom_46_js__}); function isPrintableChar(keyCode) { return ((keyCode == 32) || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 111) || (keyCode >= 186 && keyCode <= 192) || (keyCode >= 219 && keyCode <= 222) || keyCode >= 226 || (keyCode >= 65 && keyCode <= 90)); } function isMetaKey(_keyCode) { var metaKeys = [keyCode.ARROW_DOWN, keyCode.ARROW_UP, keyCode.ARROW_LEFT, keyCode.ARROW_RIGHT, keyCode.HOME, keyCode.END, keyCode.DELETE, keyCode.BACKSPACE, keyCode.F1, keyCode.F2, keyCode.F3, keyCode.F4, keyCode.F5, keyCode.F6, keyCode.F7, keyCode.F8, keyCode.F9, keyCode.F10, keyCode.F11, keyCode.F12, keyCode.TAB, keyCode.PAGE_DOWN, keyCode.PAGE_UP, keyCode.ENTER, keyCode.ESCAPE, keyCode.SHIFT, keyCode.CAPS_LOCK, keyCode.ALT]; return metaKeys.indexOf(_keyCode) != -1; } function isCtrlKey(_keyCode) { return [keyCode.CONTROL_LEFT, 224, keyCode.COMMAND_LEFT, keyCode.COMMAND_RIGHT].indexOf(_keyCode) != -1; } function stringify(value) { switch (typeof value) { case 'string': case 'number': return value + ''; case 'object': if (value === null) { return ''; } else { return value.toString(); } break; case 'undefined': return ''; default: return value.toString(); } } function toUpperCaseFirst(string) { return string[0].toUpperCase() + string.substr(1); } function duckSchema(object) { var schema; if (Array.isArray(object)) { schema = []; } else { schema = {}; for (var i in object) { if (object.hasOwnProperty(i)) { if (object[i] && typeof object[i] === 'object' && !Array.isArray(object[i])) { schema[i] = duckSchema(object[i]); } else if (Array.isArray(object[i])) { if (object[i].length && typeof object[i][0] === 'object' && !Array.isArray(object[i][0])) { schema[i] = [duckSchema(object[i][0])]; } else { schema[i] = []; } } else { schema[i] = null; } } } } return schema; } function spreadsheetColumnLabel(index) { var dividend = index + 1; var columnLabel = ''; var modulo; while (dividend > 0) { modulo = (dividend - 1) % 26; columnLabel = String.fromCharCode(65 + modulo) + columnLabel; dividend = parseInt((dividend - modulo) / 26, 10); } return columnLabel; } function createSpreadsheetData(rowCount, colCount) { rowCount = typeof rowCount === 'number' ? rowCount : 100; colCount = typeof colCount === 'number' ? colCount : 4; var rows = [], i, j; for (i = 0; i < rowCount; i++) { var row = []; for (j = 0; j < colCount; j++) { row.push(spreadsheetColumnLabel(j) + (i + 1)); } rows.push(row); } return rows; } function createSpreadsheetObjectData(rowCount, colCount) { rowCount = typeof rowCount === 'number' ? rowCount : 100; colCount = typeof colCount === 'number' ? colCount : 4; var rows = [], i, j; for (i = 0; i < rowCount; i++) { var row = {}; for (j = 0; j < colCount; j++) { row['prop' + j] = spreadsheetColumnLabel(j) + (i + 1); } rows.push(row); } return rows; } function isNumeric(n) { var t = typeof n; return t == 'number' ? !isNaN(n) && isFinite(n) : t == 'string' ? !n.length ? false : n.length == 1 ? /\d/.test(n) : /^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) : t == 'object' ? !!n && typeof n.valueOf() == "number" && !(n instanceof Date) : false; } function randomString() { function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } return s4() + s4() + s4() + s4(); } function inherit(Child, Parent) { Parent.prototype.constructor = Parent; Child.prototype = new Parent(); Child.prototype.constructor = Child; return Child; } function extend(target, extension) { for (var i in extension) { if (extension.hasOwnProperty(i)) { target[i] = extension[i]; } } } function deepExtend(target, extension) { for (var key in extension) { if (extension.hasOwnProperty(key)) { if (extension[key] && typeof extension[key] === 'object') { if (!target[key]) { if (Array.isArray(extension[key])) { target[key] = []; } else { target[key] = {}; } } deepExtend(target[key], extension[key]); } else { target[key] = extension[key]; } } } } function deepClone(obj) { if (typeof obj === "object") { return JSON.parse(JSON.stringify(obj)); } else { return obj; } } function isObjectEquals(object1, object2) { return JSON.stringify(object1) === JSON.stringify(object2); } function getPrototypeOf(obj) { var prototype; if (typeof obj.__proto__ == "object") { prototype = obj.__proto__; } else { var oldConstructor, constructor = obj.constructor; if (typeof obj.constructor == "function") { oldConstructor = constructor; if (delete obj.constructor) { constructor = obj.constructor; obj.constructor = oldConstructor; } } prototype = constructor ? constructor.prototype : null; } return prototype; } function columnFactory(GridSettings, conflictList) { function ColumnSettings() {} inherit(ColumnSettings, GridSettings); for (var i = 0, len = conflictList.length; i < len; i++) { ColumnSettings.prototype[conflictList[i]] = void 0; } return ColumnSettings; } function translateRowsToColumns(input) { var i, ilen, j, jlen, output = [], olen = 0; for (i = 0, ilen = input.length; i < ilen; i++) { for (j = 0, jlen = input[i].length; j < jlen; j++) { if (j == olen) { output.push([]); olen++; } output[j].push(input[i][j]); } } return output; } function to2dArray(arr) { var i = 0, ilen = arr.length; while (i < ilen) { arr[i] = [arr[i]]; i++; } } function extendArray(arr, extension) { var i = 0, ilen = extension.length; while (i < ilen) { arr.push(extension[i]); i++; } } function isInput(element) { var inputs = ['INPUT', 'SELECT', 'TEXTAREA']; return inputs.indexOf(element.nodeName) > -1; } function isOutsideInput(element) { return isInput(element) && element.className.indexOf('handsontableInput') == -1; } var keyCode = { MOUSE_LEFT: 1, MOUSE_RIGHT: 3, MOUSE_MIDDLE: 2, BACKSPACE: 8, COMMA: 188, INSERT: 45, DELETE: 46, END: 35, ENTER: 13, ESCAPE: 27, CONTROL_LEFT: 91, COMMAND_LEFT: 17, COMMAND_RIGHT: 93, ALT: 18, HOME: 36, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, SPACE: 32, SHIFT: 16, CAPS_LOCK: 20, TAB: 9, ARROW_RIGHT: 39, ARROW_LEFT: 37, ARROW_UP: 38, ARROW_DOWN: 40, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123, A: 65, X: 88, C: 67, V: 86 }; function isObject(obj) { return Object.prototype.toString.call(obj) == '[object Object]'; } function pivot(arr) { var pivotedArr = []; if (!arr || arr.length === 0 || !arr[0] || arr[0].length === 0) { return pivotedArr; } var rowCount = arr.length; var colCount = arr[0].length; for (var i = 0; i < rowCount; i++) { for (var j = 0; j < colCount; j++) { if (!pivotedArr[j]) { pivotedArr[j] = []; } pivotedArr[j][i] = arr[i][j]; } } return pivotedArr; } function proxy(fun, context) { return function() { return fun.apply(context, arguments); }; } function cellMethodLookupFactory(methodName, allowUndefined) { allowUndefined = typeof allowUndefined == 'undefined' ? true : allowUndefined; return function cellMethodLookup(row, col) { return (function getMethodFromProperties(properties) { if (!properties) { return; } else if (properties.hasOwnProperty(methodName) && properties[methodName] !== void 0) { return properties[methodName]; } else if (properties.hasOwnProperty('type') && properties.type) { var type; if (typeof properties.type != 'string') { throw new Error('Cell type must be a string '); } type = translateTypeNameToObject(properties.type); if (type.hasOwnProperty(methodName)) { return type[methodName]; } else if (allowUndefined) { return; } } return getMethodFromProperties(getPrototypeOf(properties)); })(typeof row == 'number' ? this.getCellMeta(row, col) : row); }; function translateTypeNameToObject(typeName) { var type = Handsontable.cellTypes[typeName]; if (typeof type == 'undefined') { throw new Error('You declared cell type "' + typeName + '" as a string that is not mapped to a known object. ' + 'Cell type must be an object or a string mapped to an object in Handsontable.cellTypes'); } return type; } } function isMobileBrowser(userAgent) { if (!userAgent) { userAgent = navigator.userAgent; } return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)); } function isTouchSupported() { return ('ontouchstart' in window); } function stopPropagation(event) { if (typeof(event.stopPropagation) === 'function') { event.stopPropagation(); } else { event.cancelBubble = true; } } function pageX(event) { if (event.pageX) { return event.pageX; } var scrollLeft = dom.getWindowScrollLeft(); var cursorX = event.clientX + scrollLeft; return cursorX; } function pageY(event) { if (event.pageY) { return event.pageY; } var scrollTop = dom.getWindowScrollTop(); var cursorY = event.clientY + scrollTop; return cursorY; } function defineGetter(object, property, value, options) { options.value = value; options.writable = options.writable === false ? false : true; options.enumerable = options.enumerable === false ? false : true; options.configurable = options.configurable === false ? false : true; Object.defineProperty(object, property, options); } window.Handsontable = window.Handsontable || {}; Handsontable.helper = { cellMethodLookupFactory: cellMethodLookupFactory, columnFactory: columnFactory, createSpreadsheetData: createSpreadsheetData, createSpreadsheetObjectData: createSpreadsheetObjectData, duckSchema: duckSchema, deepClone: deepClone, deepExtend: deepExtend, defineGetter: defineGetter, extend: extend, extendArray: extendArray, getPrototypeOf: getPrototypeOf, inherit: inherit, isCtrlKey: isCtrlKey, isInput: isInput, isMetaKey: isMetaKey, isMobileBrowser: isMobileBrowser, isNumeric: isNumeric, isObject: isObject, isObjectEquals: isObjectEquals, isOutsideInput: isOutsideInput, isPrintableChar: isPrintableChar, isTouchSupported: isTouchSupported, keyCode: keyCode, pageX: pageX, pageY: pageY, pivot: pivot, proxy: proxy, randomString: randomString, spreadsheetColumnLabel: spreadsheetColumnLabel, stopPropagation: stopPropagation, stringify: stringify, to2dArray: to2dArray, toUpperCaseFirst: toUpperCaseFirst, translateRowsToColumns: translateRowsToColumns }; //# },{"./dom.js":34}],50:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { MultiMap: {get: function() { return MultiMap; }}, __esModule: {value: true} }); ; window.MultiMap = MultiMap; function MultiMap() { var map = { arrayMap: [], weakMap: new WeakMap() }; return { 'get': function(key) { if (canBeAnArrayMapKey(key)) { return map.arrayMap[key]; } else if (canBeAWeakMapKey(key)) { return map.weakMap.get(key); } }, 'set': function(key, value) { if (canBeAnArrayMapKey(key)) { map.arrayMap[key] = value; } else if (canBeAWeakMapKey(key)) { map.weakMap.set(key, value); } else { throw new Error('Invalid key type'); } }, 'delete': function(key) { if (canBeAnArrayMapKey(key)) { delete map.arrayMap[key]; } else if (canBeAWeakMapKey(key)) { map.weakMap['delete'](key); } } }; function canBeAnArrayMapKey(obj) { return obj !== null && !isNaNSymbol(obj) && (typeof obj == 'string' || typeof obj == 'number'); } function canBeAWeakMapKey(obj) { return obj !== null && (typeof obj == 'object' || typeof obj == 'function'); } function isNaNSymbol(obj) { return obj !== obj; } } //# },{}],51:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { PluginHook: {get: function() { return PluginHook; }}, __esModule: {value: true} }); ; var Hooks = function() { return { beforeInitWalkontable: [], beforeInit: [], beforeRender: [], beforeSetRangeEnd: [], beforeDrawBorders: [], beforeChange: [], beforeChangeRender: [], beforeRemoveCol: [], beforeRemoveRow: [], beforeValidate: [], beforeGetCellMeta: [], beforeAutofill: [], beforeKeyDown: [], beforeOnCellMouseDown: [], beforeTouchScroll: [], afterInit: [], afterLoadData: [], afterUpdateSettings: [], afterRender: [], afterRenderer: [], afterChange: [], afterValidate: [], afterGetCellMeta: [], afterSetCellMeta: [], afterGetColHeader: [], afterGetRowHeader: [], afterDestroy: [], afterRemoveRow: [], afterCreateRow: [], afterRemoveCol: [], afterCreateCol: [], afterDeselect: [], afterSelection: [], afterSelectionByProp: [], afterSelectionEnd: [], afterSelectionEndByProp: [], afterOnCellMouseDown: [], afterOnCellMouseOver: [], afterOnCellCornerMouseDown: [], afterScrollVertically: [], afterScrollHorizontally: [], afterCellMetaReset: [], afterIsMultipleSelectionCheck: [], afterDocumentKeyDown: [], afterMomentumScroll: [], beforeCellAlignment: [], modifyColWidth: [], modifyRowHeight: [], modifyRow: [], modifyCol: [] }; }; var legacy = { onBeforeChange: "beforeChange", onChange: "afterChange", onCreateRow: "afterCreateRow", onCreateCol: "afterCreateCol", onSelection: "afterSelection", onCopyLimit: "afterCopyLimit", onSelectionEnd: "afterSelectionEnd", onSelectionByProp: "afterSelectionByProp", onSelectionEndByProp: "afterSelectionEndByProp" }; function PluginHook() { this.hooks = Hooks(); this.globalBucket = {}; this.legacy = legacy; } PluginHook.prototype.getBucket = function(instance) { if (instance) { if (!instance.pluginHookBucket) { instance.pluginHookBucket = {}; } return instance.pluginHookBucket; } return this.globalBucket; }; PluginHook.prototype.add = function(key, fn, instance) { if (Array.isArray(fn)) { for (var i = 0, len = fn.length; i < len; i++) { this.add(key, fn[i]); } } else { if (key in legacy) { key = legacy[key]; } var bucket = this.getBucket(instance); if (typeof bucket[key] === 'undefined') { bucket[key] = []; } fn.skip = false; if (bucket[key].indexOf(fn) === -1) { bucket[key].push(fn); } } return this; }; PluginHook.prototype.once = function(key, fn, instance) { if (Array.isArray(fn)) { for (var i = 0, len = fn.length; i < len; i++) { fn[i].runOnce = true; this.add(key, fn[i], instance); } } else { fn.runOnce = true; this.add(key, fn, instance); } }; PluginHook.prototype.remove = function(key, fn, instance) { var status = false; if (key in legacy) { key = legacy[key]; } var bucket = this.getBucket(instance); if (typeof bucket[key] !== 'undefined') { for (var i = 0, leni = bucket[key].length; i < leni; i++) { if (bucket[key][i] == fn) { bucket[key][i].skip = true; status = true; break; } } } return status; }; PluginHook.prototype.run = function(instance, key, p1, p2, p3, p4, p5, p6) { if (legacy[key]) { key = legacy[key]; } p1 = this._runBucket(this.globalBucket, instance, key, p1, p2, p3, p4, p5, p6); p1 = this._runBucket(this.getBucket(instance), instance, key, p1, p2, p3, p4, p5, p6); return p1; }; PluginHook.prototype._runBucket = function(bucket, instance, key, p1, p2, p3, p4, p5, p6) { var handlers = bucket[key], res, i, len; if (handlers) { for (i = 0, len = handlers.length; i < len; i++) { if (!handlers[i].skip) { res = handlers[i].call(instance, p1, p2, p3, p4, p5, p6); if (res !== void 0) { p1 = res; } if (handlers[i].runOnce) { this.remove(key, handlers[i], bucket === this.globalBucket ? null : instance); } } } } return p1; }; PluginHook.prototype.destroy = function(instance) { var bucket = this.getBucket(instance); for (var key in bucket) { if (bucket.hasOwnProperty(key)) { for (var i = 0, leni = bucket[key].length; i < leni; i++) { this.remove(key, bucket[key], instance); } } } }; PluginHook.prototype.register = function(key) { if (!this.isRegistered(key)) { this.hooks[key] = []; } }; PluginHook.prototype.deregister = function(key) { delete this.hooks[key]; }; PluginHook.prototype.isRegistered = function(key) { return (typeof this.hooks[key] !== "undefined"); }; PluginHook.prototype.getRegistered = function() { return Object.keys(this.hooks); }; //# },{}],52:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { registerPlugin: {get: function() { return registerPlugin; }}, getPlugin: {get: function() { return getPlugin; }}, __esModule: {value: true} }); ; var registeredPlugins = new WeakMap(); function registerPlugin(pluginName, PluginClass) { Handsontable.hooks.add('beforeInit', function() { var holder; if (!registeredPlugins.has(this)) { registeredPlugins.set(this, {}); } holder = registeredPlugins.get(this); if (!holder[pluginName]) { holder[pluginName] = new PluginClass(this); } }); Handsontable.hooks.add('afterDestroy', function() { var i, pluginsHolder; if (registeredPlugins.has(this)) { pluginsHolder = registeredPlugins.get(this); for (i in pluginsHolder) { if (pluginsHolder.hasOwnProperty(i) && pluginsHolder[i].destroy) { pluginsHolder[i].destroy(); } } registeredPlugins.delete(this); } }); } function getPlugin(instance, pluginName) { if (typeof pluginName != 'string') { throw Error('Only strings can be passed as "plugin" parameter'); } if (!registeredPlugins.has(instance) || !registeredPlugins.get(instance)[pluginName]) { throw Error('No plugin registered under name "' + pluginName + '"'); } return registeredPlugins.get(instance)[pluginName]; } //# },{}],53:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { default: {get: function() { return $__default; }}, __esModule: {value: true} }); var $___46__46__47_helpers_46_js__; var defineGetter = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}).defineGetter; var BasePlugin = function BasePlugin(hotInstance) { defineGetter(this, 'hot', hotInstance, {writable: false}); }; ($traceurRuntime.createClass)(BasePlugin, {destroy: function() { delete this.hot; }}, {}); var $__default = BasePlugin; //# },{"./../helpers.js":49}],54:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { AutoColumnSize: {get: function() { return AutoColumnSize; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_helpers_46_js__, $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_plugins_46_js__; var helper = ($___46__46__47__46__46__47_helpers_46_js__ = require("./../../helpers.js"), $___46__46__47__46__46__47_helpers_46_js__ && $___46__46__47__46__46__47_helpers_46_js__.__esModule && $___46__46__47__46__46__47_helpers_46_js__ || {default: $___46__46__47__46__46__47_helpers_46_js__}); var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; function AutoColumnSize() { var plugin = this, sampleCount = 5; this.beforeInit = function() { var instance = this; instance.autoColumnWidths = []; if (instance.getSettings().autoColumnSize !== false) { if (!instance.autoColumnSizeTmp) { instance.autoColumnSizeTmp = { table: null, tableStyle: null, theadTh: null, tbody: null, container: null, containerStyle: null, determineBeforeNextRender: true }; instance.addHook('beforeRender', htAutoColumnSize.determineIfChanged); instance.addHook('modifyColWidth', htAutoColumnSize.modifyColWidth); instance.addHook('afterDestroy', htAutoColumnSize.afterDestroy); instance.determineColumnWidth = plugin.determineColumnWidth; } } else { if (instance.autoColumnSizeTmp) { instance.removeHook('beforeRender', htAutoColumnSize.determineIfChanged); instance.removeHook('modifyColWidth', htAutoColumnSize.modifyColWidth); instance.removeHook('afterDestroy', htAutoColumnSize.afterDestroy); delete instance.determineColumnWidth; plugin.afterDestroy.call(instance); } } }; this.determineIfChanged = function(force) { if (force) { htAutoColumnSize.determineColumnsWidth.apply(this, arguments); } }; this.determineColumnWidth = function(col) { var instance = this, tmp = instance.autoColumnSizeTmp; if (!tmp.container) { createTmpContainer.call(tmp, instance); } tmp.container.className = instance.rootElement.className + ' htAutoColumnSize'; tmp.table.className = instance.table.className; var rows = instance.countRows(); var samples = {}; for (var r = 0; r < rows; r++) { var value = instance.getDataAtCell(r, col); if (!Array.isArray(value)) { value = helper.stringify(value); } var len = value.length; if (!samples[len]) { samples[len] = { needed: sampleCount, strings: [] }; } if (samples[len].needed) { samples[len].strings.push({ value: value, row: r }); samples[len].needed--; } } var settings = instance.getSettings(); if (settings.colHeaders) { instance.view.appendColHeader(col, tmp.theadTh); } dom.empty(tmp.tbody); for (var i in samples) { if (samples.hasOwnProperty(i)) { for (var j = 0, jlen = samples[i].strings.length; j < jlen; j++) { var row = samples[i].strings[j].row; var cellProperties = instance.getCellMeta(row, col); cellProperties.col = col; cellProperties.row = row; var renderer = instance.getCellRenderer(cellProperties); var tr = document.createElement('tr'); var td = document.createElement('td'); renderer(instance, td, row, col, instance.colToProp(col), samples[i].strings[j].value, cellProperties); r++; tr.appendChild(td); tmp.tbody.appendChild(tr); } } } var parent = instance.rootElement.parentNode; parent.appendChild(tmp.container); var width = dom.outerWidth(tmp.table); parent.removeChild(tmp.container); return width; }; this.determineColumnsWidth = function() { var instance = this; var settings = this.getSettings(); if (settings.autoColumnSize || !settings.colWidths) { var cols = this.countCols(); for (var c = 0; c < cols; c++) { if (!instance._getColWidthFromSettings(c)) { this.autoColumnWidths[c] = plugin.determineColumnWidth.call(instance, c); } } } }; this.modifyColWidth = function(width, col) { if (this.autoColumnWidths[col] && this.autoColumnWidths[col] > width) { return this.autoColumnWidths[col]; } return width; }; this.afterDestroy = function() { var instance = this; if (instance.autoColumnSizeTmp && instance.autoColumnSizeTmp.container && instance.autoColumnSizeTmp.container.parentNode) { instance.autoColumnSizeTmp.container.parentNode.removeChild(instance.autoColumnSizeTmp.container); } instance.autoColumnSizeTmp = null; }; function createTmpContainer(instance) { var d = document, tmp = this; tmp.table = d.createElement('table'); tmp.theadTh = d.createElement('th'); tmp.table.appendChild(d.createElement('thead')).appendChild(d.createElement('tr')).appendChild(tmp.theadTh); tmp.tableStyle = tmp.table.style; tmp.tableStyle.tableLayout = 'auto'; tmp.tableStyle.width = 'auto'; tmp.tbody = d.createElement('tbody'); tmp.table.appendChild(tmp.tbody); tmp.container = d.createElement('div'); tmp.container.className = instance.rootElement.className + ' hidden'; tmp.containerStyle = tmp.container.style; tmp.container.appendChild(tmp.table); } } var htAutoColumnSize = new AutoColumnSize(); Handsontable.hooks.add('beforeInit', htAutoColumnSize.beforeInit); Handsontable.hooks.add('afterUpdateSettings', htAutoColumnSize.beforeInit); //# },{"./../../dom.js":34,"./../../helpers.js":49,"./../../plugins.js":52}],55:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { Autofill: {get: function() { return Autofill; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47_plugins_46_js__, $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__; var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47_eventManager_46_js__ = require("./../../eventManager.js"), $___46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47_eventManager_46_js__}).eventManager; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; var WalkontableCellCoords = ($___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ = require("./../../3rdparty/walkontable/src/cellCoords.js"), $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__}).WalkontableCellCoords; ; function getDeltas(start, end, data, direction) { var rlength = data.length, clength = data ? data[0].length : 0, deltas = [], arr = [], diffRow, diffCol, startValue, endValue, delta; diffRow = end.row - start.row; diffCol = end.col - start.col; if (['down', 'up'].indexOf(direction) !== -1) { for (var col = 0; col <= diffCol; col++) { startValue = parseInt(data[0][col], 10); endValue = parseInt(data[rlength - 1][col], 10); delta = (direction === 'down' ? (endValue - startValue) : (startValue - endValue)) / (rlength - 1) || 0; arr.push(delta); } deltas.push(arr); } if (['right', 'left'].indexOf(direction) !== -1) { for (var row = 0; row <= diffRow; row++) { startValue = parseInt(data[row][0], 10); endValue = parseInt(data[row][clength - 1], 10); delta = (direction === 'right' ? (endValue - startValue) : (startValue - endValue)) / (clength - 1) || 0; arr = []; arr.push(delta); deltas.push(arr); } } return deltas; } function Autofill(instance) { var _this = this, mouseDownOnCellCorner = false, wtOnCellCornerMouseDown, wtOnCellMouseOver, eventManager; this.instance = instance; this.addingStarted = false; eventManager = eventManagerObject(instance); function mouseUpCallback(event) { if (!instance.autofill) { return true; } if (instance.autofill.handle && instance.autofill.handle.isDragged) { if (instance.autofill.handle.isDragged > 1) { instance.autofill.apply(); } instance.autofill.handle.isDragged = 0; mouseDownOnCellCorner = false; } } function mouseMoveCallback(event) { var tableBottom, tableRight; if (!_this.instance.autofill) { return false; } tableBottom = dom.offset(_this.instance.table).top - (window.pageYOffset || document.documentElement.scrollTop) + dom.outerHeight(_this.instance.table); tableRight = dom.offset(_this.instance.table).left - (window.pageXOffset || document.documentElement.scrollLeft) + dom.outerWidth(_this.instance.table); if (_this.addingStarted === false && _this.instance.autofill.handle.isDragged > 0 && event.clientY > tableBottom && event.clientX <= tableRight) { _this.instance.mouseDragOutside = true; _this.addingStarted = true; } else { _this.instance.mouseDragOutside = false; } if (_this.instance.mouseDragOutside) { setTimeout(function() { _this.addingStarted = false; _this.instance.alter('insert_row'); }, 200); } } eventManager.addEventListener(document, 'mouseup', mouseUpCallback); eventManager.addEventListener(document, 'mousemove', mouseMoveCallback); wtOnCellCornerMouseDown = this.instance.view.wt.wtSettings.settings.onCellCornerMouseDown; this.instance.view.wt.wtSettings.settings.onCellCornerMouseDown = function(event) { instance.autofill.handle.isDragged = 1; mouseDownOnCellCorner = true; wtOnCellCornerMouseDown(event); }; wtOnCellMouseOver = this.instance.view.wt.wtSettings.settings.onCellMouseOver; this.instance.view.wt.wtSettings.settings.onCellMouseOver = function(event, coords, TD, wt) { if (instance.autofill && mouseDownOnCellCorner && !instance.view.isMouseDown() && instance.autofill.handle && instance.autofill.handle.isDragged) { instance.autofill.handle.isDragged++; instance.autofill.showBorder(coords); instance.autofill.checkIfNewRowNeeded(); } wtOnCellMouseOver(event, coords, TD, wt); }; this.instance.view.wt.wtSettings.settings.onCellCornerDblClick = function() { instance.autofill.selectAdjacent(); }; } Autofill.prototype.init = function() { this.handle = {}; }; Autofill.prototype.disable = function() { this.handle.disabled = true; }; Autofill.prototype.selectAdjacent = function() { var select, data, r, maxR, c; if (this.instance.selection.isMultiple()) { select = this.instance.view.wt.selections.area.getCorners(); } else { select = this.instance.view.wt.selections.current.getCorners(); } data = this.instance.getData(); rows: for (r = select[2] + 1; r < this.instance.countRows(); r++) { for (c = select[1]; c <= select[3]; c++) { if (data[r][c]) { break rows; } } if (!!data[r][select[1] - 1] || !!data[r][select[3] + 1]) { maxR = r; } } if (maxR) { this.instance.view.wt.selections.fill.clear(); this.instance.view.wt.selections.fill.add(new WalkontableCellCoords(select[0], select[1])); this.instance.view.wt.selections.fill.add(new WalkontableCellCoords(maxR, select[3])); this.apply(); } }; Autofill.prototype.apply = function() { var drag, select, start, end, _data, direction, deltas, selRange; this.handle.isDragged = 0; drag = this.instance.view.wt.selections.fill.getCorners(); if (!drag) { return; } this.instance.view.wt.selections.fill.clear(); if (this.instance.selection.isMultiple()) { select = this.instance.view.wt.selections.area.getCorners(); } else { select = this.instance.view.wt.selections.current.getCorners(); } if (drag[0] === select[0] && drag[1] < select[1]) { direction = 'left'; start = new WalkontableCellCoords(drag[0], drag[1]); end = new WalkontableCellCoords(drag[2], select[1] - 1); } else if (drag[0] === select[0] && drag[3] > select[3]) { direction = 'right'; start = new WalkontableCellCoords(drag[0], select[3] + 1); end = new WalkontableCellCoords(drag[2], drag[3]); } else if (drag[0] < select[0] && drag[1] === select[1]) { direction = 'up'; start = new WalkontableCellCoords(drag[0], drag[1]); end = new WalkontableCellCoords(select[0] - 1, drag[3]); } else if (drag[2] > select[2] && drag[1] === select[1]) { direction = 'down'; start = new WalkontableCellCoords(select[2] + 1, drag[1]); end = new WalkontableCellCoords(drag[2], drag[3]); } if (start && start.row > -1 && start.col > -1) { selRange = { from: this.instance.getSelectedRange().from, to: this.instance.getSelectedRange().to }; _data = this.instance.getData(selRange.from.row, selRange.from.col, selRange.to.row, selRange.to.col); deltas = getDeltas(start, end, _data, direction); Handsontable.hooks.run(this.instance, 'beforeAutofill', start, end, _data); this.instance.populateFromArray(start.row, start.col, _data, end.row, end.col, 'autofill', null, direction, deltas); this.instance.selection.setRangeStart(new WalkontableCellCoords(drag[0], drag[1])); this.instance.selection.setRangeEnd(new WalkontableCellCoords(drag[2], drag[3])); } else { this.instance.selection.refreshBorders(); } }; Autofill.prototype.showBorder = function(coords) { var topLeft = this.instance.getSelectedRange().getTopLeftCorner(), bottomRight = this.instance.getSelectedRange().getBottomRightCorner(); if (this.instance.getSettings().fillHandle !== 'horizontal' && (bottomRight.row < coords.row || topLeft.row > coords.row)) { coords = new WalkontableCellCoords(coords.row, bottomRight.col); } else if (this.instance.getSettings().fillHandle !== 'vertical') { coords = new WalkontableCellCoords(bottomRight.row, coords.col); } else { return; } this.instance.view.wt.selections.fill.clear(); this.instance.view.wt.selections.fill.add(this.instance.getSelectedRange().from); this.instance.view.wt.selections.fill.add(this.instance.getSelectedRange().to); this.instance.view.wt.selections.fill.add(coords); this.instance.view.render(); }; Autofill.prototype.checkIfNewRowNeeded = function() { var fillCorners, selection, tableRows = this.instance.countRows(), that = this; if (this.instance.view.wt.selections.fill.cellRange && this.addingStarted === false) { selection = this.instance.getSelected(); fillCorners = this.instance.view.wt.selections.fill.getCorners(); if (selection[2] < tableRows - 1 && fillCorners[2] === tableRows - 1) { this.addingStarted = true; this.instance._registerTimeout(setTimeout(function() { that.instance.alter('insert_row'); that.addingStarted = false; }, 200)); } } }; Handsontable.hooks.add('afterInit', function() { var autofill = new Autofill(this); if (typeof this.getSettings().fillHandle !== 'undefined') { if (autofill.handle && this.getSettings().fillHandle === false) { autofill.disable(); } else if (!autofill.handle && this.getSettings().fillHandle !== false) { this.autofill = autofill; this.autofill.init(); } } }); Handsontable.Autofill = Autofill; //# },{"./../../3rdparty/walkontable/src/cellCoords.js":8,"./../../dom.js":34,"./../../eventManager.js":48,"./../../plugins.js":52}],56:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { ColumnSorting: {get: function() { return ColumnSorting; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47_plugins_46_js__; var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47_eventManager_46_js__ = require("./../../eventManager.js"), $___46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47_eventManager_46_js__}).eventManager; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; function ColumnSorting() { var plugin = this; this.init = function(source) { var instance = this; var sortingSettings = instance.getSettings().columnSorting; var sortingColumn, sortingOrder; instance.sortingEnabled = !!(sortingSettings); if (instance.sortingEnabled) { instance.sortIndex = []; var loadedSortingState = loadSortingState.call(instance); if (typeof loadedSortingState != 'undefined') { sortingColumn = loadedSortingState.sortColumn; sortingOrder = loadedSortingState.sortOrder; } else { sortingColumn = sortingSettings.column; sortingOrder = sortingSettings.sortOrder; } plugin.sortByColumn.call(instance, sortingColumn, sortingOrder); instance.sort = function() { var args = Array.prototype.slice.call(arguments); return plugin.sortByColumn.apply(instance, args); }; if (typeof instance.getSettings().observeChanges == 'undefined') { enableObserveChangesPlugin.call(instance); } if (source == 'afterInit') { bindColumnSortingAfterClick.call(instance); instance.addHook('afterCreateRow', plugin.afterCreateRow); instance.addHook('afterRemoveRow', plugin.afterRemoveRow); instance.addHook('afterLoadData', plugin.init); } } else { delete instance.sort; instance.removeHook('afterCreateRow', plugin.afterCreateRow); instance.removeHook('afterRemoveRow', plugin.afterRemoveRow); instance.removeHook('afterLoadData', plugin.init); } }; this.setSortingColumn = function(col, order) { var instance = this; if (typeof col == 'undefined') { delete instance.sortColumn; delete instance.sortOrder; return; } else if (instance.sortColumn === col && typeof order == 'undefined') { instance.sortOrder = !instance.sortOrder; } else { instance.sortOrder = typeof order != 'undefined' ? order : true; } instance.sortColumn = col; }; this.sortByColumn = function(col, order) { var instance = this; plugin.setSortingColumn.call(instance, col, order); if (typeof instance.sortColumn == 'undefined') { return; } Handsontable.hooks.run(instance, 'beforeColumnSort', instance.sortColumn, instance.sortOrder); plugin.sort.call(instance); instance.render(); saveSortingState.call(instance); Handsontable.hooks.run(instance, 'afterColumnSort', instance.sortColumn, instance.sortOrder); }; var saveSortingState = function() { var instance = this; var sortingState = {}; if (typeof instance.sortColumn != 'undefined') { sortingState.sortColumn = instance.sortColumn; } if (typeof instance.sortOrder != 'undefined') { sortingState.sortOrder = instance.sortOrder; } if (sortingState.hasOwnProperty('sortColumn') || sortingState.hasOwnProperty('sortOrder')) { Handsontable.hooks.run(instance, 'persistentStateSave', 'columnSorting', sortingState); } }; var loadSortingState = function() { var instance = this; var storedState = {}; Handsontable.hooks.run(instance, 'persistentStateLoad', 'columnSorting', storedState); return storedState.value; }; var bindColumnSortingAfterClick = function() { var instance = this; var eventManager = eventManagerObject(instance); eventManager.addEventListener(instance.rootElement, 'click', function(e) { if (dom.hasClass(e.target, 'columnSorting')) { var col = getColumn(e.target); plugin.sortByColumn.call(instance, col); } }); function countRowHeaders() { var THs = instance.view.TBODY.querySelector('tr').querySelectorAll('th'); return THs.length; } function getColumn(target) { var TH = dom.closest(target, 'TH'); return dom.index(TH) - countRowHeaders(); } }; function enableObserveChangesPlugin() { var instance = this; instance._registerTimeout(setTimeout(function() { instance.updateSettings({observeChanges: true}); }, 0)); } function defaultSort(sortOrder) { return function(a, b) { if (typeof a[1] == "string") { a[1] = a[1].toLowerCase(); } if (typeof b[1] == "string") { b[1] = b[1].toLowerCase(); } if (a[1] === b[1]) { return 0; } if (a[1] === null || a[1] === "") { return 1; } if (b[1] === null || b[1] === "") { return -1; } if (a[1] < b[1]) { return sortOrder ? -1 : 1; } if (a[1] > b[1]) { return sortOrder ? 1 : -1; } return 0; }; } function dateSort(sortOrder) { return function(a, b) { if (a[1] === b[1]) { return 0; } if (a[1] === null) { return 1; } if (b[1] === null) { return -1; } var aDate = new Date(a[1]); var bDate = new Date(b[1]); if (aDate < bDate) { return sortOrder ? -1 : 1; } if (aDate > bDate) { return sortOrder ? 1 : -1; } return 0; }; } this.sort = function() { var instance = this; if (typeof instance.sortOrder == 'undefined') { return; } instance.sortingEnabled = false; instance.sortIndex.length = 0; var colOffset = this.colOffset(); for (var i = 0, ilen = this.countRows() - instance.getSettings()['minSpareRows']; i < ilen; i++) { this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]); } var colMeta = instance.getCellMeta(0, instance.sortColumn); var sortFunction; switch (colMeta.type) { case 'date': sortFunction = dateSort; break; default: sortFunction = defaultSort; } this.sortIndex.sort(sortFunction(instance.sortOrder)); for (var i = this.sortIndex.length; i < instance.countRows(); i++) { this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]); } instance.sortingEnabled = true; }; this.translateRow = function(row) { var instance = this; if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length && instance.sortIndex[row]) { return instance.sortIndex[row][0]; } return row; }; this.untranslateRow = function(row) { var instance = this; if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length) { for (var i = 0; i < instance.sortIndex.length; i++) { if (instance.sortIndex[i][0] == row) { return i; } } } }; this.getColHeader = function(col, TH) { if (this.getSettings().columnSorting && col >= 0) { dom.addClass(TH.querySelector('.colHeader'), 'columnSorting'); } }; function isSorted(instance) { return typeof instance.sortColumn != 'undefined'; } this.afterCreateRow = function(index, amount) { var instance = this; if (!isSorted(instance)) { return; } for (var i = 0; i < instance.sortIndex.length; i++) { if (instance.sortIndex[i][0] >= index) { instance.sortIndex[i][0] += amount; } } for (var i = 0; i < amount; i++) { instance.sortIndex.splice(index + i, 0, [index + i, instance.getData()[index + i][instance.sortColumn + instance.colOffset()]]); } saveSortingState.call(instance); }; this.afterRemoveRow = function(index, amount) { var instance = this; if (!isSorted(instance)) { return; } var physicalRemovedIndex = plugin.translateRow.call(instance, index); instance.sortIndex.splice(index, amount); for (var i = 0; i < instance.sortIndex.length; i++) { if (instance.sortIndex[i][0] > physicalRemovedIndex) { instance.sortIndex[i][0] -= amount; } } saveSortingState.call(instance); }; this.afterChangeSort = function(changes) { var instance = this; var sortColumnChanged = false; var selection = {}; if (!changes) { return; } for (var i = 0; i < changes.length; i++) { if (changes[i][1] == instance.sortColumn) { sortColumnChanged = true; selection.row = plugin.translateRow.call(instance, changes[i][0]); selection.col = changes[i][1]; break; } } if (sortColumnChanged) { instance._registerTimeout(setTimeout(function() { plugin.sort.call(instance); instance.render(); instance.selectCell(plugin.untranslateRow.call(instance, selection.row), selection.col); }, 0)); } }; } var htSortColumn = new ColumnSorting(); Handsontable.hooks.add('afterInit', function() { htSortColumn.init.call(this, 'afterInit'); }); Handsontable.hooks.add('afterUpdateSettings', function() { htSortColumn.init.call(this, 'afterUpdateSettings'); }); Handsontable.hooks.add('modifyRow', htSortColumn.translateRow); Handsontable.hooks.add('afterGetColHeader', htSortColumn.getColHeader); Handsontable.hooks.register('beforeColumnSort'); Handsontable.hooks.register('afterColumnSort'); //# },{"./../../dom.js":34,"./../../eventManager.js":48,"./../../plugins.js":52}],57:[function(require,module,exports){ "use strict"; var $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_helpers_46_js__, $___46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__; var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var helper = ($___46__46__47__46__46__47_helpers_46_js__ = require("./../../helpers.js"), $___46__46__47__46__46__47_helpers_46_js__ && $___46__46__47__46__46__47_helpers_46_js__.__esModule && $___46__46__47__46__46__47_helpers_46_js__ || {default: $___46__46__47__46__46__47_helpers_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47_eventManager_46_js__ = require("./../../eventManager.js"), $___46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47_eventManager_46_js__}).eventManager; var WalkontableCellCoords = ($___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ = require("./../../3rdparty/walkontable/src/cellCoords.js"), $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__}).WalkontableCellCoords; function Comments(instance) { var eventManager = eventManagerObject(instance), doSaveComment = function(row, col, comment, instance) { instance.setCellMeta(row, col, 'comment', comment); instance.render(); }, saveComment = function(range, comment, instance) { doSaveComment(range.from.row, range.from.col, comment, instance); }, hideCommentTextArea = function() { var commentBox = createCommentBox(); commentBox.style.display = 'none'; commentBox.value = ''; }, bindMouseEvent = function(range) { function commentsListener(event) { eventManager.removeEventListener(document, 'mouseover'); if (!(event.target.className == 'htCommentTextArea' || event.target.innerHTML.indexOf('Comment') != -1)) { var value = document.querySelector('.htCommentTextArea').value; if (value.trim().length > 1) { saveComment(range, value, instance); } unBindMouseEvent(); hideCommentTextArea(); } } eventManager.addEventListener(document, 'mousedown', helper.proxy(commentsListener)); }, unBindMouseEvent = function() { eventManager.removeEventListener(document, 'mousedown'); eventManager.addEventListener(document, 'mousedown', helper.proxy(commentsMouseOverListener)); }, placeCommentBox = function(range, commentBox) { var TD = instance.view.wt.wtTable.getCell(range.from), offset = dom.offset(TD), lastColWidth = instance.getColWidth(range.from.col); commentBox.style.position = 'absolute'; commentBox.style.left = offset.left + lastColWidth + 'px'; commentBox.style.top = offset.top + 'px'; commentBox.style.zIndex = 2; bindMouseEvent(range, commentBox); }, createCommentBox = function(value) { var comments = document.querySelector('.htComments'); if (!comments) { comments = document.createElement('DIV'); var textArea = document.createElement('TEXTAREA'); dom.addClass(textArea, 'htCommentTextArea'); comments.appendChild(textArea); dom.addClass(comments, 'htComments'); document.getElementsByTagName('body')[0].appendChild(comments); } value = value || ''; document.querySelector('.htCommentTextArea').value = value; return comments; }, commentsMouseOverListener = function(event) { if (event.target.className.indexOf('htCommentCell') != -1) { unBindMouseEvent(); var coords = instance.view.wt.wtTable.getCoords(event.target); var range = {from: new WalkontableCellCoords(coords.row, coords.col)}; Handsontable.Comments.showComment(range); } else if (event.target.className != 'htCommentTextArea') { hideCommentTextArea(); } }; return { init: function() { eventManager.addEventListener(document, 'mouseover', helper.proxy(commentsMouseOverListener)); }, showComment: function(range) { var meta = instance.getCellMeta(range.from.row, range.from.col), value = ''; if (meta.comment) { value = meta.comment; } var commentBox = createCommentBox(value); commentBox.style.display = 'block'; placeCommentBox(range, commentBox); }, removeComment: function(row, col) { instance.removeCellMeta(row, col, 'comment'); instance.render(); }, checkSelectionCommentsConsistency: function() { var hasComment = false; var cell = instance.getSelectedRange().from; if (instance.getCellMeta(cell.row, cell.col).comment) { hasComment = true; } return hasComment; } }; } var init = function() { var instance = this; var commentsSetting = instance.getSettings().comments; if (commentsSetting) { Handsontable.Comments = new Comments(instance); Handsontable.Comments.init(); } }, afterRenderer = function(TD, row, col, prop, value, cellProperties) { if (cellProperties.comment) { dom.addClass(TD, cellProperties.commentedCellClassName); } }, addCommentsActionsToContextMenu = function(defaultOptions) { var instance = this; if (!instance.getSettings().comments) { return; } defaultOptions.items.push(Handsontable.ContextMenu.SEPARATOR); defaultOptions.items.push({ key: 'commentsAddEdit', name: function() { var hasComment = Handsontable.Comments.checkSelectionCommentsConsistency(); return hasComment ? "Edit Comment" : "Add Comment"; }, callback: function(key, selection, event) { Handsontable.Comments.showComment(this.getSelectedRange()); }, disabled: function() { return false; } }); defaultOptions.items.push({ key: 'commentsRemove', name: function() { return "Delete Comment"; }, callback: function(key, selection, event) { Handsontable.Comments.removeComment(selection.start.row, selection.start.col); }, disabled: function() { var hasComment = Handsontable.Comments.checkSelectionCommentsConsistency(); return !hasComment; } }); }; Handsontable.hooks.add('beforeInit', init); Handsontable.hooks.add('afterContextMenuDefaultOptions', addCommentsActionsToContextMenu); Handsontable.hooks.add('afterRenderer', afterRenderer); //# },{"./../../3rdparty/walkontable/src/cellCoords.js":8,"./../../dom.js":34,"./../../eventManager.js":48,"./../../helpers.js":49}],58:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { ContextMenu: {get: function() { return ContextMenu; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_helpers_46_js__, $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47_plugins_46_js__; var helper = ($___46__46__47__46__46__47_helpers_46_js__ = require("./../../helpers.js"), $___46__46__47__46__46__47_helpers_46_js__ && $___46__46__47__46__46__47_helpers_46_js__.__esModule && $___46__46__47__46__46__47_helpers_46_js__ || {default: $___46__46__47__46__46__47_helpers_46_js__}); var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47_eventManager_46_js__ = require("./../../eventManager.js"), $___46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47_eventManager_46_js__}).eventManager; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; function ContextMenu(instance, customOptions) { this.instance = instance; var contextMenu = this; contextMenu.menus = []; contextMenu.htMenus = {}; contextMenu.triggerRows = []; contextMenu.eventManager = eventManagerObject(contextMenu); this.enabled = true; this.instance.addHook('afterDestroy', function() { contextMenu.destroy(); }); this.defaultOptions = {items: [{ key: 'row_above', name: 'Insert row above', callback: function(key, selection) { this.alter("insert_row", selection.start.row); }, disabled: function() { var selected = this.getSelected(), entireColumnSelection = [0, selected[1], this.countRows() - 1, selected[1]], columnSelected = entireColumnSelection.join(',') == selected.join(','); return selected[0] < 0 || this.countRows() >= this.getSettings().maxRows || columnSelected; } }, { key: 'row_below', name: 'Insert row below', callback: function(key, selection) { this.alter("insert_row", selection.end.row + 1); }, disabled: function() { var selected = this.getSelected(), entireColumnSelection = [0, selected[1], this.countRows() - 1, selected[1]], columnSelected = entireColumnSelection.join(',') == selected.join(','); return this.getSelected()[0] < 0 || this.countRows() >= this.getSettings().maxRows || columnSelected; } }, ContextMenu.SEPARATOR, { key: 'col_left', name: 'Insert column on the left', callback: function(key, selection) { this.alter("insert_col", selection.start.col); }, disabled: function() { var selected = this.getSelected(), entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1], rowSelected = entireRowSelection.join(',') == selected.join(','); return this.getSelected()[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected; } }, { key: 'col_right', name: 'Insert column on the right', callback: function(key, selection) { this.alter("insert_col", selection.end.col + 1); }, disabled: function() { var selected = this.getSelected(), entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1], rowSelected = entireRowSelection.join(',') == selected.join(','); return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected; } }, ContextMenu.SEPARATOR, { key: 'remove_row', name: 'Remove row', callback: function(key, selection) { var amount = selection.end.row - selection.start.row + 1; this.alter("remove_row", selection.start.row, amount); }, disabled: function() { var selected = this.getSelected(), entireColumnSelection = [0, selected[1], this.countRows() - 1, selected[1]], columnSelected = entireColumnSelection.join(',') == selected.join(','); return (selected[0] < 0 || columnSelected); } }, { key: 'remove_col', name: 'Remove column', callback: function(key, selection) { var amount = selection.end.col - selection.start.col + 1; this.alter("remove_col", selection.start.col, amount); }, disabled: function() { var selected = this.getSelected(), entireRowSelection = [selected[0], 0, selected[0], this.countCols() - 1], rowSelected = entireRowSelection.join(',') == selected.join(','); return (selected[1] < 0 || rowSelected); } }, ContextMenu.SEPARATOR, { key: 'undo', name: 'Undo', callback: function() { this.undo(); }, disabled: function() { return this.undoRedo && !this.undoRedo.isUndoAvailable(); } }, { key: 'redo', name: 'Redo', callback: function() { this.redo(); }, disabled: function() { return this.undoRedo && !this.undoRedo.isRedoAvailable(); } }, ContextMenu.SEPARATOR, { key: 'make_read_only', name: function() { var label = "Read only"; var atLeastOneReadOnly = contextMenu.checkSelectionReadOnlyConsistency(this); if (atLeastOneReadOnly) { label = contextMenu.markSelected(label); } return label; }, callback: function() { var atLeastOneReadOnly = contextMenu.checkSelectionReadOnlyConsistency(this); var that = this; this.getSelectedRange().forAll(function(r, c) { that.getCellMeta(r, c).readOnly = atLeastOneReadOnly ? false : true; }); this.render(); } }, ContextMenu.SEPARATOR, { key: 'alignment', name: 'Alignment', submenu: {items: [{ name: function() { var label = "Left"; var hasClass = contextMenu.checkSelectionAlignment(this, 'htLeft'); if (hasClass) { label = contextMenu.markSelected(label); } return label; }, callback: function() { align.call(this, this.getSelectedRange(), 'horizontal', 'htLeft'); }, disabled: false }, { name: function() { var label = "Center"; var hasClass = contextMenu.checkSelectionAlignment(this, 'htCenter'); if (hasClass) { label = contextMenu.markSelected(label); } return label; }, callback: function() { align.call(this, this.getSelectedRange(), 'horizontal', 'htCenter'); }, disabled: false }, { name: function() { var label = "Right"; var hasClass = contextMenu.checkSelectionAlignment(this, 'htRight'); if (hasClass) { label = contextMenu.markSelected(label); } return label; }, callback: function() { align.call(this, this.getSelectedRange(), 'horizontal', 'htRight'); }, disabled: false }, { name: function() { var label = "Justify"; var hasClass = contextMenu.checkSelectionAlignment(this, 'htJustify'); if (hasClass) { label = contextMenu.markSelected(label); } return label; }, callback: function() { align.call(this, this.getSelectedRange(), 'horizontal', 'htJustify'); }, disabled: false }, ContextMenu.SEPARATOR, { name: function() { var label = "Top"; var hasClass = contextMenu.checkSelectionAlignment(this, 'htTop'); if (hasClass) { label = contextMenu.markSelected(label); } return label; }, callback: function() { align.call(this, this.getSelectedRange(), 'vertical', 'htTop'); }, disabled: false }, { name: function() { var label = "Middle"; var hasClass = contextMenu.checkSelectionAlignment(this, 'htMiddle'); if (hasClass) { label = contextMenu.markSelected(label); } return label; }, callback: function() { align.call(this, this.getSelectedRange(), 'vertical', 'htMiddle'); }, disabled: false }, { name: function() { var label = "Bottom"; var hasClass = contextMenu.checkSelectionAlignment(this, 'htBottom'); if (hasClass) { label = contextMenu.markSelected(label); } return label; }, callback: function() { align.call(this, this.getSelectedRange(), 'vertical', 'htBottom'); }, disabled: false }]} }]}; contextMenu.options = {}; helper.extend(contextMenu.options, this.options); this.bindMouseEvents(); this.markSelected = function(label) { return "<span class='selected'>" + String.fromCharCode(10003) + "</span>" + label; }; this.checkSelectionAlignment = function(hot, className) { var hasAlignment = false; hot.getSelectedRange().forAll(function(r, c) { var metaClassName = hot.getCellMeta(r, c).className; if (metaClassName && metaClassName.indexOf(className) != -1) { hasAlignment = true; return false; } }); return hasAlignment; }; if (!this.instance.getSettings().allowInsertRow) { var rowAboveIndex = findIndexByKey(this.defaultOptions.items, 'row_above'); this.defaultOptions.items.splice(rowAboveIndex, 1); var rowBelowIndex = findIndexByKey(this.defaultOptions.items, 'row_above'); this.defaultOptions.items.splice(rowBelowIndex, 1); this.defaultOptions.items.splice(rowBelowIndex, 1); } if (!this.instance.getSettings().allowInsertColumn) { var colLeftIndex = findIndexByKey(this.defaultOptions.items, 'col_left'); this.defaultOptions.items.splice(colLeftIndex, 1); var colRightIndex = findIndexByKey(this.defaultOptions.items, 'col_right'); this.defaultOptions.items.splice(colRightIndex, 1); this.defaultOptions.items.splice(colRightIndex, 1); } var removeRow = false; var removeCol = false; var removeRowIndex, removeColumnIndex; if (!this.instance.getSettings().allowRemoveRow) { removeRowIndex = findIndexByKey(this.defaultOptions.items, 'remove_row'); this.defaultOptions.items.splice(removeRowIndex, 1); removeRow = true; } if (!this.instance.getSettings().allowRemoveColumn) { removeColumnIndex = findIndexByKey(this.defaultOptions.items, 'remove_col'); this.defaultOptions.items.splice(removeColumnIndex, 1); removeCol = true; } if (removeRow && removeCol) { this.defaultOptions.items.splice(removeColumnIndex, 1); } this.checkSelectionReadOnlyConsistency = function(hot) { var atLeastOneReadOnly = false; hot.getSelectedRange().forAll(function(r, c) { if (hot.getCellMeta(r, c).readOnly) { atLeastOneReadOnly = true; return false; } }); return atLeastOneReadOnly; }; Handsontable.hooks.run(instance, 'afterContextMenuDefaultOptions', this.defaultOptions); } ContextMenu.prototype.createMenu = function(menuName, row) { if (menuName) { menuName = menuName.replace(/ /g, '_'); menuName = 'htContextSubMenu_' + menuName; } var menu; if (menuName) { menu = document.querySelector('.htContextMenu.' + menuName); } else { menu = document.querySelector('.htContextMenu'); } if (!menu) { menu = document.createElement('DIV'); dom.addClass(menu, 'htContextMenu'); if (menuName) { dom.addClass(menu, menuName); } document.getElementsByTagName('body')[0].appendChild(menu); } if (this.menus.indexOf(menu) < 0) { this.menus.push(menu); row = row || 0; this.triggerRows.push(row); } return menu; }; ContextMenu.prototype.bindMouseEvents = function() { function contextMenuOpenListener(event) { var settings = this.instance.getSettings(), showRowHeaders = this.instance.getSettings().rowHeaders, showColHeaders = this.instance.getSettings().colHeaders, containsCornerHeader, element, items, menu; function isValidElement(element) { return element.nodeName === 'TD' || element.parentNode.nodeName === 'TD'; } element = event.realTarget; this.closeAll(); event.preventDefault(); helper.stopPropagation(event); if (!(showRowHeaders || showColHeaders)) { if (!isValidElement(element) && !(dom.hasClass(element, 'current') && dom.hasClass(element, 'wtBorder'))) { return; } } else if (showRowHeaders && showColHeaders) { containsCornerHeader = element.parentNode.querySelectorAll('.cornerHeader').length > 0; if (containsCornerHeader) { return; } } menu = this.createMenu(); items = this.getItems(settings.contextMenu); this.show(menu, items); this.setMenuPosition(event, menu); this.eventManager.addEventListener(document.documentElement, 'mousedown', helper.proxy(ContextMenu.prototype.closeAll, this)); } var eventManager = eventManagerObject(this.instance); eventManager.addEventListener(this.instance.rootElement, 'contextmenu', helper.proxy(contextMenuOpenListener, this)); }; ContextMenu.prototype.bindTableEvents = function() { this._afterScrollCallback = function() {}; this.instance.addHook('afterScrollVertically', this._afterScrollCallback); this.instance.addHook('afterScrollHorizontally', this._afterScrollCallback); }; ContextMenu.prototype.unbindTableEvents = function() { if (this._afterScrollCallback) { this.instance.removeHook('afterScrollVertically', this._afterScrollCallback); this.instance.removeHook('afterScrollHorizontally', this._afterScrollCallback); this._afterScrollCallback = null; } }; ContextMenu.prototype.performAction = function(event, hot) { var contextMenu = this; var selectedItemIndex = hot.getSelected()[0]; var selectedItem = hot.getData()[selectedItemIndex]; if (selectedItem.disabled === true || (typeof selectedItem.disabled == 'function' && selectedItem.disabled.call(this.instance) === true)) { return; } if (!selectedItem.hasOwnProperty('submenu')) { if (typeof selectedItem.callback != 'function') { return; } var selRange = this.instance.getSelectedRange(); var normalizedSelection = ContextMenu.utils.normalizeSelection(selRange); selectedItem.callback.call(this.instance, selectedItem.key, normalizedSelection, event); contextMenu.closeAll(); } }; ContextMenu.prototype.unbindMouseEvents = function() { this.eventManager.clear(); var eventManager = eventManagerObject(this.instance); eventManager.removeEventListener(this.instance.rootElement, 'contextmenu'); }; ContextMenu.prototype.show = function(menu, items) { var that = this; menu.removeAttribute('style'); menu.style.display = 'block'; var settings = { data: items, colHeaders: false, colWidths: [200], readOnly: true, copyPaste: false, columns: [{ data: 'name', renderer: helper.proxy(this.renderer, this) }], renderAllRows: true, beforeKeyDown: function(event) { that.onBeforeKeyDown(event, htContextMenu); }, afterOnCellMouseOver: function(event, coords, TD) { that.onCellMouseOver(event, coords, TD, htContextMenu); } }; var htContextMenu = new Handsontable(menu, settings); htContextMenu.isHotTableEnv = this.instance.isHotTableEnv; Handsontable.eventManager.isHotTableEnv = this.instance.isHotTableEnv; this.eventManager.removeEventListener(menu, 'mousedown'); this.eventManager.addEventListener(menu, 'mousedown', function(event) { that.performAction(event, htContextMenu); }); this.bindTableEvents(); htContextMenu.listen(); this.htMenus[htContextMenu.guid] = htContextMenu; Handsontable.hooks.run(this.instance, 'afterContextMenuShow', htContextMenu); }; ContextMenu.prototype.close = function(menu) { this.hide(menu); this.eventManager.clear(); this.unbindTableEvents(); this.instance.listen(); }; ContextMenu.prototype.closeAll = function() { while (this.menus.length > 0) { var menu = this.menus.pop(); if (menu) { this.close(menu); } } this.triggerRows = []; }; ContextMenu.prototype.closeLastOpenedSubMenu = function() { var menu = this.menus.pop(); if (menu) { this.hide(menu); } }; ContextMenu.prototype.hide = function(menu) { menu.style.display = 'none'; var instance = this.htMenus[menu.id]; Handsontable.hooks.run(this.instance, 'afterContextMenuHide', instance); instance.destroy(); delete this.htMenus[menu.id]; }; ContextMenu.prototype.renderer = function(instance, TD, row, col, prop, value) { var contextMenu = this; var item = instance.getData()[row]; var wrapper = document.createElement('DIV'); if (typeof value === 'function') { value = value.call(this.instance); } dom.empty(TD); TD.appendChild(wrapper); if (itemIsSeparator(item)) { dom.addClass(TD, 'htSeparator'); } else { dom.fastInnerHTML(wrapper, value); } if (itemIsDisabled(item)) { dom.addClass(TD, 'htDisabled'); this.eventManager.addEventListener(wrapper, 'mouseenter', function() { instance.deselectCell(); }); } else { if (isSubMenu(item)) { dom.addClass(TD, 'htSubmenu'); this.eventManager.addEventListener(wrapper, 'mouseenter', function() { instance.selectCell(row, col); }); } else { dom.removeClass(TD, 'htSubmenu'); dom.removeClass(TD, 'htDisabled'); this.eventManager.addEventListener(wrapper, 'mouseenter', function() { instance.selectCell(row, col); }); } } function isSubMenu(item) { return item.hasOwnProperty('submenu'); } function itemIsSeparator(item) { return new RegExp(ContextMenu.SEPARATOR.name, 'i').test(item.name); } function itemIsDisabled(item) { return item.disabled === true || (typeof item.disabled == 'function' && item.disabled.call(contextMenu.instance) === true); } }; ContextMenu.prototype.onCellMouseOver = function(event, coords, TD, hot) { var menusLength = this.menus.length; if (menusLength > 0) { var lastMenu = this.menus[menusLength - 1]; if (lastMenu.id != hot.guid) { this.closeLastOpenedSubMenu(); } } else { this.closeLastOpenedSubMenu(); } if (TD.className.indexOf('htSubmenu') != -1) { var selectedItem = hot.getData()[coords.row]; var items = this.getItems(selectedItem.submenu); var subMenu = this.createMenu(selectedItem.name, coords.row); var tdCoords = TD.getBoundingClientRect(); this.show(subMenu, items); this.setSubMenuPosition(tdCoords, subMenu); } }; ContextMenu.prototype.onBeforeKeyDown = function(event, instance) { dom.enableImmediatePropagation(event); var contextMenu = this; var selection = instance.getSelected(); switch (event.keyCode) { case helper.keyCode.ESCAPE: contextMenu.closeAll(); event.preventDefault(); event.stopImmediatePropagation(); break; case helper.keyCode.ENTER: if (selection) { contextMenu.performAction(event, instance); } break; case helper.keyCode.ARROW_DOWN: if (!selection) { selectFirstCell(instance, contextMenu); } else { selectNextCell(selection[0], selection[1], instance, contextMenu); } event.preventDefault(); event.stopImmediatePropagation(); break; case helper.keyCode.ARROW_UP: if (!selection) { selectLastCell(instance, contextMenu); } else { selectPrevCell(selection[0], selection[1], instance, contextMenu); } event.preventDefault(); event.stopImmediatePropagation(); break; case helper.keyCode.ARROW_RIGHT: if (selection) { var row = selection[0]; var cell = instance.getCell(selection[0], 0); if (ContextMenu.utils.hasSubMenu(cell)) { openSubMenu(instance, contextMenu, cell, row); } } event.preventDefault(); event.stopImmediatePropagation(); break; case helper.keyCode.ARROW_LEFT: if (selection) { if (instance.rootElement.className.indexOf('htContextSubMenu_') != -1) { contextMenu.closeLastOpenedSubMenu(); var index = contextMenu.menus.length; if (index > 0) { var menu = contextMenu.menus[index - 1]; var triggerRow = contextMenu.triggerRows.pop(); instance = this.htMenus[menu.id]; instance.selectCell(triggerRow, 0); } } event.preventDefault(); event.stopImmediatePropagation(); } break; } function selectFirstCell(instance) { var firstCell = instance.getCell(0, 0); if (ContextMenu.utils.isSeparator(firstCell) || ContextMenu.utils.isDisabled(firstCell)) { selectNextCell(0, 0, instance); } else { instance.selectCell(0, 0); } } function selectLastCell(instance) { var lastRow = instance.countRows() - 1; var lastCell = instance.getCell(lastRow, 0); if (ContextMenu.utils.isSeparator(lastCell) || ContextMenu.utils.isDisabled(lastCell)) { selectPrevCell(lastRow, 0, instance); } else { instance.selectCell(lastRow, 0); } } function selectNextCell(row, col, instance) { var nextRow = row + 1; var nextCell = nextRow < instance.countRows() ? instance.getCell(nextRow, col) : null; if (!nextCell) { return; } if (ContextMenu.utils.isSeparator(nextCell) || ContextMenu.utils.isDisabled(nextCell)) { selectNextCell(nextRow, col, instance); } else { instance.selectCell(nextRow, col); } } function selectPrevCell(row, col, instance) { var prevRow = row - 1; var prevCell = prevRow >= 0 ? instance.getCell(prevRow, col) : null; if (!prevCell) { return; } if (ContextMenu.utils.isSeparator(prevCell) || ContextMenu.utils.isDisabled(prevCell)) { selectPrevCell(prevRow, col, instance); } else { instance.selectCell(prevRow, col); } } function openSubMenu(instance, contextMenu, cell, row) { var selectedItem = instance.getData()[row]; var items = contextMenu.getItems(selectedItem.submenu); var subMenu = contextMenu.createMenu(selectedItem.name, row); var coords = cell.getBoundingClientRect(); var subMenuInstance = contextMenu.show(subMenu, items); contextMenu.setSubMenuPosition(coords, subMenu); subMenuInstance.selectCell(0, 0); } }; function findByKey(items, key) { for (var i = 0, ilen = items.length; i < ilen; i++) { if (items[i].key === key) { return items[i]; } } } function findIndexByKey(items, key) { for (var i = 0, ilen = items.length; i < ilen; i++) { if (items[i].key === key) { return i; } } } ContextMenu.prototype.getItems = function(items) { var menu, item; function ContextMenuItem(rawItem) { if (typeof rawItem == 'string') { this.name = rawItem; } else { helper.extend(this, rawItem); } } ContextMenuItem.prototype = items; if (items && items.items) { items = items.items; } if (items === true) { items = this.defaultOptions.items; } if (1 == 1) { menu = []; for (var key in items) { if (items.hasOwnProperty(key)) { if (typeof items[key] === 'string') { item = findByKey(this.defaultOptions.items, items[key]); } else { item = findByKey(this.defaultOptions.items, key); } if (!item) { item = items[key]; } item = new ContextMenuItem(item); if (typeof items[key] === 'object') { helper.extend(item, items[key]); } if (!item.key) { item.key = key; } menu.push(item); } } } return menu; }; ContextMenu.prototype.setSubMenuPosition = function(coords, menu) { var scrollTop = dom.getWindowScrollTop(); var scrollLeft = dom.getWindowScrollLeft(); var cursor = { top: scrollTop + coords.top, topRelative: coords.top, left: coords.left, leftRelative: coords.left - scrollLeft, scrollTop: scrollTop, scrollLeft: scrollLeft, cellHeight: coords.height, cellWidth: coords.width }; if (this.menuFitsBelowCursor(cursor, menu, document.body.clientWidth)) { this.positionMenuBelowCursor(cursor, menu, true); } else { if (this.menuFitsAboveCursor(cursor, menu)) { this.positionMenuAboveCursor(cursor, menu, true); } else { this.positionMenuBelowCursor(cursor, menu, true); } } if (this.menuFitsOnRightOfCursor(cursor, menu, document.body.clientWidth)) { this.positionMenuOnRightOfCursor(cursor, menu, true); } else { this.positionMenuOnLeftOfCursor(cursor, menu, true); } }; ContextMenu.prototype.setMenuPosition = function(event, menu) { var scrollTop = dom.getWindowScrollTop(); var scrollLeft = dom.getWindowScrollLeft(); var cursorY = event.pageY || (event.clientY + scrollTop); var cursorX = event.pageX || (event.clientX + scrollLeft); var cursor = { top: cursorY, topRelative: cursorY - scrollTop, left: cursorX, leftRelative: cursorX - scrollLeft, scrollTop: scrollTop, scrollLeft: scrollLeft, cellHeight: event.target.clientHeight, cellWidth: event.target.clientWidth }; if (this.menuFitsBelowCursor(cursor, menu, document.body.clientHeight)) { this.positionMenuBelowCursor(cursor, menu); } else { if (this.menuFitsAboveCursor(cursor, menu)) { this.positionMenuAboveCursor(cursor, menu); } else { this.positionMenuBelowCursor(cursor, menu); } } if (this.menuFitsOnRightOfCursor(cursor, menu, document.body.clientWidth)) { this.positionMenuOnRightOfCursor(cursor, menu); } else { this.positionMenuOnLeftOfCursor(cursor, menu); } }; ContextMenu.prototype.menuFitsAboveCursor = function(cursor, menu) { return cursor.topRelative >= menu.offsetHeight; }; ContextMenu.prototype.menuFitsBelowCursor = function(cursor, menu, viewportHeight) { return cursor.topRelative + menu.offsetHeight <= viewportHeight; }; ContextMenu.prototype.menuFitsOnRightOfCursor = function(cursor, menu, viewportHeight) { return cursor.leftRelative + menu.offsetWidth <= viewportHeight; }; ContextMenu.prototype.positionMenuBelowCursor = function(cursor, menu) { menu.style.top = cursor.top + 'px'; }; ContextMenu.prototype.positionMenuAboveCursor = function(cursor, menu, subMenu) { if (subMenu) { menu.style.top = (cursor.top + cursor.cellHeight - menu.offsetHeight) + 'px'; } else { menu.style.top = (cursor.top - menu.offsetHeight) + 'px'; } }; ContextMenu.prototype.positionMenuOnRightOfCursor = function(cursor, menu, subMenu) { if (subMenu) { menu.style.left = 1 + cursor.left + cursor.cellWidth + 'px'; } else { menu.style.left = 1 + cursor.left + 'px'; } }; ContextMenu.prototype.positionMenuOnLeftOfCursor = function(cursor, menu, subMenu) { if (subMenu) { menu.style.left = (cursor.left - menu.offsetWidth) + 'px'; } else { menu.style.left = (cursor.left - menu.offsetWidth) + 'px'; } }; ContextMenu.utils = {}; ContextMenu.utils.normalizeSelection = function(selRange) { return { start: selRange.getTopLeftCorner(), end: selRange.getBottomRightCorner() }; }; ContextMenu.utils.isSeparator = function(cell) { return dom.hasClass(cell, 'htSeparator'); }; ContextMenu.utils.hasSubMenu = function(cell) { return dom.hasClass(cell, 'htSubmenu'); }; ContextMenu.utils.isDisabled = function(cell) { return dom.hasClass(cell, 'htDisabled'); }; ContextMenu.prototype.enable = function() { if (!this.enabled) { this.enabled = true; this.bindMouseEvents(); } }; ContextMenu.prototype.disable = function() { if (this.enabled) { this.enabled = false; this.closeAll(); this.unbindMouseEvents(); this.unbindTableEvents(); } }; ContextMenu.prototype.destroy = function() { this.closeAll(); while (this.menus.length > 0) { var menu = this.menus.pop(); this.triggerRows.pop(); if (menu) { this.close(menu); if (!this.isMenuEnabledByOtherHotInstance()) { this.removeMenu(menu); } } } this.unbindMouseEvents(); this.unbindTableEvents(); }; ContextMenu.prototype.isMenuEnabledByOtherHotInstance = function() { var hotContainers = document.querySelectorAll('.handsontable'); var menuEnabled = false; for (var i = 0, len = hotContainers.length; i < len; i++) { var instance = this.htMenus[hotContainers[i].id]; if (instance && instance.getSettings().contextMenu) { menuEnabled = true; break; } } return menuEnabled; }; ContextMenu.prototype.removeMenu = function(menu) { if (menu.parentNode) { this.menu.parentNode.removeChild(menu); } }; ContextMenu.prototype.align = function(range, type, alignment) { align.call(this, range, type, alignment); }; ContextMenu.SEPARATOR = {name: "---------"}; function updateHeight() { if (this.rootElement.className.indexOf('htContextMenu')) { return; } var realSeparatorHeight = 0, realEntrySize = 0, dataSize = this.getSettings().data.length, currentHiderWidth = parseInt(this.view.wt.wtTable.hider.style.width, 10); for (var i = 0; i < dataSize; i++) { if (this.getSettings().data[i].name == ContextMenu.SEPARATOR.name) { realSeparatorHeight += 1; } else { realEntrySize += 26; } } this.view.wt.wtTable.holder.style.width = currentHiderWidth + 22 + "px"; this.view.wt.wtTable.holder.style.height = realEntrySize + realSeparatorHeight + 4 + "px"; } function prepareVerticalAlignClass(className, alignment) { if (className.indexOf(alignment) != -1) { return className; } className = className.replace('htTop', '').replace('htMiddle', '').replace('htBottom', '').replace(' ', ''); className += " " + alignment; return className; } function prepareHorizontalAlignClass(className, alignment) { if (className.indexOf(alignment) != -1) { return className; } className = className.replace('htLeft', '').replace('htCenter', '').replace('htRight', '').replace('htJustify', '').replace(' ', ''); className += " " + alignment; return className; } function getAlignmentClasses(range) { var classesArray = {}; for (var row = range.from.row; row <= range.to.row; row++) { for (var col = range.from.col; col <= range.to.col; col++) { if (!classesArray[row]) { classesArray[row] = []; } classesArray[row][col] = this.getCellMeta(row, col).className; } } return classesArray; } function doAlign(row, col, type, alignment) { var cellMeta = this.getCellMeta(row, col), className = alignment; if (cellMeta.className) { if (type === 'vertical') { className = prepareVerticalAlignClass(cellMeta.className, alignment); } else { className = prepareHorizontalAlignClass(cellMeta.className, alignment); } } this.setCellMeta(row, col, 'className', className); } function align(range, type, alignment) { var stateBefore = getAlignmentClasses.call(this, range); this.runHooks('beforeCellAlignment', stateBefore, range, type, alignment); if (range.from.row == range.to.row && range.from.col == range.to.col) { doAlign.call(this, range.from.row, range.from.col, type, alignment); } else { for (var row = range.from.row; row <= range.to.row; row++) { for (var col = range.from.col; col <= range.to.col; col++) { doAlign.call(this, row, col, type, alignment); } } } this.render(); } function init() { var instance = this; var contextMenuSetting = instance.getSettings().contextMenu; var customOptions = helper.isObject(contextMenuSetting) ? contextMenuSetting : {}; if (contextMenuSetting) { if (!instance.contextMenu) { instance.contextMenu = new ContextMenu(instance, customOptions); } instance.contextMenu.enable(); } else if (instance.contextMenu) { instance.contextMenu.destroy(); delete instance.contextMenu; } } Handsontable.hooks.add('afterInit', init); Handsontable.hooks.add('afterUpdateSettings', init); Handsontable.hooks.add('afterInit', updateHeight); Handsontable.hooks.register('afterContextMenuDefaultOptions'); Handsontable.hooks.register('afterContextMenuShow'); Handsontable.hooks.register('afterContextMenuHide'); Handsontable.ContextMenu = ContextMenu; //# },{"./../../dom.js":34,"./../../eventManager.js":48,"./../../helpers.js":49,"./../../plugins.js":52}],59:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { default: {get: function() { return $__default; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47_plugins_46_js__, $___46__46__47__95_base_46_js__, $__zeroclipboard__; var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47_eventManager_46_js__ = require("./../../eventManager.js"), $___46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47_eventManager_46_js__}).eventManager; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; var BasePlugin = ($___46__46__47__95_base_46_js__ = require("./../_base.js"), $___46__46__47__95_base_46_js__ && $___46__46__47__95_base_46_js__.__esModule && $___46__46__47__95_base_46_js__ || {default: $___46__46__47__95_base_46_js__}).default; var ZeroClipboard = ($__zeroclipboard__ = require("zeroclipboard"), $__zeroclipboard__ && $__zeroclipboard__.__esModule && $__zeroclipboard__ || {default: $__zeroclipboard__}).default; var ContextMenuCopyPaste = function ContextMenuCopyPaste(hotInstance) { var $__4 = this; $traceurRuntime.superConstructor($ContextMenuCopyPaste).call(this, hotInstance); this.swfPath = null; this.hotContextMenu = null; this.outsideClickDeselectsCache = null; this.hot.addHook('afterContextMenuShow', (function(htContextMenu) { return $__4.setupZeroClipboard(htContextMenu); })); this.hot.addHook('afterInit', (function() { return $__4.afterInit(); })); this.hot.addHook('afterContextMenuDefaultOptions', (function(options) { return $__4.addToContextMenu(options); })); }; var $ContextMenuCopyPaste = ContextMenuCopyPaste; ($traceurRuntime.createClass)(ContextMenuCopyPaste, { afterInit: function() { if (!this.hot.getSettings().contextMenuCopyPaste) { return; } else if (typeof this.hot.getSettings().contextMenuCopyPaste == 'object') { this.swfPath = this.hot.getSettings().contextMenuCopyPaste.swfPath; } if (typeof ZeroClipboard === 'undefined') { throw new Error("To be able to use the Copy/Paste feature from the context menu, you need to manualy include ZeroClipboard.js file to your website."); } try { new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); } catch (exception) { if ('undefined' == typeof navigator.mimeTypes['application/x-shockwave-flash']) { throw new Error("To be able to use the Copy/Paste feature from the context menu, your browser needs to have Flash Plugin installed."); } } this.prepareZeroClipboard(); }, prepareZeroClipboard: function() { if (this.swfPath) { ZeroClipboard.config({swfPath: this.swfPath}); } }, getCopyValue: function() { this.hot.copyPaste.setCopyableText(); return this.hot.copyPaste.copyPasteInstance.elTextarea.value; }, addToContextMenu: function(defaultOptions) { if (!this.hot.getSettings().contextMenuCopyPaste) { return; } defaultOptions.items.unshift({ key: 'copy', name: 'Copy' }, { key: 'paste', name: 'Paste', callback: function() { this.copyPaste.triggerPaste(); } }, Handsontable.ContextMenu.SEPARATOR); }, setupZeroClipboard: function(hotContextMenu) { var $__4 = this; var data, zeroClipboardInstance; if (!this.hot.getSettings().contextMenuCopyPaste) { return; } this.hotContextMenu = hotContextMenu; data = this.hotContextMenu.getData(); for (var i = 0, ilen = data.length; i < ilen; i++) { if (data[i].key === 'copy') { zeroClipboardInstance = new ZeroClipboard(this.hotContextMenu.getCell(i, 0)); zeroClipboardInstance.off(); zeroClipboardInstance.on('copy', (function(event) { var clipboard = event.clipboardData; clipboard.setData('text/plain', $__4.getCopyValue()); $__4.hot.getSettings().outsideClickDeselects = $__4.outsideClickDeselectsCache; })); this.bindEvents(); break; } } }, removeCurrentClass: function() { if (this.hotContextMenu.rootElement) { var element = this.hotContextMenu.rootElement.querySelector('td.current'); if (element) { dom.removeClass(element, 'current'); } } this.outsideClickDeselectsCache = this.hot.getSettings().outsideClickDeselects; this.hot.getSettings().outsideClickDeselects = false; }, removeZeroClipboardClass: function() { if (this.hotContextMenu.rootElement) { var element = this.hotContextMenu.rootElement.querySelector('td.zeroclipboard-is-hover'); if (element) { dom.removeClass(element, 'zeroclipboard-is-hover'); } } this.hot.getSettings().outsideClickDeselects = this.outsideClickDeselectsCache; }, bindEvents: function() { var $__4 = this; var eventManager = eventManagerObject(this.hotContextMenu); eventManager.addEventListener(document, 'mouseenter', (function() { return $__4.removeCurrentClass(); })); eventManager.addEventListener(document, 'mouseleave', (function() { return $__4.removeZeroClipboardClass(); })); } }, {}, BasePlugin); var $__default = ContextMenuCopyPaste; registerPlugin('contextMenuCopyPaste', ContextMenuCopyPaste); //# },{"./../../dom.js":34,"./../../eventManager.js":48,"./../../plugins.js":52,"./../_base.js":53,"zeroclipboard":"zeroclipboard"}],60:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { CopyPaste: {get: function() { return CopyPaste; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_helpers_46_js__, $___46__46__47__46__46__47_3rdparty_47_sheetclip_46_js__, $___46__46__47__46__46__47_3rdparty_47_copypaste_46_js__, $___46__46__47__46__46__47_plugins_46_js__, $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__, $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__; var helper = ($___46__46__47__46__46__47_helpers_46_js__ = require("./../../helpers.js"), $___46__46__47__46__46__47_helpers_46_js__ && $___46__46__47__46__46__47_helpers_46_js__.__esModule && $___46__46__47__46__46__47_helpers_46_js__ || {default: $___46__46__47__46__46__47_helpers_46_js__}); var SheetClip = ($___46__46__47__46__46__47_3rdparty_47_sheetclip_46_js__ = require("./../../3rdparty/sheetclip.js"), $___46__46__47__46__46__47_3rdparty_47_sheetclip_46_js__ && $___46__46__47__46__46__47_3rdparty_47_sheetclip_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_sheetclip_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_sheetclip_46_js__}).default; var copyPasteManager = ($___46__46__47__46__46__47_3rdparty_47_copypaste_46_js__ = require("./../../3rdparty/copypaste.js"), $___46__46__47__46__46__47_3rdparty_47_copypaste_46_js__ && $___46__46__47__46__46__47_3rdparty_47_copypaste_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_copypaste_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_copypaste_46_js__}).copyPasteManager; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; var WalkontableCellCoords = ($___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ = require("./../../3rdparty/walkontable/src/cellCoords.js"), $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__}).WalkontableCellCoords; var WalkontableCellRange = ($___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__ = require("./../../3rdparty/walkontable/src/cellRange.js"), $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__ && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__}).WalkontableCellRange; ; function CopyPastePlugin(instance) { var _this = this; this.copyPasteInstance = copyPasteManager(); this.copyPasteInstance.onCut(onCut); this.copyPasteInstance.onPaste(onPaste); instance.addHook('beforeKeyDown', onBeforeKeyDown); function onCut() { if (!instance.isListening()) { return; } instance.selection.empty(); } function onPaste(str) { var input, inputArray, selected, coordsFrom, coordsTo, cellRange, topLeftCorner, bottomRightCorner, areaStart, areaEnd; if (!instance.isListening() || !instance.selection.isSelected()) { return; } input = str; inputArray = SheetClip.parse(input); selected = instance.getSelected(); coordsFrom = new WalkontableCellCoords(selected[0], selected[1]); coordsTo = new WalkontableCellCoords(selected[2], selected[3]); cellRange = new WalkontableCellRange(coordsFrom, coordsFrom, coordsTo); topLeftCorner = cellRange.getTopLeftCorner(); bottomRightCorner = cellRange.getBottomRightCorner(); areaStart = topLeftCorner; areaEnd = new WalkontableCellCoords(Math.max(bottomRightCorner.row, inputArray.length - 1 + topLeftCorner.row), Math.max(bottomRightCorner.col, inputArray[0].length - 1 + topLeftCorner.col)); instance.addHookOnce('afterChange', function(changes, source) { if (changes && changes.length) { this.selectCell(areaStart.row, areaStart.col, areaEnd.row, areaEnd.col); } }); instance.populateFromArray(areaStart.row, areaStart.col, inputArray, areaEnd.row, areaEnd.col, 'paste', instance.getSettings().pasteMode); } function onBeforeKeyDown(event) { var ctrlDown; if (instance.getSelected()) { if (helper.isCtrlKey(event.keyCode)) { _this.setCopyableText(); event.stopImmediatePropagation(); return; } ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; if (event.keyCode == helper.keyCode.A && ctrlDown) { instance._registerTimeout(setTimeout(helper.proxy(_this.setCopyableText, _this), 0)); } } } this.destroy = function() { this.copyPasteInstance.removeCallback(onCut); this.copyPasteInstance.removeCallback(onPaste); this.copyPasteInstance.destroy(); instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; instance.addHook('afterDestroy', helper.proxy(this.destroy, this)); this.triggerPaste = helper.proxy(this.copyPasteInstance.triggerPaste, this.copyPasteInstance); this.triggerCut = helper.proxy(this.copyPasteInstance.triggerCut, this.copyPasteInstance); this.setCopyableText = function() { var settings = instance.getSettings(); var copyRowsLimit = settings.copyRowsLimit; var copyColsLimit = settings.copyColsLimit; var selRange = instance.getSelectedRange(); var topLeft = selRange.getTopLeftCorner(); var bottomRight = selRange.getBottomRightCorner(); var startRow = topLeft.row; var startCol = topLeft.col; var endRow = bottomRight.row; var endCol = bottomRight.col; var finalEndRow = Math.min(endRow, startRow + copyRowsLimit - 1); var finalEndCol = Math.min(endCol, startCol + copyColsLimit - 1); instance.copyPaste.copyPasteInstance.copyable(instance.getCopyableData(startRow, startCol, finalEndRow, finalEndCol)); if (endRow !== finalEndRow || endCol !== finalEndCol) { Handsontable.hooks.run(instance, "afterCopyLimit", endRow - startRow + 1, endCol - startCol + 1, copyRowsLimit, copyColsLimit); } }; } function init() { var instance = this, pluginEnabled = instance.getSettings().copyPaste !== false; if (pluginEnabled && !instance.copyPaste) { instance.copyPaste = new CopyPastePlugin(instance); } else if (!pluginEnabled && instance.copyPaste) { instance.copyPaste.destroy(); delete instance.copyPaste; } } Handsontable.hooks.add('afterInit', init); Handsontable.hooks.add('afterUpdateSettings', init); Handsontable.hooks.register('afterCopyLimit'); //# },{"./../../3rdparty/copypaste.js":3,"./../../3rdparty/sheetclip.js":5,"./../../3rdparty/walkontable/src/cellCoords.js":8,"./../../3rdparty/walkontable/src/cellRange.js":9,"./../../helpers.js":49,"./../../plugins.js":52}],61:[function(require,module,exports){ "use strict"; var $___46__46__47__46__46__47_plugins_46_js__, $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__, $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_selection_46_js__; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; var WalkontableCellRange = ($___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__ = require("./../../3rdparty/walkontable/src/cellRange.js"), $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__ && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__}).WalkontableCellRange; var WalkontableSelection = ($___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_selection_46_js__ = require("./../../3rdparty/walkontable/src/selection.js"), $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_selection_46_js__ && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_selection_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_selection_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_selection_46_js__}).WalkontableSelection; function CustomBorders() {} var instance; var checkEnable = function(customBorders) { if (typeof customBorders === "boolean") { if (customBorders === true) { return true; } } if (typeof customBorders === "object") { if (customBorders.length > 0) { return true; } } return false; }; var init = function() { if (checkEnable(this.getSettings().customBorders)) { if (!this.customBorders) { instance = this; this.customBorders = new CustomBorders(); } } }; var getSettingIndex = function(className) { for (var i = 0; i < instance.view.wt.selections.length; i++) { if (instance.view.wt.selections[i].settings.className == className) { return i; } } return -1; }; var insertBorderIntoSettings = function(border) { var coordinates = { row: border.row, col: border.col }; var selection = new WalkontableSelection(border, new WalkontableCellRange(coordinates, coordinates, coordinates)); var index = getSettingIndex(border.className); if (index >= 0) { instance.view.wt.selections[index] = selection; } else { instance.view.wt.selections.push(selection); } }; var prepareBorderFromCustomAdded = function(row, col, borderObj) { var border = createEmptyBorders(row, col); border = extendDefaultBorder(border, borderObj); this.setCellMeta(row, col, 'borders', border); insertBorderIntoSettings(border); }; var prepareBorderFromCustomAddedRange = function(rowObj) { var range = rowObj.range; for (var row = range.from.row; row <= range.to.row; row++) { for (var col = range.from.col; col <= range.to.col; col++) { var border = createEmptyBorders(row, col); var add = 0; if (row == range.from.row) { add++; if (rowObj.hasOwnProperty('top')) { border.top = rowObj.top; } } if (row == range.to.row) { add++; if (rowObj.hasOwnProperty('bottom')) { border.bottom = rowObj.bottom; } } if (col == range.from.col) { add++; if (rowObj.hasOwnProperty('left')) { border.left = rowObj.left; } } if (col == range.to.col) { add++; if (rowObj.hasOwnProperty('right')) { border.right = rowObj.right; } } if (add > 0) { this.setCellMeta(row, col, 'borders', border); insertBorderIntoSettings(border); } } } }; var createClassName = function(row, col) { return "border_row" + row + "col" + col; }; var createDefaultCustomBorder = function() { return { width: 1, color: '#000' }; }; var createSingleEmptyBorder = function() { return {hide: true}; }; var createDefaultHtBorder = function() { return { width: 1, color: '#000', cornerVisible: false }; }; var createEmptyBorders = function(row, col) { return { className: createClassName(row, col), border: createDefaultHtBorder(), row: row, col: col, top: createSingleEmptyBorder(), right: createSingleEmptyBorder(), bottom: createSingleEmptyBorder(), left: createSingleEmptyBorder() }; }; var extendDefaultBorder = function(defaultBorder, customBorder) { if (customBorder.hasOwnProperty('border')) { defaultBorder.border = customBorder.border; } if (customBorder.hasOwnProperty('top')) { defaultBorder.top = customBorder.top; } if (customBorder.hasOwnProperty('right')) { defaultBorder.right = customBorder.right; } if (customBorder.hasOwnProperty('bottom')) { defaultBorder.bottom = customBorder.bottom; } if (customBorder.hasOwnProperty('left')) { defaultBorder.left = customBorder.left; } return defaultBorder; }; var removeBordersFromDom = function(borderClassName) { var borders = document.querySelectorAll("." + borderClassName); for (var i = 0; i < borders.length; i++) { if (borders[i]) { if (borders[i].nodeName != 'TD') { var parent = borders[i].parentNode; if (parent.parentNode) { parent.parentNode.removeChild(parent); } } } } }; var removeAllBorders = function(row, col) { var borderClassName = createClassName(row, col); removeBordersFromDom(borderClassName); this.removeCellMeta(row, col, 'borders'); }; var setBorder = function(row, col, place, remove) { var bordersMeta = this.getCellMeta(row, col).borders; if (!bordersMeta || bordersMeta.border == undefined) { bordersMeta = createEmptyBorders(row, col); } if (remove) { bordersMeta[place] = createSingleEmptyBorder(); } else { bordersMeta[place] = createDefaultCustomBorder(); } this.setCellMeta(row, col, 'borders', bordersMeta); var borderClassName = createClassName(row, col); removeBordersFromDom(borderClassName); insertBorderIntoSettings(bordersMeta); this.render(); }; var prepareBorder = function(range, place, remove) { if (range.from.row == range.to.row && range.from.col == range.to.col) { if (place == "noBorders") { removeAllBorders.call(this, range.from.row, range.from.col); } else { setBorder.call(this, range.from.row, range.from.col, place, remove); } } else { switch (place) { case "noBorders": for (var column = range.from.col; column <= range.to.col; column++) { for (var row = range.from.row; row <= range.to.row; row++) { removeAllBorders.call(this, row, column); } } break; case "top": for (var topCol = range.from.col; topCol <= range.to.col; topCol++) { setBorder.call(this, range.from.row, topCol, place, remove); } break; case "right": for (var rowRight = range.from.row; rowRight <= range.to.row; rowRight++) { setBorder.call(this, rowRight, range.to.col, place); } break; case "bottom": for (var bottomCol = range.from.col; bottomCol <= range.to.col; bottomCol++) { setBorder.call(this, range.to.row, bottomCol, place); } break; case "left": for (var rowLeft = range.from.row; rowLeft <= range.to.row; rowLeft++) { setBorder.call(this, rowLeft, range.from.col, place); } break; } } }; var checkSelectionBorders = function(hot, direction) { var atLeastOneHasBorder = false; hot.getSelectedRange().forAll(function(r, c) { var metaBorders = hot.getCellMeta(r, c).borders; if (metaBorders) { if (direction) { if (!metaBorders[direction].hasOwnProperty('hide')) { atLeastOneHasBorder = true; return false; } } else { atLeastOneHasBorder = true; return false; } } }); return atLeastOneHasBorder; }; var markSelected = function(label) { return "<span class='selected'>" + String.fromCharCode(10003) + "</span>" + label; }; var addBordersOptionsToContextMenu = function(defaultOptions) { if (!this.getSettings().customBorders) { return; } defaultOptions.items.push(Handsontable.ContextMenu.SEPARATOR); defaultOptions.items.push({ key: 'borders', name: 'Borders', submenu: {items: { top: { name: function() { var label = "Top"; var hasBorder = checkSelectionBorders(this, 'top'); if (hasBorder) { label = markSelected(label); } return label; }, callback: function() { var hasBorder = checkSelectionBorders(this, 'top'); prepareBorder.call(this, this.getSelectedRange(), 'top', hasBorder); }, disabled: false }, right: { name: function() { var label = 'Right'; var hasBorder = checkSelectionBorders(this, 'right'); if (hasBorder) { label = markSelected(label); } return label; }, callback: function() { var hasBorder = checkSelectionBorders(this, 'right'); prepareBorder.call(this, this.getSelectedRange(), 'right', hasBorder); }, disabled: false }, bottom: { name: function() { var label = 'Bottom'; var hasBorder = checkSelectionBorders(this, 'bottom'); if (hasBorder) { label = markSelected(label); } return label; }, callback: function() { var hasBorder = checkSelectionBorders(this, 'bottom'); prepareBorder.call(this, this.getSelectedRange(), 'bottom', hasBorder); }, disabled: false }, left: { name: function() { var label = 'Left'; var hasBorder = checkSelectionBorders(this, 'left'); if (hasBorder) { label = markSelected(label); } return label; }, callback: function() { var hasBorder = checkSelectionBorders(this, 'left'); prepareBorder.call(this, this.getSelectedRange(), 'left', hasBorder); }, disabled: false }, remove: { name: 'Remove border(s)', callback: function() { prepareBorder.call(this, this.getSelectedRange(), 'noBorders'); }, disabled: function() { return !checkSelectionBorders(this); } } }} }); }; Handsontable.hooks.add('beforeInit', init); Handsontable.hooks.add('afterContextMenuDefaultOptions', addBordersOptionsToContextMenu); Handsontable.hooks.add('afterInit', function() { var customBorders = this.getSettings().customBorders; if (customBorders) { for (var i = 0; i < customBorders.length; i++) { if (customBorders[i].range) { prepareBorderFromCustomAddedRange.call(this, customBorders[i]); } else { prepareBorderFromCustomAdded.call(this, customBorders[i].row, customBorders[i].col, customBorders[i]); } } this.render(); this.view.wt.draw(true); } }); Handsontable.CustomBorders = CustomBorders; //# },{"./../../3rdparty/walkontable/src/cellRange.js":9,"./../../3rdparty/walkontable/src/selection.js":20,"./../../plugins.js":52}],62:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { DragToScroll: {get: function() { return DragToScroll; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47_plugins_46_js__; var eventManagerObject = ($___46__46__47__46__46__47_eventManager_46_js__ = require("./../../eventManager.js"), $___46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47_eventManager_46_js__}).eventManager; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; Handsontable.plugins.DragToScroll = DragToScroll; function DragToScroll() { this.boundaries = null; this.callback = null; } DragToScroll.prototype.setBoundaries = function(boundaries) { this.boundaries = boundaries; }; DragToScroll.prototype.setCallback = function(callback) { this.callback = callback; }; DragToScroll.prototype.check = function(x, y) { var diffX = 0; var diffY = 0; if (y < this.boundaries.top) { diffY = y - this.boundaries.top; } else if (y > this.boundaries.bottom) { diffY = y - this.boundaries.bottom; } if (x < this.boundaries.left) { diffX = x - this.boundaries.left; } else if (x > this.boundaries.right) { diffX = x - this.boundaries.right; } this.callback(diffX, diffY); }; var dragToScroll; var instance; if (typeof Handsontable !== 'undefined') { var setupListening = function(instance) { instance.dragToScrollListening = false; var scrollHandler = instance.view.wt.wtTable.holder; dragToScroll = new DragToScroll(); if (scrollHandler === window) { return; } else { dragToScroll.setBoundaries(scrollHandler.getBoundingClientRect()); } dragToScroll.setCallback(function(scrollX, scrollY) { if (scrollX < 0) { scrollHandler.scrollLeft -= 50; } else if (scrollX > 0) { scrollHandler.scrollLeft += 50; } if (scrollY < 0) { scrollHandler.scrollTop -= 20; } else if (scrollY > 0) { scrollHandler.scrollTop += 20; } }); instance.dragToScrollListening = true; }; } Handsontable.hooks.add('afterInit', function() { var instance = this; var eventManager = eventManagerObject(this); eventManager.addEventListener(document, 'mouseup', function() { instance.dragToScrollListening = false; }); eventManager.addEventListener(document, 'mousemove', function(event) { if (instance.dragToScrollListening) { dragToScroll.check(event.clientX, event.clientY); } }); }); Handsontable.hooks.add('afterDestroy', function() { eventManagerObject(this).clear(); }); Handsontable.hooks.add('afterOnCellMouseDown', function() { setupListening(this); }); Handsontable.hooks.add('afterOnCellCornerMouseDown', function() { setupListening(this); }); Handsontable.plugins.DragToScroll = DragToScroll; //# },{"./../../eventManager.js":48,"./../../plugins.js":52}],63:[function(require,module,exports){ "use strict"; var $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_plugins_46_js__; var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; function Grouping(instance) { var groups = []; var item = { id: '', level: 0, hidden: 0, rows: [], cols: [] }; var counters = { rows: 0, cols: 0 }; var levels = { rows: 0, cols: 0 }; var hiddenRows = []; var hiddenCols = []; var classes = { 'groupIndicatorContainer': 'htGroupIndicatorContainer', 'groupIndicator': function(direction) { return 'ht' + direction + 'Group'; }, 'groupStart': 'htGroupStart', 'collapseButton': 'htCollapseButton', 'expandButton': 'htExpandButton', 'collapseGroupId': function(id) { return 'htCollapse-' + id; }, 'collapseFromLevel': function(direction, level) { return 'htCollapse' + direction + 'FromLevel-' + level; }, 'clickable': 'clickable', 'levelTrigger': 'htGroupLevelTrigger' }; var compare = function(property, orderDirection) { return function(item1, item2) { return typeof(orderDirection) === 'undefined' || orderDirection === 'asc' ? item1[property] - item2[property] : item2[property] - item1[property]; }; }; var range = function(from, to) { var arr = []; while (from <= to) { arr.push(from++); } return arr; }; var getRangeGroups = function(dataType, from, to) { var cells = [], cell = { row: null, col: null }; if (dataType == "cols") { while (from <= to) { cell = { row: -1, col: from++ }; cells.push(cell); } } else { while (from <= to) { cell = { row: from++, col: -1 }; cells.push(cell); } } var cellsGroups = getCellsGroups(cells), totalRows = 0, totalCols = 0; for (var i = 0; i < cellsGroups.length; i++) { totalRows += cellsGroups[i].filter(function(item) { return item['rows']; }).length; totalCols += cellsGroups[i].filter(function(item) { return item['cols']; }).length; } return { total: { rows: totalRows, cols: totalCols }, groups: cellsGroups }; }; var getCellsGroups = function(cells) { var _groups = []; for (var i = 0; i < cells.length; i++) { _groups.push(getCellGroups(cells[i])); } return _groups; }; var getCellGroups = function(coords, groupLevel, groupType) { var row = coords.row, col = coords.col; var tmpRow = (row === -1 ? 0 : row), tmpCol = (col === -1 ? 0 : col); var _groups = []; for (var i = 0; i < groups.length; i++) { var group = groups[i], id = group['id'], level = group['level'], rows = group['rows'] || [], cols = group['cols'] || []; if (_groups.indexOf(id) === -1) { if (rows.indexOf(tmpRow) !== -1 || cols.indexOf(tmpCol) !== -1) { _groups.push(group); } } } if (col === -1) { _groups = _groups.concat(getColGroups()); } else if (row === -1) { _groups = _groups.concat(getRowGroups()); } if (groupLevel) { _groups = _groups.filter(function(item) { return item['level'] === groupLevel; }); } if (groupType) { if (groupType === 'cols') { _groups = _groups.filter(function(item) { return item['cols']; }); } else if (groupType === 'rows') { _groups = _groups.filter(function(item) { return item['rows']; }); } } var tmp = []; return _groups.filter(function(item) { if (tmp.indexOf(item.id) === -1) { tmp.push(item.id); return item; } }); }; var getGroupById = function(id) { for (var i = 0, groupsLength = groups.length; i < groupsLength; i++) { if (groups[i].id == id) { return groups[i]; } } return false; }; var getGroupByRowAndLevel = function(row, level) { for (var i = 0, groupsLength = groups.length; i < groupsLength; i++) { if (groups[i].level == level && groups[i].rows && groups[i].rows.indexOf(row) > -1) { return groups[i]; } } return false; }; var getGroupByColAndLevel = function(col, level) { for (var i = 0, groupsLength = groups.length; i < groupsLength; i++) { if (groups[i].level == level && groups[i].cols && groups[i].cols.indexOf(col) > -1) { return groups[i]; } } return false; }; var getColGroups = function() { var result = []; for (var i = 0, groupsLength = groups.length; i < groupsLength; i++) { if (Array.isArray(groups[i]['cols'])) { result.push(groups[i]); } } return result; }; var getColGroupsByLevel = function(level) { var result = []; for (var i = 0, groupsLength = groups.length; i < groupsLength; i++) { if (groups[i]['cols'] && groups[i]['level'] === level) { result.push(groups[i]); } } return result; }; var getRowGroups = function() { var result = []; for (var i = 0, groupsLength = groups.length; i < groupsLength; i++) { if (Array.isArray(groups[i]['rows'])) { result.push(groups[i]); } } return result; }; var getRowGroupsByLevel = function(level) { var result = []; for (var i = 0, groupsLength = groups.length; i < groupsLength; i++) { if (groups[i]['rows'] && groups[i]['level'] === level) { result.push(groups[i]); } } return result; }; var getLastLevelColsInRange = function(rangeGroups) { var level = 0; if (rangeGroups.length) { rangeGroups.forEach(function(items) { items = items.filter(function(item) { return item['cols']; }); if (items.length) { var sortedGroup = items.sort(compare('level', 'desc')), lastLevel = sortedGroup[0].level; if (level < lastLevel) { level = lastLevel; } } }); } return level; }; var getLastLevelRowsInRange = function(rangeGroups) { var level = 0; if (rangeGroups.length) { rangeGroups.forEach(function(items) { items = items.filter(function(item) { return item['rows']; }); if (items.length) { var sortedGroup = items.sort(compare('level', 'desc')), lastLevel = sortedGroup[0].level; if (level < lastLevel) { level = lastLevel; } } }); } return level; }; var groupCols = function(from, to) { var rangeGroups = getRangeGroups("cols", from, to), lastLevel = getLastLevelColsInRange(rangeGroups.groups); if (lastLevel === levels.cols) { levels.cols++; } else if (lastLevel > levels.cols) { levels.cols = lastLevel + 1; } if (!counters.cols) { counters.cols = getColGroups().length; } counters.cols++; groups.push({ id: 'c' + counters.cols, level: lastLevel + 1, cols: range(from, to), hidden: 0 }); }; var groupRows = function(from, to) { var rangeGroups = getRangeGroups("rows", from, to), lastLevel = getLastLevelRowsInRange(rangeGroups.groups); levels.rows = Math.max(levels.rows, lastLevel + 1); if (!counters.rows) { counters.rows = getRowGroups().length; } counters.rows++; groups.push({ id: 'r' + counters.rows, level: lastLevel + 1, rows: range(from, to), hidden: 0 }); }; var showHideGroups = function(hidden, groups) { var level; for (var i = 0, groupsLength = groups.length; i < groupsLength; i++) { groups[i].hidden = hidden; level = groups[i].level; if (!hiddenRows[level]) { hiddenRows[level] = []; } if (!hiddenCols[level]) { hiddenCols[level] = []; } if (groups[i].rows) { for (var j = 0, rowsLength = groups[i].rows.length; j < rowsLength; j++) { if (hidden > 0) { hiddenRows[level][groups[i].rows[j]] = true; } else { hiddenRows[level][groups[i].rows[j]] = void 0; } } } else if (groups[i].cols) { for (var j = 0, colsLength = groups[i].cols.length; j < colsLength; j++) { if (hidden > 0) { hiddenCols[level][groups[i].cols[j]] = true; } else { hiddenCols[level][groups[i].cols[j]] = void 0; } } } } }; var nextIndexSharesLevel = function(dimension, currentPosition, level, currentGroupId) { var nextCellGroupId, levelsByOrder; switch (dimension) { case 'rows': nextCellGroupId = getGroupByRowAndLevel(currentPosition + 1, level).id; levelsByOrder = Handsontable.Grouping.getGroupLevelsByRows(); break; case 'cols': nextCellGroupId = getGroupByColAndLevel(currentPosition + 1, level).id; levelsByOrder = Handsontable.Grouping.getGroupLevelsByCols(); break; } return !!(levelsByOrder[currentPosition + 1] && levelsByOrder[currentPosition + 1].indexOf(level) > -1 && currentGroupId == nextCellGroupId); }; var previousIndexSharesLevel = function(dimension, currentPosition, level, currentGroupId) { var previousCellGroupId, levelsByOrder; switch (dimension) { case 'rows': previousCellGroupId = getGroupByRowAndLevel(currentPosition - 1, level).id; levelsByOrder = Handsontable.Grouping.getGroupLevelsByRows(); break; case 'cols': previousCellGroupId = getGroupByColAndLevel(currentPosition - 1, level).id; levelsByOrder = Handsontable.Grouping.getGroupLevelsByCols(); break; } return !!(levelsByOrder[currentPosition - 1] && levelsByOrder[currentPosition - 1].indexOf(level) > -1 && currentGroupId == previousCellGroupId); }; var isLastIndexOfTheLine = function(dimension, index, level, currentGroupId) { if (index === 0) { return false; } var levelsByOrder, entriesLength, previousSharesLevel = previousIndexSharesLevel(dimension, index, level, currentGroupId), nextSharesLevel = nextIndexSharesLevel(dimension, index, level, currentGroupId), nextIsHidden = false; switch (dimension) { case 'rows': levelsByOrder = Handsontable.Grouping.getGroupLevelsByRows(); entriesLength = instance.countRows(); for (var i = 0; i <= levels.rows; i++) { if (hiddenRows[i] && hiddenRows[i][index + 1]) { nextIsHidden = true; break; } } break; case 'cols': levelsByOrder = Handsontable.Grouping.getGroupLevelsByCols(); entriesLength = instance.countCols(); for (var i = 0; i <= levels.cols; i++) { if (hiddenCols[i] && hiddenCols[i][index + 1]) { nextIsHidden = true; break; } } break; } if (previousSharesLevel) { if (index == entriesLength - 1) { return true; } else if (!nextSharesLevel || (nextSharesLevel && nextIsHidden)) { return true; } else if (!levelsByOrder[index + 1]) { return true; } } return false; }; var isLastHidden = function(dataType) { var levelAmount; switch (dataType) { case 'rows': levelAmount = levels.rows; for (var j = 0; j <= levelAmount; j++) { if (hiddenRows[j] && hiddenRows[j][instance.countRows() - 1]) { return true; } } break; case 'cols': levelAmount = levels.cols; for (var j = 0; j <= levelAmount; j++) { if (hiddenCols[j] && hiddenCols[j][instance.countCols() - 1]) { return true; } } break; } return false; }; var isFirstIndexOfTheLine = function(dimension, index, level, currentGroupId) { var levelsByOrder, entriesLength, currentGroup = getGroupById(currentGroupId), previousAreHidden = false, arePreviousHidden = function(dimension) { var hidden = false, hiddenArr = dimension == 'rows' ? hiddenRows : hiddenCols; for (var i = 0; i <= levels[dimension]; i++) { tempInd = index; while (currentGroup[dimension].indexOf(tempInd) > -1) { hidden = !!(hiddenArr[i] && hiddenArr[i][tempInd]); tempInd--; } if (hidden) { break; } } return hidden; }, previousSharesLevel = previousIndexSharesLevel(dimension, index, level, currentGroupId), nextSharesLevel = nextIndexSharesLevel(dimension, index, level, currentGroupId), tempInd; switch (dimension) { case 'rows': levelsByOrder = Handsontable.Grouping.getGroupLevelsByRows(); entriesLength = instance.countRows(); previousAreHidden = arePreviousHidden(dimension); break; case 'cols': levelsByOrder = Handsontable.Grouping.getGroupLevelsByCols(); entriesLength = instance.countCols(); previousAreHidden = arePreviousHidden(dimension); break; } if (index == entriesLength - 1) { return false; } else if (index === 0) { if (nextSharesLevel) { return true; } } else if (!previousSharesLevel || (previousSharesLevel && previousAreHidden)) { if (nextSharesLevel) { return true; } } else if (!levelsByOrder[index - 1]) { if (nextSharesLevel) { return true; } } return false; }; var addGroupExpander = function(dataType, index, level, id, elem) { var previousIndexGroupId; switch (dataType) { case 'rows': previousIndexGroupId = getGroupByRowAndLevel(index - 1, level).id; break; case 'cols': previousIndexGroupId = getGroupByColAndLevel(index - 1, level).id; break; } if (!previousIndexGroupId) { return null; } if (index > 0) { if (previousIndexSharesLevel(dataType, index - 1, level, previousIndexGroupId) && previousIndexGroupId != id) { var expanderButton = document.createElement('DIV'); dom.addClass(expanderButton, classes.expandButton); expanderButton.id = 'htExpand-' + previousIndexGroupId; expanderButton.appendChild(document.createTextNode('+')); expanderButton.setAttribute('data-level', level); expanderButton.setAttribute('data-type', dataType); expanderButton.setAttribute('data-hidden', "1"); elem.appendChild(expanderButton); return expanderButton; } } return null; }; var isCollapsed = function(currentPosition) { var rowGroups = getRowGroups(), colGroups = getColGroups(); for (var i = 0, rowGroupsCount = rowGroups.length; i < rowGroupsCount; i++) { if (rowGroups[i].rows.indexOf(currentPosition.row) > -1 && rowGroups[i].hidden) { return true; } } if (currentPosition.col === null) { return false; } for (var i = 0, colGroupsCount = colGroups.length; i < colGroupsCount; i++) { if (colGroups[i].cols.indexOf(currentPosition.col) > -1 && colGroups[i].hidden) { return true; } } return false; }; return { getGroups: function() { return groups; }, getLevels: function() { return levels; }, instance: instance, baseSpareRows: instance.getSettings().minSpareRows, baseSpareCols: instance.getSettings().minSpareCols, getRowGroups: getRowGroups, getColGroups: getColGroups, init: function() { var groupsSetting = instance.getSettings().groups; if (groupsSetting) { if (Array.isArray(groupsSetting)) { Handsontable.Grouping.initGroups(groupsSetting); } } }, initGroups: function(initialGroups) { var that = this; groups = []; initialGroups.forEach(function(item) { var _group = [], isRow = false, isCol = false; if (Array.isArray(item.rows)) { _group = item.rows; isRow = true; } else if (Array.isArray(item.cols)) { _group = item.cols; isCol = true; } var from = _group[0], to = _group[_group.length - 1]; if (isRow) { groupRows(from, to); } else if (isCol) { groupCols(from, to); } }); }, resetGroups: function() { groups = []; counters = { rows: 0, cols: 0 }; levels = { rows: 0, cols: 0 }; var allOccurrences; for (var i in classes) { if (typeof classes[i] != 'function') { allOccurrences = document.querySelectorAll('.' + classes[i]); for (var j = 0, occurrencesLength = allOccurrences.length; j < occurrencesLength; j++) { dom.removeClass(allOccurrences[j], classes[i]); } } } var otherClasses = ['htGroupColClosest', 'htGroupCol']; for (var i = 0, otherClassesLength = otherClasses.length; i < otherClassesLength; i++) { allOccurrences = document.querySelectorAll('.' + otherClasses[i]); for (var j = 0, occurrencesLength = allOccurrences.length; j < occurrencesLength; j++) { dom.removeClass(allOccurrences[j], otherClasses[i]); } } }, updateGroups: function() { var groupSettings = this.getSettings().groups; Handsontable.Grouping.resetGroups(); Handsontable.Grouping.initGroups(groupSettings); }, afterGetRowHeader: function(row, TH) { var currentRowHidden = false; for (var i = 0, levels = hiddenRows.length; i < levels; i++) { if (hiddenRows[i] && hiddenRows[i][row] === true) { currentRowHidden = true; } } if (currentRowHidden) { dom.addClass(TH.parentNode, 'hidden'); } else if (!currentRowHidden && dom.hasClass(TH.parentNode, 'hidden')) { dom.removeClass(TH.parentNode, 'hidden'); } }, afterGetColHeader: function(col, TH) { var rowHeaders = this.view.wt.wtSettings.getSetting('rowHeaders').length, thisColgroup = instance.rootElement.querySelectorAll('colgroup col:nth-child(' + parseInt(col + rowHeaders + 1, 10) + ')'); if (thisColgroup.length === 0) { return; } var currentColHidden = false; for (var i = 0, levels = hiddenCols.length; i < levels; i++) { if (hiddenCols[i] && hiddenCols[i][col] === true) { currentColHidden = true; } } if (currentColHidden) { for (var i = 0, colsAmount = thisColgroup.length; i < colsAmount; i++) { dom.addClass(thisColgroup[i], 'hidden'); } } else if (!currentColHidden && dom.hasClass(thisColgroup[0], 'hidden')) { for (var i = 0, colsAmount = thisColgroup.length; i < colsAmount; i++) { dom.removeClass(thisColgroup[i], 'hidden'); } } }, groupIndicatorsFactory: function(renderersArr, direction) { var groupsLevelsList, getCurrentLevel, getCurrentGroupId, dataType, getGroupByIndexAndLevel, headersType, currentHeaderModifier, createLevelTriggers; switch (direction) { case 'horizontal': groupsLevelsList = Handsontable.Grouping.getGroupLevelsByCols(); getCurrentLevel = function(elem) { return Array.prototype.indexOf.call(elem.parentNode.parentNode.childNodes, elem.parentNode) + 1; }; getCurrentGroupId = function(col, level) { return getGroupByColAndLevel(col, level).id; }; dataType = 'cols'; getGroupByIndexAndLevel = function(col, level) { return getGroupByColAndLevel(col - 1, level); }; headersType = "columnHeaders"; currentHeaderModifier = function(headerRenderers) { if (headerRenderers.length === 1) { var oldFn = headerRenderers[0]; headerRenderers[0] = function(index, elem, level) { if (index < -1) { makeGroupIndicatorsForLevel()(index, elem, level); } else { dom.removeClass(elem, classes.groupIndicatorContainer); oldFn(index, elem, level); } }; } return function() { return headerRenderers; }; }; createLevelTriggers = true; break; case 'vertical': groupsLevelsList = Handsontable.Grouping.getGroupLevelsByRows(); getCurrentLevel = function(elem) { return dom.index(elem) + 1; }; getCurrentGroupId = function(row, level) { return getGroupByRowAndLevel(row, level).id; }; dataType = 'rows'; getGroupByIndexAndLevel = function(row, level) { return getGroupByRowAndLevel(row - 1, level); }; headersType = "rowHeaders"; currentHeaderModifier = function(headerRenderers) { return headerRenderers; }; break; } var createButton = function(parent) { var button = document.createElement('div'); parent.appendChild(button); return { button: button, addClass: function(className) { dom.addClass(button, className); } }; }; var makeGroupIndicatorsForLevel = function() { var directionClassname = direction.charAt(0).toUpperCase() + direction.slice(1); return function(index, elem, level) { level++; var child, collapseButton; while (child = elem.lastChild) { elem.removeChild(child); } dom.addClass(elem, classes.groupIndicatorContainer); var currentGroupId = getCurrentGroupId(index, level); if (index > -1 && (groupsLevelsList[index] && groupsLevelsList[index].indexOf(level) > -1)) { collapseButton = createButton(elem); collapseButton.addClass(classes.groupIndicator(directionClassname)); if (isFirstIndexOfTheLine(dataType, index, level, currentGroupId)) { collapseButton.addClass(classes.groupStart); } if (isLastIndexOfTheLine(dataType, index, level, currentGroupId)) { collapseButton.button.appendChild(document.createTextNode('-')); collapseButton.addClass(classes.collapseButton); collapseButton.button.id = classes.collapseGroupId(currentGroupId); collapseButton.button.setAttribute('data-level', level); collapseButton.button.setAttribute('data-type', dataType); } } if (createLevelTriggers) { var rowInd = dom.index(elem.parentNode); if (index === -1 || (index < -1 && rowInd === Handsontable.Grouping.getLevels().cols + 1) || (rowInd === 0 && Handsontable.Grouping.getLevels().cols === 0)) { collapseButton = createButton(elem); collapseButton.addClass(classes.levelTrigger); if (index === -1) { collapseButton.button.id = classes.collapseFromLevel("Cols", level); collapseButton.button.appendChild(document.createTextNode(level)); } else if (index < -1 && rowInd === Handsontable.Grouping.getLevels().cols + 1 || (rowInd === 0 && Handsontable.Grouping.getLevels().cols === 0)) { var colInd = dom.index(elem) + 1; collapseButton.button.id = classes.collapseFromLevel("Rows", colInd); collapseButton.button.appendChild(document.createTextNode(colInd)); } } } var expanderButton = addGroupExpander(dataType, index, level, currentGroupId, elem); if (index > 0) { var previousGroupObj = getGroupByIndexAndLevel(index - 1, level); if (expanderButton && previousGroupObj.hidden) { dom.addClass(expanderButton, classes.clickable); } } updateHeaderWidths(); }; }; renderersArr = currentHeaderModifier(renderersArr); if (counters[dataType] > 0) { for (var i = 0; i < levels[dataType] + 1; i++) { if (!Array.isArray(renderersArr)) { renderersArr = typeof renderersArr === 'function' ? renderersArr() : new Array(renderersArr); } renderersArr.unshift(makeGroupIndicatorsForLevel()); } } }, getGroupLevelsByRows: function() { var rowGroups = getRowGroups(), result = []; for (var i = 0, groupsLength = rowGroups.length; i < groupsLength; i++) { if (rowGroups[i].rows) { for (var j = 0, groupRowsLength = rowGroups[i].rows.length; j < groupRowsLength; j++) { if (!result[rowGroups[i].rows[j]]) { result[rowGroups[i].rows[j]] = []; } result[rowGroups[i].rows[j]].push(rowGroups[i].level); } } } return result; }, getGroupLevelsByCols: function() { var colGroups = getColGroups(), result = []; for (var i = 0, groupsLength = colGroups.length; i < groupsLength; i++) { if (colGroups[i].cols) { for (var j = 0, groupColsLength = colGroups[i].cols.length; j < groupColsLength; j++) { if (!result[colGroups[i].cols[j]]) { result[colGroups[i].cols[j]] = []; } result[colGroups[i].cols[j]].push(colGroups[i].level); } } } return result; }, toggleGroupVisibility: function(event, coords, TD) { if (dom.hasClass(event.target, classes.expandButton) || dom.hasClass(event.target, classes.collapseButton) || dom.hasClass(event.target, classes.levelTrigger)) { var element = event.target, elemIdSplit = element.id.split('-'); var groups = [], id, level, type, hidden; var prepareGroupData = function(componentElement) { if (componentElement) { element = componentElement; } elemIdSplit = element.id.split('-'); id = elemIdSplit[1]; level = parseInt(element.getAttribute('data-level'), 10); type = element.getAttribute('data-type'); hidden = parseInt(element.getAttribute('data-hidden')); if (isNaN(hidden)) { hidden = 1; } else { hidden = (hidden ? 0 : 1); } element.setAttribute('data-hidden', hidden.toString()); groups.push(getGroupById(id)); }; if (element.className.indexOf(classes.levelTrigger) > -1) { var groupsInLevel, groupsToExpand = [], groupsToCollapse = [], levelType = element.id.indexOf("Rows") > -1 ? "rows" : "cols"; for (var i = 1, levelsCount = levels[levelType]; i <= levelsCount; i++) { groupsInLevel = levelType == "rows" ? getRowGroupsByLevel(i) : getColGroupsByLevel(i); if (i >= parseInt(elemIdSplit[1], 10)) { for (var j = 0, groupCount = groupsInLevel.length; j < groupCount; j++) { groupsToCollapse.push(groupsInLevel[j]); } } else { for (var j = 0, groupCount = groupsInLevel.length; j < groupCount; j++) { groupsToExpand.push(groupsInLevel[j]); } } } showHideGroups(true, groupsToCollapse); showHideGroups(false, groupsToExpand); } else { prepareGroupData(); showHideGroups(hidden, groups); } type = type || levelType; var lastHidden = isLastHidden(type), typeUppercase = type.charAt(0).toUpperCase() + type.slice(1), spareElements = Handsontable.Grouping['baseSpare' + typeUppercase]; if (lastHidden) { if (spareElements == 0) { instance.alter('insert_' + type.slice(0, -1), instance['count' + typeUppercase]()); Handsontable.Grouping["dummy" + type.slice(0, -1)] = true; } } else { if (spareElements == 0) { if (Handsontable.Grouping["dummy" + type.slice(0, -1)]) { instance.alter('remove_' + type.slice(0, -1), instance['count' + typeUppercase]() - 1); Handsontable.Grouping["dummy" + type.slice(0, -1)] = false; } } } instance.render(); event.stopImmediatePropagation(); } }, modifySelectionFactory: function(position) { var instance = this.instance; var currentlySelected, nextPosition = new WalkontableCellCoords(0, 0), nextVisible = function(direction, currentPosition) { var updateDelta = 0; switch (direction) { case 'down': while (isCollapsed(currentPosition)) { updateDelta++; currentPosition.row += 1; } break; case 'up': while (isCollapsed(currentPosition)) { updateDelta--; currentPosition.row -= 1; } break; case 'right': while (isCollapsed(currentPosition)) { updateDelta++; currentPosition.col += 1; } break; case 'left': while (isCollapsed(currentPosition)) { updateDelta--; currentPosition.col -= 1; } break; } return updateDelta; }, updateDelta = function(delta, nextPosition) { if (delta.row > 0) { if (isCollapsed(nextPosition)) { delta.row += nextVisible('down', nextPosition); } } else if (delta.row < 0) { if (isCollapsed(nextPosition)) { delta.row += nextVisible('up', nextPosition); } } if (delta.col > 0) { if (isCollapsed(nextPosition)) { delta.col += nextVisible('right', nextPosition); } } else if (delta.col < 0) { if (isCollapsed(nextPosition)) { delta.col += nextVisible('left', nextPosition); } } }; switch (position) { case 'start': return function(delta) { currentlySelected = instance.getSelected(); nextPosition.row = currentlySelected[0] + delta.row; nextPosition.col = currentlySelected[1] + delta.col; updateDelta(delta, nextPosition); }; break; case 'end': return function(delta) { currentlySelected = instance.getSelected(); nextPosition.row = currentlySelected[2] + delta.row; nextPosition.col = currentlySelected[3] + delta.col; updateDelta(delta, nextPosition); }; break; } }, modifyRowHeight: function(height, row) { if (instance.view.wt.wtTable.rowFilter && isCollapsed({ row: row, col: null })) { return 0; } }, validateGroups: function() { var areRangesOverlapping = function(a, b) { if ((a[0] < b[0] && a[1] < b[1] && b[0] <= a[1]) || (a[0] > b[0] && b[1] < a[1] && a[0] <= b[1])) { return true; } }; var configGroups = instance.getSettings().groups, cols = [], rows = []; for (var i = 0, groupsLength = configGroups.length; i < groupsLength; i++) { if (configGroups[i].rows) { if (configGroups[i].rows.length === 1) { throw new Error("Grouping error: Group {" + configGroups[i].rows[0] + "} is invalid. Cannot define single-entry groups."); return false; } else if (configGroups[i].rows.length === 0) { throw new Error("Grouping error: Cannot define empty groups."); return false; } rows.push(configGroups[i].rows); for (var j = 0, rowsLength = rows.length; j < rowsLength; j++) { if (areRangesOverlapping(configGroups[i].rows, rows[j])) { throw new Error("Grouping error: ranges {" + configGroups[i].rows[0] + ", " + configGroups[i].rows[1] + "} and {" + rows[j][0] + ", " + rows[j][1] + "} are overlapping."); return false; } } } else if (configGroups[i].cols) { if (configGroups[i].cols.length === 1) { throw new Error("Grouping error: Group {" + configGroups[i].cols[0] + "} is invalid. Cannot define single-entry groups."); return false; } else if (configGroups[i].cols.length === 0) { throw new Error("Grouping error: Cannot define empty groups."); return false; } cols.push(configGroups[i].cols); for (var j = 0, colsLength = cols.length; j < colsLength; j++) { if (areRangesOverlapping(configGroups[i].cols, cols[j])) { throw new Error("Grouping error: ranges {" + configGroups[i].cols[0] + ", " + configGroups[i].cols[1] + "} and {" + cols[j][0] + ", " + cols[j][1] + "} are overlapping."); return false; } } } } return true; }, afterGetRowHeaderRenderers: function(arr) { Handsontable.Grouping.groupIndicatorsFactory(arr, 'vertical'); }, afterGetColumnHeaderRenderers: function(arr) { Handsontable.Grouping.groupIndicatorsFactory(arr, 'horizontal'); }, hookProxy: function(fn, arg) { return function() { if (instance.getSettings().groups) { return arg ? Handsontable.Grouping[fn](arg).apply(this, arguments) : Handsontable.Grouping[fn].apply(this, arguments); } else { return void 0; } }; } }; } Grouping.prototype.beforeInit = function() {}; var init = function() { var instance = this, groupingSetting = !!(instance.getSettings().groups); if (groupingSetting) { var headerUpdates = {}; Handsontable.Grouping = new Grouping(instance); if (!instance.getSettings().rowHeaders) { headerUpdates.rowHeaders = true; } if (!instance.getSettings().colHeaders) { headerUpdates.colHeaders = true; } if (headerUpdates.colHeaders || headerUpdates.rowHeaders) { instance.updateSettings(headerUpdates); } var groupConfigValid = Handsontable.Grouping.validateGroups(); if (!groupConfigValid) { return; } instance.addHook('beforeInit', Handsontable.Grouping.hookProxy('init')); instance.addHook('afterUpdateSettings', Handsontable.Grouping.hookProxy('updateGroups')); instance.addHook('afterGetColumnHeaderRenderers', Handsontable.Grouping.hookProxy('afterGetColumnHeaderRenderers')); instance.addHook('afterGetRowHeaderRenderers', Handsontable.Grouping.hookProxy('afterGetRowHeaderRenderers')); instance.addHook('afterGetRowHeader', Handsontable.Grouping.hookProxy('afterGetRowHeader')); instance.addHook('afterGetColHeader', Handsontable.Grouping.hookProxy('afterGetColHeader')); instance.addHook('beforeOnCellMouseDown', Handsontable.Grouping.hookProxy('toggleGroupVisibility')); instance.addHook('modifyTransformStart', Handsontable.Grouping.hookProxy('modifySelectionFactory', 'start')); instance.addHook('modifyTransformEnd', Handsontable.Grouping.hookProxy('modifySelectionFactory', 'end')); instance.addHook('modifyRowHeight', Handsontable.Grouping.hookProxy('modifyRowHeight')); } }; var updateHeaderWidths = function() { var colgroups = document.querySelectorAll('colgroup'); for (var i = 0, colgroupsLength = colgroups.length; i < colgroupsLength; i++) { var rowHeaders = colgroups[i].querySelectorAll('col.rowHeader'); if (rowHeaders.length === 0) { return; } for (var j = 0, rowHeadersLength = rowHeaders.length + 1; j < rowHeadersLength; j++) { if (rowHeadersLength == 2) { return; } if (j < Handsontable.Grouping.getLevels().rows + 1) { if (j == Handsontable.Grouping.getLevels().rows) { dom.addClass(rowHeaders[j], 'htGroupColClosest'); } else { dom.addClass(rowHeaders[j], 'htGroupCol'); } } } } }; Handsontable.hooks.add('beforeInit', init); Handsontable.hooks.add('afterUpdateSettings', function() { if (this.getSettings().groups && !Handsontable.Grouping) { init.call(this, arguments); } else if (!this.getSettings().groups && Handsontable.Grouping) { Handsontable.Grouping.resetGroups(); Handsontable.Grouping = void 0; } }); Handsontable.plugins.Grouping = Grouping; //# },{"./../../dom.js":34,"./../../plugins.js":52}],64:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { ManualColumnFreeze: {get: function() { return ManualColumnFreeze; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_plugins_46_js__; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; function ManualColumnFreeze(instance) { var fixedColumnsCount = instance.getSettings().fixedColumnsLeft; var init = function() { if (typeof instance.manualColumnPositionsPluginUsages !== 'undefined') { instance.manualColumnPositionsPluginUsages.push('manualColumnFreeze'); } else { instance.manualColumnPositionsPluginUsages = ['manualColumnFreeze']; } bindHooks(); }; function addContextMenuEntry(defaultOptions) { defaultOptions.items.push(Handsontable.ContextMenu.SEPARATOR, { key: 'freeze_column', name: function() { var selectedColumn = instance.getSelected()[1]; if (selectedColumn > fixedColumnsCount - 1) { return 'Freeze this column'; } else { return 'Unfreeze this column'; } }, disabled: function() { var selection = instance.getSelected(); return selection[1] !== selection[3]; }, callback: function() { var selectedColumn = instance.getSelected()[1]; if (selectedColumn > fixedColumnsCount - 1) { freezeColumn(selectedColumn); } else { unfreezeColumn(selectedColumn); } } }); } function addFixedColumn() { instance.updateSettings({fixedColumnsLeft: fixedColumnsCount + 1}); fixedColumnsCount++; } function removeFixedColumn() { instance.updateSettings({fixedColumnsLeft: fixedColumnsCount - 1}); fixedColumnsCount--; } function checkPositionData(col) { if (!instance.manualColumnPositions || instance.manualColumnPositions.length === 0) { if (!instance.manualColumnPositions) { instance.manualColumnPositions = []; } } if (col) { if (!instance.manualColumnPositions[col]) { createPositionData(col + 1); } } else { createPositionData(instance.countCols()); } } function createPositionData(len) { if (instance.manualColumnPositions.length < len) { for (var i = instance.manualColumnPositions.length; i < len; i++) { instance.manualColumnPositions[i] = i; } } } function modifyColumnOrder(col, actualCol, returnCol, action) { if (returnCol == null) { returnCol = col; } if (action === 'freeze') { instance.manualColumnPositions.splice(fixedColumnsCount, 0, instance.manualColumnPositions.splice(actualCol, 1)[0]); } else if (action === 'unfreeze') { instance.manualColumnPositions.splice(returnCol, 0, instance.manualColumnPositions.splice(actualCol, 1)[0]); } } function getBestColumnReturnPosition(col) { var i = fixedColumnsCount, j = getModifiedColumnIndex(i), initialCol = getModifiedColumnIndex(col); while (j < initialCol) { i++; j = getModifiedColumnIndex(i); } return i - 1; } function freezeColumn(col) { if (col <= fixedColumnsCount - 1) { return; } var modifiedColumn = getModifiedColumnIndex(col) || col; checkPositionData(modifiedColumn); modifyColumnOrder(modifiedColumn, col, null, 'freeze'); addFixedColumn(); instance.view.wt.wtOverlays.leftOverlay.refresh(); } function unfreezeColumn(col) { if (col > fixedColumnsCount - 1) { return; } var returnCol = getBestColumnReturnPosition(col); var modifiedColumn = getModifiedColumnIndex(col) || col; checkPositionData(modifiedColumn); modifyColumnOrder(modifiedColumn, col, returnCol, 'unfreeze'); removeFixedColumn(); instance.view.wt.wtOverlays.leftOverlay.refresh(); } function getModifiedColumnIndex(col) { return instance.manualColumnPositions[col]; } function onModifyCol(col) { if (this.manualColumnPositionsPluginUsages.length > 1) { return col; } return getModifiedColumnIndex(col); } function bindHooks() { instance.addHook('modifyCol', onModifyCol); instance.addHook('afterContextMenuDefaultOptions', addContextMenuEntry); } return { init: init, freezeColumn: freezeColumn, unfreezeColumn: unfreezeColumn, helpers: { addFixedColumn: addFixedColumn, removeFixedColumn: removeFixedColumn, checkPositionData: checkPositionData, modifyColumnOrder: modifyColumnOrder, getBestColumnReturnPosition: getBestColumnReturnPosition } }; } var init = function init() { if (!this.getSettings().manualColumnFreeze) { return; } var mcfPlugin; Handsontable.plugins.manualColumnFreeze = ManualColumnFreeze; this.manualColumnFreeze = new ManualColumnFreeze(this); mcfPlugin = this.manualColumnFreeze; mcfPlugin.init.call(this); }; Handsontable.hooks.add('beforeInit', init); //# },{"./../../plugins.js":52}],65:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { ManualColumnMove: {get: function() { return ManualColumnMove; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_helpers_46_js__, $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47_plugins_46_js__; var helper = ($___46__46__47__46__46__47_helpers_46_js__ = require("./../../helpers.js"), $___46__46__47__46__46__47_helpers_46_js__ && $___46__46__47__46__46__47_helpers_46_js__.__esModule && $___46__46__47__46__46__47_helpers_46_js__ || {default: $___46__46__47__46__46__47_helpers_46_js__}); var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47_eventManager_46_js__ = require("./../../eventManager.js"), $___46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47_eventManager_46_js__}).eventManager; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; function ManualColumnMove() { var startCol, endCol, startX, startOffset, currentCol, instance, currentTH, handle = document.createElement('DIV'), guide = document.createElement('DIV'), eventManager = eventManagerObject(this); handle.className = 'manualColumnMover'; guide.className = 'manualColumnMoverGuide'; var saveManualColumnPositions = function() { var instance = this; Handsontable.hooks.run(instance, 'persistentStateSave', 'manualColumnPositions', instance.manualColumnPositions); }; var loadManualColumnPositions = function() { var instance = this; var storedState = {}; Handsontable.hooks.run(instance, 'persistentStateLoad', 'manualColumnPositions', storedState); return storedState.value; }; function setupHandlePosition(TH) { instance = this; currentTH = TH; var col = this.view.wt.wtTable.getCoords(TH).col; if (col >= 0) { currentCol = col; var box = currentTH.getBoundingClientRect(); startOffset = box.left; handle.style.top = box.top + 'px'; handle.style.left = startOffset + 'px'; instance.rootElement.appendChild(handle); } } function refreshHandlePosition(TH, delta) { var box = TH.getBoundingClientRect(); var handleWidth = 6; if (delta > 0) { handle.style.left = (box.left + box.width - handleWidth) + 'px'; } else { handle.style.left = box.left + 'px'; } } function setupGuidePosition() { var instance = this; dom.addClass(handle, 'active'); dom.addClass(guide, 'active'); var box = currentTH.getBoundingClientRect(); guide.style.width = box.width + 'px'; guide.style.height = instance.view.maximumVisibleElementHeight(0) + 'px'; guide.style.top = handle.style.top; guide.style.left = startOffset + 'px'; instance.rootElement.appendChild(guide); } function refreshGuidePosition(diff) { guide.style.left = startOffset + diff + 'px'; } function hideHandleAndGuide() { dom.removeClass(handle, 'active'); dom.removeClass(guide, 'active'); } var checkColumnHeader = function(element) { if (element.tagName != 'BODY') { if (element.parentNode.tagName == 'THEAD') { return true; } else { element = element.parentNode; return checkColumnHeader(element); } } return false; }; var getTHFromTargetElement = function(element) { if (element.tagName != 'TABLE') { if (element.tagName == 'TH') { return element; } else { return getTHFromTargetElement(element.parentNode); } } return null; }; var bindEvents = function() { var instance = this; var pressed; eventManager.addEventListener(instance.rootElement, 'mouseover', function(e) { if (checkColumnHeader(e.target)) { var th = getTHFromTargetElement(e.target); if (th) { if (pressed) { var col = instance.view.wt.wtTable.getCoords(th).col; if (col >= 0) { endCol = col; refreshHandlePosition(e.target, endCol - startCol); } } else { setupHandlePosition.call(instance, th); } } } }); eventManager.addEventListener(instance.rootElement, 'mousedown', function(e) { if (dom.hasClass(e.target, 'manualColumnMover')) { startX = helper.pageX(e); setupGuidePosition.call(instance); pressed = instance; startCol = currentCol; endCol = currentCol; } }); eventManager.addEventListener(window, 'mousemove', function(e) { if (pressed) { refreshGuidePosition(helper.pageX(e) - startX); } }); eventManager.addEventListener(window, 'mouseup', function(e) { if (pressed) { hideHandleAndGuide(); pressed = false; createPositionData(instance.manualColumnPositions, instance.countCols()); instance.manualColumnPositions.splice(endCol, 0, instance.manualColumnPositions.splice(startCol, 1)[0]); instance.forceFullRender = true; instance.view.render(); saveManualColumnPositions.call(instance); Handsontable.hooks.run(instance, 'afterColumnMove', startCol, endCol); setupHandlePosition.call(instance, currentTH); } }); instance.addHook('afterDestroy', unbindEvents); }; var unbindEvents = function() { eventManager.clear(); }; var createPositionData = function(positionArr, len) { if (positionArr.length < len) { for (var i = positionArr.length; i < len; i++) { positionArr[i] = i; } } }; this.beforeInit = function() { this.manualColumnPositions = []; }; this.init = function(source) { var instance = this; var manualColMoveEnabled = !!(this.getSettings().manualColumnMove); if (manualColMoveEnabled) { var initialManualColumnPositions = this.getSettings().manualColumnMove; var loadedManualColumnPositions = loadManualColumnPositions.call(instance); if (typeof loadedManualColumnPositions != 'undefined') { this.manualColumnPositions = loadedManualColumnPositions; } else if (Array.isArray(initialManualColumnPositions)) { this.manualColumnPositions = initialManualColumnPositions; } else { this.manualColumnPositions = []; } if (source == 'afterInit') { if (typeof instance.manualColumnPositionsPluginUsages != 'undefined') { instance.manualColumnPositionsPluginUsages.push('manualColumnMove'); } else { instance.manualColumnPositionsPluginUsages = ['manualColumnMove']; } bindEvents.call(this); if (this.manualColumnPositions.length > 0) { this.forceFullRender = true; this.render(); } } } else { var pluginUsagesIndex = instance.manualColumnPositionsPluginUsages ? instance.manualColumnPositionsPluginUsages.indexOf('manualColumnMove') : -1; if (pluginUsagesIndex > -1) { unbindEvents.call(this); this.manualColumnPositions = []; instance.manualColumnPositionsPluginUsages[pluginUsagesIndex] = void 0; } } }; this.modifyCol = function(col) { if (this.getSettings().manualColumnMove) { if (typeof this.manualColumnPositions[col] === 'undefined') { createPositionData(this.manualColumnPositions, col + 1); } return this.manualColumnPositions[col]; } return col; }; this.afterRemoveCol = function(index, amount) { if (!this.getSettings().manualColumnMove) { return; } var rmindx, colpos = this.manualColumnPositions; rmindx = colpos.splice(index, amount); colpos = colpos.map(function(colpos) { var i, newpos = colpos; for (i = 0; i < rmindx.length; i++) { if (colpos > rmindx[i]) { newpos--; } } return newpos; }); this.manualColumnPositions = colpos; }; this.afterCreateCol = function(index, amount) { if (!this.getSettings().manualColumnMove) { return; } var colpos = this.manualColumnPositions; if (!colpos.length) { return; } var addindx = []; for (var i = 0; i < amount; i++) { addindx.push(index + i); } if (index >= colpos.length) { colpos.concat(addindx); } else { colpos = colpos.map(function(colpos) { return (colpos >= index) ? (colpos + amount) : colpos; }); colpos.splice.apply(colpos, [index, 0].concat(addindx)); } this.manualColumnPositions = colpos; }; } var htManualColumnMove = new ManualColumnMove(); Handsontable.hooks.add('beforeInit', htManualColumnMove.beforeInit); Handsontable.hooks.add('afterInit', function() { htManualColumnMove.init.call(this, 'afterInit'); }); Handsontable.hooks.add('afterUpdateSettings', function() { htManualColumnMove.init.call(this, 'afterUpdateSettings'); }); Handsontable.hooks.add('modifyCol', htManualColumnMove.modifyCol); Handsontable.hooks.add('afterRemoveCol', htManualColumnMove.afterRemoveCol); Handsontable.hooks.add('afterCreateCol', htManualColumnMove.afterCreateCol); Handsontable.hooks.register('afterColumnMove'); //# },{"./../../dom.js":34,"./../../eventManager.js":48,"./../../helpers.js":49,"./../../plugins.js":52}],66:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { ManualColumnResize: {get: function() { return ManualColumnResize; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_helpers_46_js__, $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47_plugins_46_js__; var helper = ($___46__46__47__46__46__47_helpers_46_js__ = require("./../../helpers.js"), $___46__46__47__46__46__47_helpers_46_js__ && $___46__46__47__46__46__47_helpers_46_js__.__esModule && $___46__46__47__46__46__47_helpers_46_js__ || {default: $___46__46__47__46__46__47_helpers_46_js__}); var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47_eventManager_46_js__ = require("./../../eventManager.js"), $___46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47_eventManager_46_js__}).eventManager; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; function ManualColumnResize() { var currentTH, currentCol, currentWidth, instance, newSize, startX, startWidth, startOffset, handle = document.createElement('DIV'), guide = document.createElement('DIV'), eventManager = eventManagerObject(this); handle.className = 'manualColumnResizer'; guide.className = 'manualColumnResizerGuide'; var saveManualColumnWidths = function() { var instance = this; Handsontable.hooks.run(instance, 'persistentStateSave', 'manualColumnWidths', instance.manualColumnWidths); }; var loadManualColumnWidths = function() { var instance = this; var storedState = {}; Handsontable.hooks.run(instance, 'persistentStateLoad', 'manualColumnWidths', storedState); return storedState.value; }; function setupHandlePosition(TH) { instance = this; currentTH = TH; var col = this.view.wt.wtTable.getCoords(TH).col; if (col >= 0) { currentCol = col; var box = currentTH.getBoundingClientRect(); startOffset = box.left - 6; startWidth = parseInt(box.width, 10); handle.style.top = box.top + 'px'; handle.style.left = startOffset + startWidth + 'px'; instance.rootElement.appendChild(handle); } } function refreshHandlePosition() { handle.style.left = startOffset + currentWidth + 'px'; } function setupGuidePosition() { var instance = this; dom.addClass(handle, 'active'); dom.addClass(guide, 'active'); guide.style.top = handle.style.top; guide.style.left = handle.style.left; guide.style.height = instance.view.maximumVisibleElementHeight(0) + 'px'; instance.rootElement.appendChild(guide); } function refreshGuidePosition() { guide.style.left = handle.style.left; } function hideHandleAndGuide() { dom.removeClass(handle, 'active'); dom.removeClass(guide, 'active'); } var checkColumnHeader = function(element) { if (element.tagName != 'BODY') { if (element.parentNode.tagName == 'THEAD') { return true; } else { element = element.parentNode; return checkColumnHeader(element); } } return false; }; var getTHFromTargetElement = function(element) { if (element.tagName != 'TABLE') { if (element.tagName == 'TH') { return element; } else { return getTHFromTargetElement(element.parentNode); } } return null; }; var bindEvents = function() { var instance = this; var pressed; var dblclick = 0; var autoresizeTimeout = null; eventManager.addEventListener(instance.rootElement, 'mouseover', function(e) { if (checkColumnHeader(e.target)) { var th = getTHFromTargetElement(e.target); if (th) { if (!pressed) { setupHandlePosition.call(instance, th); } } } }); eventManager.addEventListener(instance.rootElement, 'mousedown', function(e) { if (dom.hasClass(e.target, 'manualColumnResizer')) { setupGuidePosition.call(instance); pressed = instance; if (autoresizeTimeout == null) { autoresizeTimeout = setTimeout(function() { if (dblclick >= 2) { newSize = instance.determineColumnWidth.call(instance, currentCol); setManualSize(currentCol, newSize); instance.forceFullRender = true; instance.view.render(); Handsontable.hooks.run(instance, 'afterColumnResize', currentCol, newSize); } dblclick = 0; autoresizeTimeout = null; }, 500); instance._registerTimeout(autoresizeTimeout); } dblclick++; startX = helper.pageX(e); newSize = startWidth; } }); eventManager.addEventListener(window, 'mousemove', function(e) { if (pressed) { currentWidth = startWidth + (helper.pageX(e) - startX); newSize = setManualSize(currentCol, currentWidth); refreshHandlePosition(); refreshGuidePosition(); } }); eventManager.addEventListener(window, 'mouseup', function() { if (pressed) { hideHandleAndGuide(); pressed = false; if (newSize != startWidth) { instance.forceFullRender = true; instance.view.render(); saveManualColumnWidths.call(instance); Handsontable.hooks.run(instance, 'afterColumnResize', currentCol, newSize); } setupHandlePosition.call(instance, currentTH); } }); instance.addHook('afterDestroy', unbindEvents); }; var unbindEvents = function() { eventManager.clear(); }; this.beforeInit = function() { this.manualColumnWidths = []; }; this.init = function(source) { var instance = this; var manualColumnWidthEnabled = !!(this.getSettings().manualColumnResize); if (manualColumnWidthEnabled) { var initialColumnWidths = this.getSettings().manualColumnResize; var loadedManualColumnWidths = loadManualColumnWidths.call(instance); if (typeof instance.manualColumnWidthsPluginUsages != 'undefined') { instance.manualColumnWidthsPluginUsages.push('manualColumnResize'); } else { instance.manualColumnWidthsPluginUsages = ['manualColumnResize']; } if (typeof loadedManualColumnWidths != 'undefined') { this.manualColumnWidths = loadedManualColumnWidths; } else if (Array.isArray(initialColumnWidths)) { this.manualColumnWidths = initialColumnWidths; } else { this.manualColumnWidths = []; } if (source == 'afterInit') { bindEvents.call(this); if (this.manualColumnWidths.length > 0) { this.forceFullRender = true; this.render(); } } } else { var pluginUsagesIndex = instance.manualColumnWidthsPluginUsages ? instance.manualColumnWidthsPluginUsages.indexOf('manualColumnResize') : -1; if (pluginUsagesIndex > -1) { unbindEvents.call(this); this.manualColumnWidths = []; } } }; var setManualSize = function(col, width) { width = Math.max(width, 20); col = Handsontable.hooks.run(instance, 'modifyCol', col); instance.manualColumnWidths[col] = width; return width; }; this.modifyColWidth = function(width, col) { col = this.runHooks('modifyCol', col); if (this.getSettings().manualColumnResize && this.manualColumnWidths[col]) { return this.manualColumnWidths[col]; } return width; }; } var htManualColumnResize = new ManualColumnResize(); Handsontable.hooks.add('beforeInit', htManualColumnResize.beforeInit); Handsontable.hooks.add('afterInit', function() { htManualColumnResize.init.call(this, 'afterInit'); }); Handsontable.hooks.add('afterUpdateSettings', function() { htManualColumnResize.init.call(this, 'afterUpdateSettings'); }); Handsontable.hooks.add('modifyColWidth', htManualColumnResize.modifyColWidth); Handsontable.hooks.register('afterColumnResize'); //# },{"./../../dom.js":34,"./../../eventManager.js":48,"./../../helpers.js":49,"./../../plugins.js":52}],67:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { ManualRowMove: {get: function() { return ManualRowMove; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_helpers_46_js__, $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47_plugins_46_js__; var helper = ($___46__46__47__46__46__47_helpers_46_js__ = require("./../../helpers.js"), $___46__46__47__46__46__47_helpers_46_js__ && $___46__46__47__46__46__47_helpers_46_js__.__esModule && $___46__46__47__46__46__47_helpers_46_js__ || {default: $___46__46__47__46__46__47_helpers_46_js__}); var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47_eventManager_46_js__ = require("./../../eventManager.js"), $___46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47_eventManager_46_js__}).eventManager; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; function ManualRowMove() { var startRow, endRow, startY, startOffset, currentRow, currentTH, handle = document.createElement('DIV'), guide = document.createElement('DIV'), eventManager = eventManagerObject(this); handle.className = 'manualRowMover'; guide.className = 'manualRowMoverGuide'; var saveManualRowPositions = function() { var instance = this; Handsontable.hooks.run(instance, 'persistentStateSave', 'manualRowPositions', instance.manualRowPositions); }; var loadManualRowPositions = function() { var instance = this, storedState = {}; Handsontable.hooks.run(instance, 'persistentStateLoad', 'manualRowPositions', storedState); return storedState.value; }; function setupHandlePosition(TH) { var instance = this; currentTH = TH; var row = this.view.wt.wtTable.getCoords(TH).row; if (row >= 0) { currentRow = row; var box = currentTH.getBoundingClientRect(); startOffset = box.top; handle.style.top = startOffset + 'px'; handle.style.left = box.left + 'px'; instance.rootElement.appendChild(handle); } } function refreshHandlePosition(TH, delta) { var box = TH.getBoundingClientRect(); var handleHeight = 6; if (delta > 0) { handle.style.top = (box.top + box.height - handleHeight) + 'px'; } else { handle.style.top = box.top + 'px'; } } function setupGuidePosition() { var instance = this; dom.addClass(handle, 'active'); dom.addClass(guide, 'active'); var box = currentTH.getBoundingClientRect(); guide.style.width = instance.view.maximumVisibleElementWidth(0) + 'px'; guide.style.height = box.height + 'px'; guide.style.top = startOffset + 'px'; guide.style.left = handle.style.left; instance.rootElement.appendChild(guide); } function refreshGuidePosition(diff) { guide.style.top = startOffset + diff + 'px'; } function hideHandleAndGuide() { dom.removeClass(handle, 'active'); dom.removeClass(guide, 'active'); } var checkRowHeader = function(element) { if (element.tagName != 'BODY') { if (element.parentNode.tagName == 'TBODY') { return true; } else { element = element.parentNode; return checkRowHeader(element); } } return false; }; var getTHFromTargetElement = function(element) { if (element.tagName != 'TABLE') { if (element.tagName == 'TH') { return element; } else { return getTHFromTargetElement(element.parentNode); } } return null; }; var bindEvents = function() { var instance = this; var pressed; eventManager.addEventListener(instance.rootElement, 'mouseover', function(e) { if (checkRowHeader(e.target)) { var th = getTHFromTargetElement(e.target); if (th) { if (pressed) { endRow = instance.view.wt.wtTable.getCoords(th).row; refreshHandlePosition(th, endRow - startRow); } else { setupHandlePosition.call(instance, th); } } } }); eventManager.addEventListener(instance.rootElement, 'mousedown', function(e) { if (dom.hasClass(e.target, 'manualRowMover')) { startY = helper.pageY(e); setupGuidePosition.call(instance); pressed = instance; startRow = currentRow; endRow = currentRow; } }); eventManager.addEventListener(window, 'mousemove', function(e) { if (pressed) { refreshGuidePosition(helper.pageY(e) - startY); } }); eventManager.addEventListener(window, 'mouseup', function(e) { if (pressed) { hideHandleAndGuide(); pressed = false; createPositionData(instance.manualRowPositions, instance.countRows()); instance.manualRowPositions.splice(endRow, 0, instance.manualRowPositions.splice(startRow, 1)[0]); instance.forceFullRender = true; instance.view.render(); saveManualRowPositions.call(instance); Handsontable.hooks.run(instance, 'afterRowMove', startRow, endRow); setupHandlePosition.call(instance, currentTH); } }); instance.addHook('afterDestroy', unbindEvents); }; var unbindEvents = function() { eventManager.clear(); }; var createPositionData = function(positionArr, len) { if (positionArr.length < len) { for (var i = positionArr.length; i < len; i++) { positionArr[i] = i; } } }; this.beforeInit = function() { this.manualRowPositions = []; }; this.init = function(source) { var instance = this; var manualRowMoveEnabled = !!(instance.getSettings().manualRowMove); if (manualRowMoveEnabled) { var initialManualRowPositions = instance.getSettings().manualRowMove; var loadedManualRowPostions = loadManualRowPositions.call(instance); if (typeof instance.manualRowPositionsPluginUsages != 'undefined') { instance.manualRowPositionsPluginUsages.push('manualColumnMove'); } else { instance.manualRowPositionsPluginUsages = ['manualColumnMove']; } if (typeof loadedManualRowPostions != 'undefined') { this.manualRowPositions = loadedManualRowPostions; } else if (Array.isArray(initialManualRowPositions)) { this.manualRowPositions = initialManualRowPositions; } else { this.manualRowPositions = []; } if (source === 'afterInit') { bindEvents.call(this); if (this.manualRowPositions.length > 0) { instance.forceFullRender = true; instance.render(); } } } else { var pluginUsagesIndex = instance.manualRowPositionsPluginUsages ? instance.manualRowPositionsPluginUsages.indexOf('manualColumnMove') : -1; if (pluginUsagesIndex > -1) { unbindEvents.call(this); instance.manualRowPositions = []; instance.manualRowPositionsPluginUsages[pluginUsagesIndex] = void 0; } } }; this.modifyRow = function(row) { var instance = this; if (instance.getSettings().manualRowMove) { if (typeof instance.manualRowPositions[row] === 'undefined') { createPositionData(this.manualRowPositions, row + 1); } return instance.manualRowPositions[row]; } return row; }; } var htManualRowMove = new ManualRowMove(); Handsontable.hooks.add('beforeInit', htManualRowMove.beforeInit); Handsontable.hooks.add('afterInit', function() { htManualRowMove.init.call(this, 'afterInit'); }); Handsontable.hooks.add('afterUpdateSettings', function() { htManualRowMove.init.call(this, 'afterUpdateSettings'); }); Handsontable.hooks.add('modifyRow', htManualRowMove.modifyRow); Handsontable.hooks.register('afterRowMove'); //# },{"./../../dom.js":34,"./../../eventManager.js":48,"./../../helpers.js":49,"./../../plugins.js":52}],68:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { ManualRowResize: {get: function() { return ManualRowResize; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_helpers_46_js__, $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47_plugins_46_js__; var helper = ($___46__46__47__46__46__47_helpers_46_js__ = require("./../../helpers.js"), $___46__46__47__46__46__47_helpers_46_js__ && $___46__46__47__46__46__47_helpers_46_js__.__esModule && $___46__46__47__46__46__47_helpers_46_js__ || {default: $___46__46__47__46__46__47_helpers_46_js__}); var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47_eventManager_46_js__ = require("./../../eventManager.js"), $___46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47_eventManager_46_js__}).eventManager; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; function ManualRowResize() { var currentTH, currentRow, currentHeight, instance, newSize, startY, startHeight, startOffset, handle = document.createElement('DIV'), guide = document.createElement('DIV'), eventManager = eventManagerObject(this); handle.className = 'manualRowResizer'; guide.className = 'manualRowResizerGuide'; var saveManualRowHeights = function() { var instance = this; Handsontable.hooks.run(instance, 'persistentStateSave', 'manualRowHeights', instance.manualRowHeights); }; var loadManualRowHeights = function() { var instance = this, storedState = {}; Handsontable.hooks.run(instance, 'persistentStateLoad', 'manualRowHeights', storedState); return storedState.value; }; function setupHandlePosition(TH) { instance = this; currentTH = TH; var row = this.view.wt.wtTable.getCoords(TH).row; if (row >= 0) { currentRow = row; var box = currentTH.getBoundingClientRect(); startOffset = box.top - 6; startHeight = parseInt(box.height, 10); handle.style.left = box.left + 'px'; handle.style.top = startOffset + startHeight + 'px'; instance.rootElement.appendChild(handle); } } function refreshHandlePosition() { handle.style.top = startOffset + currentHeight + 'px'; } function setupGuidePosition() { var instance = this; dom.addClass(handle, 'active'); dom.addClass(guide, 'active'); guide.style.top = handle.style.top; guide.style.left = handle.style.left; guide.style.width = instance.view.maximumVisibleElementWidth(0) + 'px'; instance.rootElement.appendChild(guide); } function refreshGuidePosition() { guide.style.top = handle.style.top; } function hideHandleAndGuide() { dom.removeClass(handle, 'active'); dom.removeClass(guide, 'active'); } var checkRowHeader = function(element) { if (element.tagName != 'BODY') { if (element.parentNode.tagName == 'TBODY') { return true; } else { element = element.parentNode; return checkRowHeader(element); } } return false; }; var getTHFromTargetElement = function(element) { if (element.tagName != 'TABLE') { if (element.tagName == 'TH') { return element; } else { return getTHFromTargetElement(element.parentNode); } } return null; }; var bindEvents = function() { var instance = this; var pressed; var dblclick = 0; var autoresizeTimeout = null; eventManager.addEventListener(instance.rootElement, 'mouseover', function(e) { if (checkRowHeader(e.target)) { var th = getTHFromTargetElement(e.target); if (th) { if (!pressed) { setupHandlePosition.call(instance, th); } } } }); eventManager.addEventListener(instance.rootElement, 'mousedown', function(e) { if (dom.hasClass(e.target, 'manualRowResizer')) { setupGuidePosition.call(instance); pressed = instance; if (autoresizeTimeout == null) { autoresizeTimeout = setTimeout(function() { if (dblclick >= 2) { setManualSize(currentRow, null); instance.forceFullRender = true; instance.view.render(); Handsontable.hooks.run(instance, 'afterRowResize', currentRow, newSize); } dblclick = 0; autoresizeTimeout = null; }, 500); instance._registerTimeout(autoresizeTimeout); } dblclick++; startY = helper.pageY(e); newSize = startHeight; } }); eventManager.addEventListener(window, 'mousemove', function(e) { if (pressed) { currentHeight = startHeight + (helper.pageY(e) - startY); newSize = setManualSize(currentRow, currentHeight); refreshHandlePosition(); refreshGuidePosition(); } }); eventManager.addEventListener(window, 'mouseup', function(e) { if (pressed) { hideHandleAndGuide(); pressed = false; if (newSize != startHeight) { instance.forceFullRender = true; instance.view.render(); saveManualRowHeights.call(instance); Handsontable.hooks.run(instance, 'afterRowResize', currentRow, newSize); } setupHandlePosition.call(instance, currentTH); } }); instance.addHook('afterDestroy', unbindEvents); }; var unbindEvents = function() { eventManager.clear(); }; this.beforeInit = function() { this.manualRowHeights = []; }; this.init = function(source) { var instance = this; var manualColumnHeightEnabled = !!(this.getSettings().manualRowResize); if (manualColumnHeightEnabled) { var initialRowHeights = this.getSettings().manualRowResize; var loadedManualRowHeights = loadManualRowHeights.call(instance); if (typeof instance.manualRowHeightsPluginUsages != 'undefined') { instance.manualRowHeightsPluginUsages.push('manualRowResize'); } else { instance.manualRowHeightsPluginUsages = ['manualRowResize']; } if (typeof loadedManualRowHeights != 'undefined') { this.manualRowHeights = loadedManualRowHeights; } else if (Array.isArray(initialRowHeights)) { this.manualRowHeights = initialRowHeights; } else { this.manualRowHeights = []; } if (source === 'afterInit') { bindEvents.call(this); if (this.manualRowHeights.length > 0) { this.forceFullRender = true; this.render(); } } else { this.forceFullRender = true; this.render(); } } else { var pluginUsagesIndex = instance.manualRowHeightsPluginUsages ? instance.manualRowHeightsPluginUsages.indexOf('manualRowResize') : -1; if (pluginUsagesIndex > -1) { unbindEvents.call(this); this.manualRowHeights = []; instance.manualRowHeightsPluginUsages[pluginUsagesIndex] = void 0; } } }; var setManualSize = function(row, height) { row = Handsontable.hooks.run(instance, 'modifyRow', row); instance.manualRowHeights[row] = height; return height; }; this.modifyRowHeight = function(height, row) { if (this.getSettings().manualRowResize) { row = this.runHooks('modifyRow', row); if (this.manualRowHeights[row] !== void 0) { return this.manualRowHeights[row]; } } return height; }; } var htManualRowResize = new ManualRowResize(); Handsontable.hooks.add('beforeInit', htManualRowResize.beforeInit); Handsontable.hooks.add('afterInit', function() { htManualRowResize.init.call(this, 'afterInit'); }); Handsontable.hooks.add('afterUpdateSettings', function() { htManualRowResize.init.call(this, 'afterUpdateSettings'); }); Handsontable.hooks.add('modifyRowHeight', htManualRowResize.modifyRowHeight); Handsontable.hooks.register('afterRowResize'); //# },{"./../../dom.js":34,"./../../eventManager.js":48,"./../../helpers.js":49,"./../../plugins.js":52}],69:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { MergeCells: {get: function() { return MergeCells; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_plugins_46_js__, $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__, $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__, $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_table_46_js__; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; var WalkontableCellCoords = ($___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ = require("./../../3rdparty/walkontable/src/cellCoords.js"), $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__}).WalkontableCellCoords; var WalkontableCellRange = ($___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__ = require("./../../3rdparty/walkontable/src/cellRange.js"), $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__ && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_cellRange_46_js__}).WalkontableCellRange; var WalkontableTable = ($___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_table_46_js__ = require("./../../3rdparty/walkontable/src/table.js"), $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_table_46_js__ && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_table_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_table_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_walkontable_47_src_47_table_46_js__}).WalkontableTable; ; function CellInfoCollection() { var collection = []; collection.getInfo = function(row, col) { for (var i = 0, ilen = this.length; i < ilen; i++) { if (this[i].row <= row && this[i].row + this[i].rowspan - 1 >= row && this[i].col <= col && this[i].col + this[i].colspan - 1 >= col) { return this[i]; } } }; collection.setInfo = function(info) { for (var i = 0, ilen = this.length; i < ilen; i++) { if (this[i].row === info.row && this[i].col === info.col) { this[i] = info; return; } } this.push(info); }; collection.removeInfo = function(row, col) { for (var i = 0, ilen = this.length; i < ilen; i++) { if (this[i].row === row && this[i].col === col) { this.splice(i, 1); break; } } }; return collection; } function MergeCells(mergeCellsSetting) { this.mergedCellInfoCollection = new CellInfoCollection(); if (Array.isArray(mergeCellsSetting)) { for (var i = 0, ilen = mergeCellsSetting.length; i < ilen; i++) { this.mergedCellInfoCollection.setInfo(mergeCellsSetting[i]); } } } MergeCells.prototype.canMergeRange = function(cellRange) { return !cellRange.isSingle(); }; MergeCells.prototype.mergeRange = function(cellRange) { if (!this.canMergeRange(cellRange)) { return; } var topLeft = cellRange.getTopLeftCorner(); var bottomRight = cellRange.getBottomRightCorner(); var mergeParent = {}; mergeParent.row = topLeft.row; mergeParent.col = topLeft.col; mergeParent.rowspan = bottomRight.row - topLeft.row + 1; mergeParent.colspan = bottomRight.col - topLeft.col + 1; this.mergedCellInfoCollection.setInfo(mergeParent); }; MergeCells.prototype.mergeOrUnmergeSelection = function(cellRange) { var info = this.mergedCellInfoCollection.getInfo(cellRange.from.row, cellRange.from.col); if (info) { this.unmergeSelection(cellRange.from); } else { this.mergeSelection(cellRange); } }; MergeCells.prototype.mergeSelection = function(cellRange) { this.mergeRange(cellRange); }; MergeCells.prototype.unmergeSelection = function(cellRange) { var info = this.mergedCellInfoCollection.getInfo(cellRange.row, cellRange.col); this.mergedCellInfoCollection.removeInfo(info.row, info.col); }; MergeCells.prototype.applySpanProperties = function(TD, row, col) { var info = this.mergedCellInfoCollection.getInfo(row, col); if (info) { if (info.row === row && info.col === col) { TD.setAttribute('rowspan', info.rowspan); TD.setAttribute('colspan', info.colspan); } else { TD.removeAttribute('rowspan'); TD.removeAttribute('colspan'); TD.style.display = "none"; } } else { TD.removeAttribute('rowspan'); TD.removeAttribute('colspan'); } }; MergeCells.prototype.modifyTransform = function(hook, currentSelectedRange, delta) { var sameRowspan = function(merged, coords) { if (coords.row >= merged.row && coords.row <= (merged.row + merged.rowspan - 1)) { return true; } return false; }, sameColspan = function(merged, coords) { if (coords.col >= merged.col && coords.col <= (merged.col + merged.colspan - 1)) { return true; } return false; }, getNextPosition = function(newDelta) { return new WalkontableCellCoords(currentSelectedRange.to.row + newDelta.row, currentSelectedRange.to.col + newDelta.col); }; var newDelta = { row: delta.row, col: delta.col }; if (hook == 'modifyTransformStart') { if (!this.lastDesiredCoords) { this.lastDesiredCoords = new WalkontableCellCoords(null, null); } var currentPosition = new WalkontableCellCoords(currentSelectedRange.highlight.row, currentSelectedRange.highlight.col), mergedParent = this.mergedCellInfoCollection.getInfo(currentPosition.row, currentPosition.col), currentRangeContainsMerge; for (var i = 0, mergesLength = this.mergedCellInfoCollection.length; i < mergesLength; i++) { var range = this.mergedCellInfoCollection[i]; range = new WalkontableCellCoords(range.row + range.rowspan - 1, range.col + range.colspan - 1); if (currentSelectedRange.includes(range)) { currentRangeContainsMerge = true; break; } } if (mergedParent) { var mergeTopLeft = new WalkontableCellCoords(mergedParent.row, mergedParent.col), mergeBottomRight = new WalkontableCellCoords(mergedParent.row + mergedParent.rowspan - 1, mergedParent.col + mergedParent.colspan - 1), mergeRange = new WalkontableCellRange(mergeTopLeft, mergeTopLeft, mergeBottomRight); if (!mergeRange.includes(this.lastDesiredCoords)) { this.lastDesiredCoords = new WalkontableCellCoords(null, null); } newDelta.row = this.lastDesiredCoords.row ? this.lastDesiredCoords.row - currentPosition.row : newDelta.row; newDelta.col = this.lastDesiredCoords.col ? this.lastDesiredCoords.col - currentPosition.col : newDelta.col; if (delta.row > 0) { newDelta.row = mergedParent.row + mergedParent.rowspan - 1 - currentPosition.row + delta.row; } else if (delta.row < 0) { newDelta.row = currentPosition.row - mergedParent.row + delta.row; } if (delta.col > 0) { newDelta.col = mergedParent.col + mergedParent.colspan - 1 - currentPosition.col + delta.col; } else if (delta.col < 0) { newDelta.col = currentPosition.col - mergedParent.col + delta.col; } } var nextPosition = new WalkontableCellCoords(currentSelectedRange.highlight.row + newDelta.row, currentSelectedRange.highlight.col + newDelta.col), nextParentIsMerged = this.mergedCellInfoCollection.getInfo(nextPosition.row, nextPosition.col); if (nextParentIsMerged) { this.lastDesiredCoords = nextPosition; newDelta = { row: nextParentIsMerged.row - currentPosition.row, col: nextParentIsMerged.col - currentPosition.col }; } } else if (hook == 'modifyTransformEnd') { for (var i = 0, mergesLength = this.mergedCellInfoCollection.length; i < mergesLength; i++) { var currentMerge = this.mergedCellInfoCollection[i], mergeTopLeft = new WalkontableCellCoords(currentMerge.row, currentMerge.col), mergeBottomRight = new WalkontableCellCoords(currentMerge.row + currentMerge.rowspan - 1, currentMerge.col + currentMerge.colspan - 1), mergedRange = new WalkontableCellRange(mergeTopLeft, mergeTopLeft, mergeBottomRight), sharedBorders = currentSelectedRange.getBordersSharedWith(mergedRange); if (mergedRange.isEqual(currentSelectedRange)) { currentSelectedRange.setDirection("NW-SE"); } else if (sharedBorders.length > 0) { var mergeHighlighted = (currentSelectedRange.highlight.isEqual(mergedRange.from)); if (sharedBorders.indexOf('top') > -1) { if (currentSelectedRange.to.isSouthEastOf(mergedRange.from) && mergeHighlighted) { currentSelectedRange.setDirection("NW-SE"); } else if (currentSelectedRange.to.isSouthWestOf(mergedRange.from) && mergeHighlighted) { currentSelectedRange.setDirection("NE-SW"); } } else if (sharedBorders.indexOf('bottom') > -1) { if (currentSelectedRange.to.isNorthEastOf(mergedRange.from) && mergeHighlighted) { currentSelectedRange.setDirection("SW-NE"); } else if (currentSelectedRange.to.isNorthWestOf(mergedRange.from) && mergeHighlighted) { currentSelectedRange.setDirection("SE-NW"); } } } var nextPosition = getNextPosition(newDelta), withinRowspan = sameRowspan(currentMerge, nextPosition), withinColspan = sameColspan(currentMerge, nextPosition); if (currentSelectedRange.includesRange(mergedRange) && (mergedRange.includes(nextPosition) || withinRowspan || withinColspan)) { if (withinRowspan) { if (newDelta.row < 0) { newDelta.row -= currentMerge.rowspan - 1; } else if (newDelta.row > 0) { newDelta.row += currentMerge.rowspan - 1; } } if (withinColspan) { if (newDelta.col < 0) { newDelta.col -= currentMerge.colspan - 1; } else if (newDelta.col > 0) { newDelta.col += currentMerge.colspan - 1; } } } } } if (newDelta.row !== 0) { delta.row = newDelta.row; } if (newDelta.col !== 0) { delta.col = newDelta.col; } }; var beforeInit = function() { var instance = this; var mergeCellsSetting = instance.getSettings().mergeCells; if (mergeCellsSetting) { if (!instance.mergeCells) { instance.mergeCells = new MergeCells(mergeCellsSetting); } } }; var afterInit = function() { var instance = this; if (instance.mergeCells) { instance.view.wt.wtTable.getCell = function(coords) { if (instance.getSettings().mergeCells) { var mergeParent = instance.mergeCells.mergedCellInfoCollection.getInfo(coords.row, coords.col); if (mergeParent) { coords = mergeParent; } } return WalkontableTable.prototype.getCell.call(this, coords); }; } }; var onBeforeKeyDown = function(event) { if (!this.mergeCells) { return; } var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; if (ctrlDown) { if (event.keyCode === 77) { this.mergeCells.mergeOrUnmergeSelection(this.getSelectedRange()); this.render(); event.stopImmediatePropagation(); } } }; var addMergeActionsToContextMenu = function(defaultOptions) { if (!this.getSettings().mergeCells) { return; } defaultOptions.items.push(Handsontable.ContextMenu.SEPARATOR); defaultOptions.items.push({ key: 'mergeCells', name: function() { var sel = this.getSelected(); var info = this.mergeCells.mergedCellInfoCollection.getInfo(sel[0], sel[1]); if (info) { return 'Unmerge cells'; } else { return 'Merge cells'; } }, callback: function() { this.mergeCells.mergeOrUnmergeSelection(this.getSelectedRange()); this.render(); }, disabled: function() { return false; } }); }; var afterRenderer = function(TD, row, col, prop, value, cellProperties) { if (this.mergeCells) { this.mergeCells.applySpanProperties(TD, row, col); } }; var modifyTransformFactory = function(hook) { return function(delta) { var mergeCellsSetting = this.getSettings().mergeCells; if (mergeCellsSetting) { var currentSelectedRange = this.getSelectedRange(); this.mergeCells.modifyTransform(hook, currentSelectedRange, delta); if (hook === "modifyTransformEnd") { var totalRows = this.countRows(); var totalCols = this.countCols(); if (currentSelectedRange.from.row < 0) { currentSelectedRange.from.row = 0; } else if (currentSelectedRange.from.row > 0 && currentSelectedRange.from.row >= totalRows) { currentSelectedRange.from.row = currentSelectedRange.from - 1; } if (currentSelectedRange.from.col < 0) { currentSelectedRange.from.col = 0; } else if (currentSelectedRange.from.col > 0 && currentSelectedRange.from.col >= totalCols) { currentSelectedRange.from.col = totalCols - 1; } } } }; }; var beforeSetRangeEnd = function(coords) { this.lastDesiredCoords = null; var mergeCellsSetting = this.getSettings().mergeCells; if (mergeCellsSetting) { var selRange = this.getSelectedRange(); selRange.highlight = new WalkontableCellCoords(selRange.highlight.row, selRange.highlight.col); selRange.to = coords; var rangeExpanded = false; do { rangeExpanded = false; for (var i = 0, ilen = this.mergeCells.mergedCellInfoCollection.length; i < ilen; i++) { var cellInfo = this.mergeCells.mergedCellInfoCollection[i]; var mergedCellTopLeft = new WalkontableCellCoords(cellInfo.row, cellInfo.col); var mergedCellBottomRight = new WalkontableCellCoords(cellInfo.row + cellInfo.rowspan - 1, cellInfo.col + cellInfo.colspan - 1); var mergedCellRange = new WalkontableCellRange(mergedCellTopLeft, mergedCellTopLeft, mergedCellBottomRight); if (selRange.expandByRange(mergedCellRange)) { coords.row = selRange.to.row; coords.col = selRange.to.col; rangeExpanded = true; } } } while (rangeExpanded); } }; var beforeDrawAreaBorders = function(corners, className) { if (className && className == 'area') { var mergeCellsSetting = this.getSettings().mergeCells; if (mergeCellsSetting) { var selRange = this.getSelectedRange(); var startRange = new WalkontableCellRange(selRange.from, selRange.from, selRange.from); var stopRange = new WalkontableCellRange(selRange.to, selRange.to, selRange.to); for (var i = 0, ilen = this.mergeCells.mergedCellInfoCollection.length; i < ilen; i++) { var cellInfo = this.mergeCells.mergedCellInfoCollection[i]; var mergedCellTopLeft = new WalkontableCellCoords(cellInfo.row, cellInfo.col); var mergedCellBottomRight = new WalkontableCellCoords(cellInfo.row + cellInfo.rowspan - 1, cellInfo.col + cellInfo.colspan - 1); var mergedCellRange = new WalkontableCellRange(mergedCellTopLeft, mergedCellTopLeft, mergedCellBottomRight); if (startRange.expandByRange(mergedCellRange)) { corners[0] = startRange.from.row; corners[1] = startRange.from.col; } if (stopRange.expandByRange(mergedCellRange)) { corners[2] = stopRange.from.row; corners[3] = stopRange.from.col; } } } } }; var afterGetCellMeta = function(row, col, cellProperties) { var mergeCellsSetting = this.getSettings().mergeCells; if (mergeCellsSetting) { var mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(row, col); if (mergeParent && (mergeParent.row != row || mergeParent.col != col)) { cellProperties.copyable = false; } } }; var afterViewportRowCalculatorOverride = function(calc) { var mergeCellsSetting = this.getSettings().mergeCells; if (mergeCellsSetting) { var colCount = this.countCols(); var mergeParent; for (var c = 0; c < colCount; c++) { mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(calc.startRow, c); if (mergeParent) { if (mergeParent.row < calc.startRow) { calc.startRow = mergeParent.row; return afterViewportRowCalculatorOverride.call(this, calc); } } mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(calc.endRow, c); if (mergeParent) { var mergeEnd = mergeParent.row + mergeParent.rowspan - 1; if (mergeEnd > calc.endRow) { calc.endRow = mergeEnd; return afterViewportRowCalculatorOverride.call(this, calc); } } } } }; var afterViewportColumnCalculatorOverride = function(calc) { var mergeCellsSetting = this.getSettings().mergeCells; if (mergeCellsSetting) { var rowCount = this.countRows(); var mergeParent; for (var r = 0; r < rowCount; r++) { mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(r, calc.startColumn); if (mergeParent) { if (mergeParent.col < calc.startColumn) { calc.startColumn = mergeParent.col; return afterViewportColumnCalculatorOverride.call(this, calc); } } mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(r, calc.endColumn); if (mergeParent) { var mergeEnd = mergeParent.col + mergeParent.colspan - 1; if (mergeEnd > calc.endColumn) { calc.endColumn = mergeEnd; return afterViewportColumnCalculatorOverride.call(this, calc); } } } } }; var isMultipleSelection = function(isMultiple) { if (isMultiple && this.mergeCells) { var mergedCells = this.mergeCells.mergedCellInfoCollection, selectionRange = this.getSelectedRange(); for (var group in mergedCells) { if (selectionRange.highlight.row == mergedCells[group].row && selectionRange.highlight.col == mergedCells[group].col && selectionRange.to.row == mergedCells[group].row + mergedCells[group].rowspan - 1 && selectionRange.to.col == mergedCells[group].col + mergedCells[group].colspan - 1) { return false; } } } return isMultiple; }; Handsontable.hooks.add('beforeInit', beforeInit); Handsontable.hooks.add('afterInit', afterInit); Handsontable.hooks.add('beforeKeyDown', onBeforeKeyDown); Handsontable.hooks.add('modifyTransformStart', modifyTransformFactory('modifyTransformStart')); Handsontable.hooks.add('modifyTransformEnd', modifyTransformFactory('modifyTransformEnd')); Handsontable.hooks.add('beforeSetRangeEnd', beforeSetRangeEnd); Handsontable.hooks.add('beforeDrawBorders', beforeDrawAreaBorders); Handsontable.hooks.add('afterIsMultipleSelection', isMultipleSelection); Handsontable.hooks.add('afterRenderer', afterRenderer); Handsontable.hooks.add('afterContextMenuDefaultOptions', addMergeActionsToContextMenu); Handsontable.hooks.add('afterGetCellMeta', afterGetCellMeta); Handsontable.hooks.add('afterViewportRowCalculatorOverride', afterViewportRowCalculatorOverride); Handsontable.hooks.add('afterViewportColumnCalculatorOverride', afterViewportColumnCalculatorOverride); Handsontable.MergeCells = MergeCells; //# },{"./../../3rdparty/walkontable/src/cellCoords.js":8,"./../../3rdparty/walkontable/src/cellRange.js":9,"./../../3rdparty/walkontable/src/table.js":22,"./../../plugins.js":52}],70:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { MultipleSelectionHandles: {get: function() { return MultipleSelectionHandles; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_eventManager_46_js__, $___46__46__47__46__46__47_plugins_46_js__; var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47__46__46__47_eventManager_46_js__ = require("./../../eventManager.js"), $___46__46__47__46__46__47_eventManager_46_js__ && $___46__46__47__46__46__47_eventManager_46_js__.__esModule && $___46__46__47__46__46__47_eventManager_46_js__ || {default: $___46__46__47__46__46__47_eventManager_46_js__}).eventManager; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; function MultipleSelectionHandles(instance) { this.instance = instance; this.dragged = []; this.eventManager = eventManagerObject(instance); this.bindTouchEvents(); } MultipleSelectionHandles.prototype.getCurrentRangeCoords = function(selectedRange, currentTouch, touchStartDirection, currentDirection, draggedHandle) { var topLeftCorner = selectedRange.getTopLeftCorner(), bottomRightCorner = selectedRange.getBottomRightCorner(), bottomLeftCorner = selectedRange.getBottomLeftCorner(), topRightCorner = selectedRange.getTopRightCorner(); var newCoords = { start: null, end: null }; switch (touchStartDirection) { case "NE-SW": switch (currentDirection) { case "NE-SW": case "NW-SE": if (draggedHandle == "topLeft") { newCoords = { start: new WalkontableCellCoords(currentTouch.row, selectedRange.highlight.col), end: new WalkontableCellCoords(bottomLeftCorner.row, currentTouch.col) }; } else { newCoords = { start: new WalkontableCellCoords(selectedRange.highlight.row, currentTouch.col), end: new WalkontableCellCoords(currentTouch.row, topLeftCorner.col) }; } break; case "SE-NW": if (draggedHandle == "bottomRight") { newCoords = { start: new WalkontableCellCoords(bottomRightCorner.row, currentTouch.col), end: new WalkontableCellCoords(currentTouch.row, topLeftCorner.col) }; } break; } break; case "NW-SE": switch (currentDirection) { case "NE-SW": if (draggedHandle == "topLeft") { newCoords = { start: currentTouch, end: bottomLeftCorner }; } else { newCoords.end = currentTouch; } break; case "NW-SE": if (draggedHandle == "topLeft") { newCoords = { start: currentTouch, end: bottomRightCorner }; } else { newCoords.end = currentTouch; } break; case "SE-NW": if (draggedHandle == "topLeft") { newCoords = { start: currentTouch, end: topLeftCorner }; } else { newCoords.end = currentTouch; } break; case "SW-NE": if (draggedHandle == "topLeft") { newCoords = { start: currentTouch, end: topRightCorner }; } else { newCoords.end = currentTouch; } break; } break; case "SW-NE": switch (currentDirection) { case "NW-SE": if (draggedHandle == "bottomRight") { newCoords = { start: new WalkontableCellCoords(currentTouch.row, topLeftCorner.col), end: new WalkontableCellCoords(bottomLeftCorner.row, currentTouch.col) }; } else { newCoords = { start: new WalkontableCellCoords(topLeftCorner.row, currentTouch.col), end: new WalkontableCellCoords(currentTouch.row, bottomRightCorner.col) }; } break; case "SW-NE": if (draggedHandle == "topLeft") { newCoords = { start: new WalkontableCellCoords(selectedRange.highlight.row, currentTouch.col), end: new WalkontableCellCoords(currentTouch.row, bottomRightCorner.col) }; } else { newCoords = { start: new WalkontableCellCoords(currentTouch.row, topLeftCorner.col), end: new WalkontableCellCoords(topLeftCorner.row, currentTouch.col) }; } break; case "SE-NW": if (draggedHandle == "bottomRight") { newCoords = { start: new WalkontableCellCoords(currentTouch.row, topRightCorner.col), end: new WalkontableCellCoords(topLeftCorner.row, currentTouch.col) }; } else if (draggedHandle == "topLeft") { newCoords = { start: bottomLeftCorner, end: currentTouch }; } break; } break; case "SE-NW": switch (currentDirection) { case "NW-SE": case "NE-SW": case "SW-NE": if (draggedHandle == "topLeft") { newCoords.end = currentTouch; } break; case "SE-NW": if (draggedHandle == "topLeft") { newCoords.end = currentTouch; } else { newCoords = { start: currentTouch, end: topLeftCorner }; } break; } break; } return newCoords; }; MultipleSelectionHandles.prototype.bindTouchEvents = function() { var that = this; var removeFromDragged = function(query) { if (this.dragged.length == 1) { this.dragged = []; return true; } var entryPosition = this.dragged.indexOf(query); if (entryPosition == -1) { return false; } else if (entryPosition === 0) { this.dragged = this.dragged.slice(0, 1); } else if (entryPosition == 1) { this.dragged = this.dragged.slice(-1); } }; this.eventManager.addEventListener(this.instance.rootElement, 'touchstart', function(event) { if (dom.hasClass(event.target, "topLeftSelectionHandle-HitArea")) { that.dragged.push("topLeft"); var selectedRange = that.instance.getSelectedRange(); that.touchStartRange = { width: selectedRange.getWidth(), height: selectedRange.getHeight(), direction: selectedRange.getDirection() }; event.preventDefault(); return false; } else if (dom.hasClass(event.target, "bottomRightSelectionHandle-HitArea")) { that.dragged.push("bottomRight"); var selectedRange = that.instance.getSelectedRange(); that.touchStartRange = { width: selectedRange.getWidth(), height: selectedRange.getHeight(), direction: selectedRange.getDirection() }; event.preventDefault(); return false; } }); this.eventManager.addEventListener(this.instance.rootElement, 'touchend', function(event) { if (dom.hasClass(event.target, "topLeftSelectionHandle-HitArea")) { removeFromDragged.call(that, "topLeft"); that.touchStartRange = void 0; event.preventDefault(); return false; } else if (dom.hasClass(event.target, "bottomRightSelectionHandle-HitArea")) { removeFromDragged.call(that, "bottomRight"); that.touchStartRange = void 0; event.preventDefault(); return false; } }); this.eventManager.addEventListener(this.instance.rootElement, 'touchmove', function(event) { var scrollTop = dom.getWindowScrollTop(), scrollLeft = dom.getWindowScrollLeft(); if (that.dragged.length > 0) { var endTarget = document.elementFromPoint(event.touches[0].screenX - scrollLeft, event.touches[0].screenY - scrollTop); if (!endTarget) { return; } if (endTarget.nodeName == "TD" || endTarget.nodeName == "TH") { var targetCoords = that.instance.getCoords(endTarget); if (targetCoords.col == -1) { targetCoords.col = 0; } var selectedRange = that.instance.getSelectedRange(), rangeWidth = selectedRange.getWidth(), rangeHeight = selectedRange.getHeight(), rangeDirection = selectedRange.getDirection(); if (rangeWidth == 1 && rangeHeight == 1) { that.instance.selection.setRangeEnd(targetCoords); } var newRangeCoords = that.getCurrentRangeCoords(selectedRange, targetCoords, that.touchStartRange.direction, rangeDirection, that.dragged[0]); if (newRangeCoords.start != null) { that.instance.selection.setRangeStart(newRangeCoords.start); } that.instance.selection.setRangeEnd(newRangeCoords.end); } event.preventDefault(); } }); }; MultipleSelectionHandles.prototype.isDragged = function() { return this.dragged.length > 0; }; var init = function() { var instance = this; Handsontable.plugins.multipleSelectionHandles = new MultipleSelectionHandles(instance); }; Handsontable.hooks.add('afterInit', init); //# },{"./../../dom.js":34,"./../../eventManager.js":48,"./../../plugins.js":52}],71:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { ObserveChanges: {get: function() { return ObserveChanges; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_plugins_46_js__, $___46__46__47__46__46__47_3rdparty_47_json_45_patch_45_duplex_46_js__; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; var jsonPatch = ($___46__46__47__46__46__47_3rdparty_47_json_45_patch_45_duplex_46_js__ = require("./../../3rdparty/json-patch-duplex.js"), $___46__46__47__46__46__47_3rdparty_47_json_45_patch_45_duplex_46_js__ && $___46__46__47__46__46__47_3rdparty_47_json_45_patch_45_duplex_46_js__.__esModule && $___46__46__47__46__46__47_3rdparty_47_json_45_patch_45_duplex_46_js__ || {default: $___46__46__47__46__46__47_3rdparty_47_json_45_patch_45_duplex_46_js__}).default; ; function ObserveChanges() {} Handsontable.hooks.add('afterLoadData', init); Handsontable.hooks.add('afterUpdateSettings', init); Handsontable.hooks.register('afterChangesObserved'); function init() { var instance = this; var pluginEnabled = instance.getSettings().observeChanges; if (pluginEnabled) { if (instance.observer) { destroy.call(instance); } createObserver.call(instance); bindEvents.call(instance); } else if (!pluginEnabled) { destroy.call(instance); } } function createObserver() { var instance = this; instance.observeChangesActive = true; instance.pauseObservingChanges = function() { instance.observeChangesActive = false; }; instance.resumeObservingChanges = function() { instance.observeChangesActive = true; }; instance.observedData = instance.getData(); instance.observer = jsonPatch.observe(instance.observedData, function(patches) { if (instance.observeChangesActive) { runHookForOperation.call(instance, patches); instance.render(); } instance.runHooks('afterChangesObserved'); }); } function runHookForOperation(rawPatches) { var instance = this; var patches = cleanPatches(rawPatches); for (var i = 0, len = patches.length; i < len; i++) { var patch = patches[i]; var parsedPath = parsePath(patch.path); switch (patch.op) { case 'add': if (isNaN(parsedPath.col)) { instance.runHooks('afterCreateRow', parsedPath.row); } else { instance.runHooks('afterCreateCol', parsedPath.col); } break; case 'remove': if (isNaN(parsedPath.col)) { instance.runHooks('afterRemoveRow', parsedPath.row, 1); } else { instance.runHooks('afterRemoveCol', parsedPath.col, 1); } break; case 'replace': instance.runHooks('afterChange', [parsedPath.row, parsedPath.col, null, patch.value], 'external'); break; } } function cleanPatches(rawPatches) { var patches; patches = removeLengthRelatedPatches(rawPatches); patches = removeMultipleAddOrRemoveColPatches(patches); return patches; } function removeMultipleAddOrRemoveColPatches(rawPatches) { var newOrRemovedColumns = []; return rawPatches.filter(function(patch) { var parsedPath = parsePath(patch.path); if (['add', 'remove'].indexOf(patch.op) != -1 && !isNaN(parsedPath.col)) { if (newOrRemovedColumns.indexOf(parsedPath.col) != -1) { return false; } else { newOrRemovedColumns.push(parsedPath.col); } } return true; }); } function removeLengthRelatedPatches(rawPatches) { return rawPatches.filter(function(patch) { return !/[/]length/ig.test(patch.path); }); } function parsePath(path) { var match = path.match(/^\/(\d+)\/?(.*)?$/); return { row: parseInt(match[1], 10), col: /^\d*$/.test(match[2]) ? parseInt(match[2], 10) : match[2] }; } } function destroy() { var instance = this; if (instance.observer) { destroyObserver.call(instance); unbindEvents.call(instance); } } function destroyObserver() { var instance = this; jsonPatch.unobserve(instance.observedData, instance.observer); delete instance.observeChangesActive; delete instance.pauseObservingChanges; delete instance.resumeObservingChanges; } function bindEvents() { var instance = this; instance.addHook('afterDestroy', destroy); instance.addHook('afterCreateRow', afterTableAlter); instance.addHook('afterRemoveRow', afterTableAlter); instance.addHook('afterCreateCol', afterTableAlter); instance.addHook('afterRemoveCol', afterTableAlter); instance.addHook('afterChange', function(changes, source) { if (source != 'loadData') { afterTableAlter.call(this); } }); } function unbindEvents() { var instance = this; instance.removeHook('afterDestroy', destroy); instance.removeHook('afterCreateRow', afterTableAlter); instance.removeHook('afterRemoveRow', afterTableAlter); instance.removeHook('afterCreateCol', afterTableAlter); instance.removeHook('afterRemoveCol', afterTableAlter); instance.removeHook('afterChange', afterTableAlter); } function afterTableAlter() { var instance = this; instance.pauseObservingChanges(); instance.addHookOnce('afterChangesObserved', function() { instance.resumeObservingChanges(); }); } //# },{"./../../3rdparty/json-patch-duplex.js":4,"./../../plugins.js":52}],72:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { HandsontablePersistentState: {get: function() { return HandsontablePersistentState; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_plugins_46_js__; var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; function Storage(prefix) { var savedKeys; var saveSavedKeys = function() { window.localStorage[prefix + '__' + 'persistentStateKeys'] = JSON.stringify(savedKeys); }; var loadSavedKeys = function() { var keysJSON = window.localStorage[prefix + '__' + 'persistentStateKeys']; var keys = typeof keysJSON == 'string' ? JSON.parse(keysJSON) : void 0; savedKeys = keys ? keys : []; }; var clearSavedKeys = function() { savedKeys = []; saveSavedKeys(); }; loadSavedKeys(); this.saveValue = function(key, value) { window.localStorage[prefix + '_' + key] = JSON.stringify(value); if (savedKeys.indexOf(key) == -1) { savedKeys.push(key); saveSavedKeys(); } }; this.loadValue = function(key, defaultValue) { key = typeof key != 'undefined' ? key : defaultValue; var value = window.localStorage[prefix + '_' + key]; return typeof value == "undefined" ? void 0 : JSON.parse(value); }; this.reset = function(key) { window.localStorage.removeItem(prefix + '_' + key); }; this.resetAll = function() { for (var index = 0; index < savedKeys.length; index++) { window.localStorage.removeItem(prefix + '_' + savedKeys[index]); } clearSavedKeys(); }; } function HandsontablePersistentState() { var plugin = this; this.init = function() { var instance = this, pluginSettings = instance.getSettings()['persistentState']; plugin.enabled = !!(pluginSettings); if (!plugin.enabled) { removeHooks.call(instance); return; } if (!instance.storage) { instance.storage = new Storage(instance.rootElement.id); } instance.resetState = plugin.resetValue; addHooks.call(instance); }; this.saveValue = function(key, value) { var instance = this; instance.storage.saveValue(key, value); }; this.loadValue = function(key, saveTo) { var instance = this; saveTo.value = instance.storage.loadValue(key); }; this.resetValue = function(key) { var instance = this; if (typeof key != 'undefined') { instance.storage.reset(key); } else { instance.storage.resetAll(); } }; var hooks = { 'persistentStateSave': plugin.saveValue, 'persistentStateLoad': plugin.loadValue, 'persistentStateReset': plugin.resetValue }; for (var hookName in hooks) { if (hooks.hasOwnProperty(hookName)) { Handsontable.hooks.register(hookName); } } function addHooks() { var instance = this; for (var hookName in hooks) { if (hooks.hasOwnProperty(hookName)) { instance.addHook(hookName, hooks[hookName]); } } } function removeHooks() { var instance = this; for (var hookName in hooks) { if (hooks.hasOwnProperty(hookName)) { instance.removeHook(hookName, hooks[hookName]); } } } } var htPersistentState = new HandsontablePersistentState(); Handsontable.hooks.add('beforeInit', htPersistentState.init); Handsontable.hooks.add('afterUpdateSettings', htPersistentState.init); //# },{"./../../plugins.js":52}],73:[function(require,module,exports){ "use strict"; var $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_renderers_46_js__; var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var $__0 = ($___46__46__47__46__46__47_renderers_46_js__ = require("./../../renderers.js"), $___46__46__47__46__46__47_renderers_46_js__ && $___46__46__47__46__46__47_renderers_46_js__.__esModule && $___46__46__47__46__46__47_renderers_46_js__ || {default: $___46__46__47__46__46__47_renderers_46_js__}), registerRenderer = $__0.registerRenderer, getRenderer = $__0.getRenderer; Handsontable.Search = function Search(instance) { this.query = function(queryStr, callback, queryMethod) { var rowCount = instance.countRows(); var colCount = instance.countCols(); var queryResult = []; if (!callback) { callback = Handsontable.Search.global.getDefaultCallback(); } if (!queryMethod) { queryMethod = Handsontable.Search.global.getDefaultQueryMethod(); } for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) { for (var colIndex = 0; colIndex < colCount; colIndex++) { var cellData = instance.getDataAtCell(rowIndex, colIndex); var cellProperties = instance.getCellMeta(rowIndex, colIndex); var cellCallback = cellProperties.search.callback || callback; var cellQueryMethod = cellProperties.search.queryMethod || queryMethod; var testResult = cellQueryMethod(queryStr, cellData); if (testResult) { var singleResult = { row: rowIndex, col: colIndex, data: cellData }; queryResult.push(singleResult); } if (cellCallback) { cellCallback(instance, rowIndex, colIndex, cellData, testResult); } } } return queryResult; }; }; Handsontable.Search.DEFAULT_CALLBACK = function(instance, row, col, data, testResult) { instance.getCellMeta(row, col).isSearchResult = testResult; }; Handsontable.Search.DEFAULT_QUERY_METHOD = function(query, value) { if (typeof query == 'undefined' || query == null || !query.toLowerCase || query.length === 0) { return false; } if (typeof value == 'undefined' || value == null) { return false; } return value.toString().toLowerCase().indexOf(query.toLowerCase()) != -1; }; Handsontable.Search.DEFAULT_SEARCH_RESULT_CLASS = 'htSearchResult'; Handsontable.Search.global = (function() { var defaultCallback = Handsontable.Search.DEFAULT_CALLBACK; var defaultQueryMethod = Handsontable.Search.DEFAULT_QUERY_METHOD; var defaultSearchResultClass = Handsontable.Search.DEFAULT_SEARCH_RESULT_CLASS; return { getDefaultCallback: function() { return defaultCallback; }, setDefaultCallback: function(newDefaultCallback) { defaultCallback = newDefaultCallback; }, getDefaultQueryMethod: function() { return defaultQueryMethod; }, setDefaultQueryMethod: function(newDefaultQueryMethod) { defaultQueryMethod = newDefaultQueryMethod; }, getDefaultSearchResultClass: function() { return defaultSearchResultClass; }, setDefaultSearchResultClass: function(newSearchResultClass) { defaultSearchResultClass = newSearchResultClass; } }; })(); Handsontable.SearchCellDecorator = function(instance, TD, row, col, prop, value, cellProperties) { var searchResultClass = (cellProperties.search !== null && typeof cellProperties.search == 'object' && cellProperties.search.searchResultClass) || Handsontable.Search.global.getDefaultSearchResultClass(); if (cellProperties.isSearchResult) { dom.addClass(TD, searchResultClass); } else { dom.removeClass(TD, searchResultClass); } }; var originalBaseRenderer = getRenderer('base'); registerRenderer('base', function(instance, TD, row, col, prop, value, cellProperties) { originalBaseRenderer.apply(this, arguments); Handsontable.SearchCellDecorator.apply(this, arguments); }); function init() { var instance = this; var pluginEnabled = !!instance.getSettings().search; if (pluginEnabled) { instance.search = new Handsontable.Search(instance); } else { delete instance.search; } } Handsontable.hooks.add('afterInit', init); Handsontable.hooks.add('afterUpdateSettings', init); //# },{"./../../dom.js":34,"./../../renderers.js":76}],74:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { TouchScroll: {get: function() { return TouchScroll; }}, __esModule: {value: true} }); var $___46__46__47__46__46__47_dom_46_js__, $___46__46__47__46__46__47_plugins_46_js__; var dom = ($___46__46__47__46__46__47_dom_46_js__ = require("./../../dom.js"), $___46__46__47__46__46__47_dom_46_js__ && $___46__46__47__46__46__47_dom_46_js__.__esModule && $___46__46__47__46__46__47_dom_46_js__ || {default: $___46__46__47__46__46__47_dom_46_js__}); var registerPlugin = ($___46__46__47__46__46__47_plugins_46_js__ = require("./../../plugins.js"), $___46__46__47__46__46__47_plugins_46_js__ && $___46__46__47__46__46__47_plugins_46_js__.__esModule && $___46__46__47__46__46__47_plugins_46_js__ || {default: $___46__46__47__46__46__47_plugins_46_js__}).registerPlugin; ; function TouchScroll() {} TouchScroll.prototype.init = function(instance) { this.instance = instance; this.bindEvents(); this.scrollbars = [this.instance.view.wt.wtOverlays.topOverlay, this.instance.view.wt.wtOverlays.leftOverlay, this.instance.view.wt.wtOverlays.topLeftCornerOverlay]; this.clones = [this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.holder.parentNode, this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.holder.parentNode, this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.holder.parentNode]; }; TouchScroll.prototype.bindEvents = function() { var that = this; this.instance.addHook('beforeTouchScroll', function() { Handsontable.freezeOverlays = true; for (var i = 0, cloneCount = that.clones.length; i < cloneCount; i++) { dom.addClass(that.clones[i], 'hide-tween'); } }); this.instance.addHook('afterMomentumScroll', function() { Handsontable.freezeOverlays = false; for (var i = 0, cloneCount = that.clones.length; i < cloneCount; i++) { dom.removeClass(that.clones[i], 'hide-tween'); } for (var i = 0, cloneCount = that.clones.length; i < cloneCount; i++) { dom.addClass(that.clones[i], 'show-tween'); } setTimeout(function() { for (var i = 0, cloneCount = that.clones.length; i < cloneCount; i++) { dom.removeClass(that.clones[i], 'show-tween'); } }, 400); for (var i = 0, cloneCount = that.scrollbars.length; i < cloneCount; i++) { that.scrollbars[i].refresh(); that.scrollbars[i].resetFixedPosition(); } }); }; var touchScrollHandler = new TouchScroll(); Handsontable.hooks.add('afterInit', function() { touchScrollHandler.init.call(touchScrollHandler, this); }); //# },{"./../../dom.js":34,"./../../plugins.js":52}],75:[function(require,module,exports){ "use strict"; var $___46__46__47__46__46__47_helpers_46_js__; var helper = ($___46__46__47__46__46__47_helpers_46_js__ = require("./../../helpers.js"), $___46__46__47__46__46__47_helpers_46_js__ && $___46__46__47__46__46__47_helpers_46_js__.__esModule && $___46__46__47__46__46__47_helpers_46_js__ || {default: $___46__46__47__46__46__47_helpers_46_js__}); Handsontable.UndoRedo = function(instance) { var plugin = this; this.instance = instance; this.doneActions = []; this.undoneActions = []; this.ignoreNewActions = false; instance.addHook("afterChange", function(changes, origin) { if (changes) { var action = new Handsontable.UndoRedo.ChangeAction(changes); plugin.done(action); } }); instance.addHook("afterCreateRow", function(index, amount, createdAutomatically) { if (createdAutomatically) { return; } var action = new Handsontable.UndoRedo.CreateRowAction(index, amount); plugin.done(action); }); instance.addHook("beforeRemoveRow", function(index, amount) { var originalData = plugin.instance.getData(); index = (originalData.length + index) % originalData.length; var removedData = originalData.slice(index, index + amount); var action = new Handsontable.UndoRedo.RemoveRowAction(index, removedData); plugin.done(action); }); instance.addHook("afterCreateCol", function(index, amount, createdAutomatically) { if (createdAutomatically) { return; } var action = new Handsontable.UndoRedo.CreateColumnAction(index, amount); plugin.done(action); }); instance.addHook("beforeRemoveCol", function(index, amount) { var originalData = plugin.instance.getData(); index = (plugin.instance.countCols() + index) % plugin.instance.countCols(); var removedData = []; for (var i = 0, len = originalData.length; i < len; i++) { removedData[i] = originalData[i].slice(index, index + amount); } var headers; if (Array.isArray(instance.getSettings().colHeaders)) { headers = instance.getSettings().colHeaders.slice(index, index + removedData.length); } var action = new Handsontable.UndoRedo.RemoveColumnAction(index, removedData, headers); plugin.done(action); }); instance.addHook("beforeCellAlignment", function(stateBefore, range, type, alignment) { var action = new Handsontable.UndoRedo.CellAlignmentAction(stateBefore, range, type, alignment); plugin.done(action); }); }; Handsontable.UndoRedo.prototype.done = function(action) { if (!this.ignoreNewActions) { this.doneActions.push(action); this.undoneActions.length = 0; } }; Handsontable.UndoRedo.prototype.undo = function() { if (this.isUndoAvailable()) { var action = this.doneActions.pop(); this.ignoreNewActions = true; var that = this; action.undo(this.instance, function() { that.ignoreNewActions = false; that.undoneActions.push(action); }); } }; Handsontable.UndoRedo.prototype.redo = function() { if (this.isRedoAvailable()) { var action = this.undoneActions.pop(); this.ignoreNewActions = true; var that = this; action.redo(this.instance, function() { that.ignoreNewActions = false; that.doneActions.push(action); }); } }; Handsontable.UndoRedo.prototype.isUndoAvailable = function() { return this.doneActions.length > 0; }; Handsontable.UndoRedo.prototype.isRedoAvailable = function() { return this.undoneActions.length > 0; }; Handsontable.UndoRedo.prototype.clear = function() { this.doneActions.length = 0; this.undoneActions.length = 0; }; Handsontable.UndoRedo.Action = function() {}; Handsontable.UndoRedo.Action.prototype.undo = function() {}; Handsontable.UndoRedo.Action.prototype.redo = function() {}; Handsontable.UndoRedo.ChangeAction = function(changes) { this.changes = changes; }; helper.inherit(Handsontable.UndoRedo.ChangeAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.ChangeAction.prototype.undo = function(instance, undoneCallback) { var data = helper.deepClone(this.changes), emptyRowsAtTheEnd = instance.countEmptyRows(true), emptyColsAtTheEnd = instance.countEmptyCols(true); for (var i = 0, len = data.length; i < len; i++) { data[i].splice(3, 1); } instance.addHookOnce('afterChange', undoneCallback); instance.setDataAtRowProp(data, null, null, 'undo'); for (var i = 0, len = data.length; i < len; i++) { if (instance.getSettings().minSpareRows && data[i][0] + 1 + instance.getSettings().minSpareRows === instance.countRows() && emptyRowsAtTheEnd == instance.getSettings().minSpareRows) { instance.alter('remove_row', parseInt(data[i][0] + 1, 10), instance.getSettings().minSpareRows); instance.undoRedo.doneActions.pop(); } if (instance.getSettings().minSpareCols && data[i][1] + 1 + instance.getSettings().minSpareCols === instance.countCols() && emptyColsAtTheEnd == instance.getSettings().minSpareCols) { instance.alter('remove_col', parseInt(data[i][1] + 1, 10), instance.getSettings().minSpareCols); instance.undoRedo.doneActions.pop(); } } }; Handsontable.UndoRedo.ChangeAction.prototype.redo = function(instance, onFinishCallback) { var data = helper.deepClone(this.changes); for (var i = 0, len = data.length; i < len; i++) { data[i].splice(2, 1); } instance.addHookOnce('afterChange', onFinishCallback); instance.setDataAtRowProp(data, null, null, 'redo'); }; Handsontable.UndoRedo.CreateRowAction = function(index, amount) { this.index = index; this.amount = amount; }; helper.inherit(Handsontable.UndoRedo.CreateRowAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.CreateRowAction.prototype.undo = function(instance, undoneCallback) { var rowCount = instance.countRows(), minSpareRows = instance.getSettings().minSpareRows; if (this.index >= rowCount && this.index - minSpareRows < rowCount) { this.index -= minSpareRows; } instance.addHookOnce('afterRemoveRow', undoneCallback); instance.alter('remove_row', this.index, this.amount); }; Handsontable.UndoRedo.CreateRowAction.prototype.redo = function(instance, redoneCallback) { instance.addHookOnce('afterCreateRow', redoneCallback); instance.alter('insert_row', this.index + 1, this.amount); }; Handsontable.UndoRedo.RemoveRowAction = function(index, data) { this.index = index; this.data = data; }; helper.inherit(Handsontable.UndoRedo.RemoveRowAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.RemoveRowAction.prototype.undo = function(instance, undoneCallback) { var spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.data); Array.prototype.splice.apply(instance.getData(), spliceArgs); instance.addHookOnce('afterRender', undoneCallback); instance.render(); }; Handsontable.UndoRedo.RemoveRowAction.prototype.redo = function(instance, redoneCallback) { instance.addHookOnce('afterRemoveRow', redoneCallback); instance.alter('remove_row', this.index, this.data.length); }; Handsontable.UndoRedo.CreateColumnAction = function(index, amount) { this.index = index; this.amount = amount; }; helper.inherit(Handsontable.UndoRedo.CreateColumnAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.CreateColumnAction.prototype.undo = function(instance, undoneCallback) { instance.addHookOnce('afterRemoveCol', undoneCallback); instance.alter('remove_col', this.index, this.amount); }; Handsontable.UndoRedo.CreateColumnAction.prototype.redo = function(instance, redoneCallback) { instance.addHookOnce('afterCreateCol', redoneCallback); instance.alter('insert_col', this.index + 1, this.amount); }; Handsontable.UndoRedo.CellAlignmentAction = function(stateBefore, range, type, alignment) { this.stateBefore = stateBefore; this.range = range; this.type = type; this.alignment = alignment; }; Handsontable.UndoRedo.CellAlignmentAction.prototype.undo = function(instance, undoneCallback) { if (!instance.contextMenu) { return; } for (var row = this.range.from.row; row <= this.range.to.row; row++) { for (var col = this.range.from.col; col <= this.range.to.col; col++) { instance.setCellMeta(row, col, 'className', this.stateBefore[row][col] || ' htLeft'); } } instance.addHookOnce('afterRender', undoneCallback); instance.render(); }; Handsontable.UndoRedo.CellAlignmentAction.prototype.redo = function(instance, undoneCallback) { if (!instance.contextMenu) { return; } for (var row = this.range.from.row; row <= this.range.to.row; row++) { for (var col = this.range.from.col; col <= this.range.to.col; col++) { instance.contextMenu.align.call(instance, this.range, this.type, this.alignment); } } instance.addHookOnce('afterRender', undoneCallback); instance.render(); }; Handsontable.UndoRedo.RemoveColumnAction = function(index, data, headers) { this.index = index; this.data = data; this.amount = this.data[0].length; this.headers = headers; }; helper.inherit(Handsontable.UndoRedo.RemoveColumnAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.RemoveColumnAction.prototype.undo = function(instance, undoneCallback) { var row, spliceArgs; for (var i = 0, len = instance.getData().length; i < len; i++) { row = instance.getSourceDataAtRow(i); spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.data[i]); Array.prototype.splice.apply(row, spliceArgs); } if (typeof this.headers != 'undefined') { spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.headers); Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArgs); } instance.addHookOnce('afterRender', undoneCallback); instance.render(); }; Handsontable.UndoRedo.RemoveColumnAction.prototype.redo = function(instance, redoneCallback) { instance.addHookOnce('afterRemoveCol', redoneCallback); instance.alter('remove_col', this.index, this.amount); }; function init() { var instance = this; var pluginEnabled = typeof instance.getSettings().undo == 'undefined' || instance.getSettings().undo; if (pluginEnabled) { if (!instance.undoRedo) { instance.undoRedo = new Handsontable.UndoRedo(instance); exposeUndoRedoMethods(instance); instance.addHook('beforeKeyDown', onBeforeKeyDown); instance.addHook('afterChange', onAfterChange); } } else { if (instance.undoRedo) { delete instance.undoRedo; removeExposedUndoRedoMethods(instance); instance.removeHook('beforeKeyDown', onBeforeKeyDown); instance.removeHook('afterChange', onAfterChange); } } } function onBeforeKeyDown(event) { var instance = this; var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; if (ctrlDown) { if (event.keyCode === 89 || (event.shiftKey && event.keyCode === 90)) { instance.undoRedo.redo(); event.stopImmediatePropagation(); } else if (event.keyCode === 90) { instance.undoRedo.undo(); event.stopImmediatePropagation(); } } } function onAfterChange(changes, source) { var instance = this; if (source == 'loadData') { return instance.undoRedo.clear(); } } function exposeUndoRedoMethods(instance) { instance.undo = function() { return instance.undoRedo.undo(); }; instance.redo = function() { return instance.undoRedo.redo(); }; instance.isUndoAvailable = function() { return instance.undoRedo.isUndoAvailable(); }; instance.isRedoAvailable = function() { return instance.undoRedo.isRedoAvailable(); }; instance.clearUndo = function() { return instance.undoRedo.clear(); }; } function removeExposedUndoRedoMethods(instance) { delete instance.undo; delete instance.redo; delete instance.isUndoAvailable; delete instance.isRedoAvailable; delete instance.clearUndo; } Handsontable.hooks.add('afterInit', init); Handsontable.hooks.add('afterUpdateSettings', init); //# },{"./../../helpers.js":49}],76:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { registerRenderer: {get: function() { return registerRenderer; }}, getRenderer: {get: function() { return getRenderer; }}, hasRenderer: {get: function() { return hasRenderer; }}, __esModule: {value: true} }); var $__helpers_46_js__; var helper = ($__helpers_46_js__ = require("./helpers.js"), $__helpers_46_js__ && $__helpers_46_js__.__esModule && $__helpers_46_js__ || {default: $__helpers_46_js__}); ; var registeredRenderers = {}; Handsontable.renderers = Handsontable.renderers || {}; Handsontable.renderers.registerRenderer = registerRenderer; Handsontable.renderers.getRenderer = getRenderer; function registerRenderer(rendererName, rendererFunction) { var registerName; registeredRenderers[rendererName] = rendererFunction; registerName = helper.toUpperCaseFirst(rendererName) + 'Renderer'; Handsontable.renderers[registerName] = rendererFunction; Handsontable[registerName] = rendererFunction; } function getRenderer(rendererName) { if (typeof rendererName == 'function') { return rendererName; } if (typeof rendererName != 'string') { throw Error('Only strings and functions can be passed as "renderer" parameter'); } if (!(rendererName in registeredRenderers)) { throw Error('No editor registered under name "' + rendererName + '"'); } return registeredRenderers[rendererName]; } function hasRenderer(rendererName) { return rendererName in registeredRenderers; } //# },{"./helpers.js":49}],77:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { cellDecorator: {get: function() { return cellDecorator; }}, __esModule: {value: true} }); var $___46__46__47_dom_46_js__, $___46__46__47_renderers_46_js__; var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var registerRenderer = ($___46__46__47_renderers_46_js__ = require("./../renderers.js"), $___46__46__47_renderers_46_js__ && $___46__46__47_renderers_46_js__.__esModule && $___46__46__47_renderers_46_js__ || {default: $___46__46__47_renderers_46_js__}).registerRenderer; ; registerRenderer('base', cellDecorator); Handsontable.renderers.cellDecorator = cellDecorator; function cellDecorator(instance, TD, row, col, prop, value, cellProperties) { if (cellProperties.className) { if (TD.className) { TD.className = TD.className + " " + cellProperties.className; } else { TD.className = cellProperties.className; } } if (cellProperties.readOnly) { dom.addClass(TD, cellProperties.readOnlyCellClassName); } if (cellProperties.valid === false && cellProperties.invalidCellClassName) { dom.addClass(TD, cellProperties.invalidCellClassName); } else { dom.removeClass(TD, cellProperties.invalidCellClassName); } if (cellProperties.wordWrap === false && cellProperties.noWordWrapClassName) { dom.addClass(TD, cellProperties.noWordWrapClassName); } if (!value && cellProperties.placeholder) { dom.addClass(TD, cellProperties.placeholderCellClassName); } } //# },{"./../dom.js":34,"./../renderers.js":76}],78:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { autocompleteRenderer: {get: function() { return autocompleteRenderer; }}, __esModule: {value: true} }); var $___46__46__47_dom_46_js__, $___46__46__47_eventManager_46_js__, $___46__46__47_renderers_46_js__, $___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__; var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var eventManagerObject = ($___46__46__47_eventManager_46_js__ = require("./../eventManager.js"), $___46__46__47_eventManager_46_js__ && $___46__46__47_eventManager_46_js__.__esModule && $___46__46__47_eventManager_46_js__ || {default: $___46__46__47_eventManager_46_js__}).eventManager; var $__1 = ($___46__46__47_renderers_46_js__ = require("./../renderers.js"), $___46__46__47_renderers_46_js__ && $___46__46__47_renderers_46_js__.__esModule && $___46__46__47_renderers_46_js__ || {default: $___46__46__47_renderers_46_js__}), getRenderer = $__1.getRenderer, registerRenderer = $__1.registerRenderer; var WalkontableCellCoords = ($___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ = require("./../3rdparty/walkontable/src/cellCoords.js"), $___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ && $___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__.__esModule && $___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ || {default: $___46__46__47_3rdparty_47_walkontable_47_src_47_cellCoords_46_js__}).WalkontableCellCoords; ; var clonableWRAPPER = document.createElement('DIV'); clonableWRAPPER.className = 'htAutocompleteWrapper'; var clonableARROW = document.createElement('DIV'); clonableARROW.className = 'htAutocompleteArrow'; clonableARROW.appendChild(document.createTextNode(String.fromCharCode(9660))); var wrapTdContentWithWrapper = function(TD, WRAPPER) { WRAPPER.innerHTML = TD.innerHTML; dom.empty(TD); TD.appendChild(WRAPPER); }; registerRenderer('autocomplete', autocompleteRenderer); function autocompleteRenderer(instance, TD, row, col, prop, value, cellProperties) { var WRAPPER = clonableWRAPPER.cloneNode(true); var ARROW = clonableARROW.cloneNode(true); getRenderer('text')(instance, TD, row, col, prop, value, cellProperties); TD.appendChild(ARROW); dom.addClass(TD, 'htAutocomplete'); if (!TD.firstChild) { TD.appendChild(document.createTextNode(String.fromCharCode(160))); } if (!instance.acArrowListener) { var eventManager = eventManagerObject(instance); instance.acArrowListener = function(event) { if (dom.hasClass(event.target, 'htAutocompleteArrow')) { instance.view.wt.getSetting('onCellDblClick', null, new WalkontableCellCoords(row, col), TD); } }; eventManager.addEventListener(instance.rootElement, 'mousedown', instance.acArrowListener); instance.addHookOnce('afterDestroy', function() { eventManager.clear(); }); } } //# },{"./../3rdparty/walkontable/src/cellCoords.js":8,"./../dom.js":34,"./../eventManager.js":48,"./../renderers.js":76}],79:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { checkboxRenderer: {get: function() { return checkboxRenderer; }}, __esModule: {value: true} }); var $___46__46__47_dom_46_js__, $___46__46__47_helpers_46_js__, $___46__46__47_eventManager_46_js__, $___46__46__47_renderers_46_js__; var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var helper = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}); var eventManagerObject = ($___46__46__47_eventManager_46_js__ = require("./../eventManager.js"), $___46__46__47_eventManager_46_js__ && $___46__46__47_eventManager_46_js__.__esModule && $___46__46__47_eventManager_46_js__ || {default: $___46__46__47_eventManager_46_js__}).eventManager; var $__1 = ($___46__46__47_renderers_46_js__ = require("./../renderers.js"), $___46__46__47_renderers_46_js__ && $___46__46__47_renderers_46_js__.__esModule && $___46__46__47_renderers_46_js__ || {default: $___46__46__47_renderers_46_js__}), getRenderer = $__1.getRenderer, registerRenderer = $__1.registerRenderer; ; registerRenderer('checkbox', checkboxRenderer); var clonableINPUT = document.createElement('INPUT'); clonableINPUT.className = 'htCheckboxRendererInput'; clonableINPUT.type = 'checkbox'; clonableINPUT.setAttribute('autocomplete', 'off'); function checkboxRenderer(instance, TD, row, col, prop, value, cellProperties) { var eventManager = eventManagerObject(instance); if (typeof cellProperties.checkedTemplate === "undefined") { cellProperties.checkedTemplate = true; } if (typeof cellProperties.uncheckedTemplate === "undefined") { cellProperties.uncheckedTemplate = false; } dom.empty(TD); var INPUT = clonableINPUT.cloneNode(false); if (value === cellProperties.checkedTemplate || value === helper.stringify(cellProperties.checkedTemplate)) { INPUT.checked = true; TD.appendChild(INPUT); } else if (value === cellProperties.uncheckedTemplate || value === helper.stringify(cellProperties.uncheckedTemplate)) { TD.appendChild(INPUT); } else if (value === null) { INPUT.className += ' noValue'; TD.appendChild(INPUT); } else { dom.fastInnerText(TD, '#bad value#'); } if (cellProperties.readOnly) { eventManager.addEventListener(INPUT, 'click', function(event) { event.preventDefault(); }); } else { eventManager.addEventListener(INPUT, 'mousedown', function(event) { helper.stopPropagation(event); }); eventManager.addEventListener(INPUT, 'mouseup', function(event) { helper.stopPropagation(event); }); eventManager.addEventListener(INPUT, 'change', function() { if (this.checked) { instance.setDataAtRowProp(row, prop, cellProperties.checkedTemplate); } else { instance.setDataAtRowProp(row, prop, cellProperties.uncheckedTemplate); } }); } if (!instance.CheckboxRenderer || !instance.CheckboxRenderer.beforeKeyDownHookBound) { instance.CheckboxRenderer = {beforeKeyDownHookBound: true}; instance.addHook('beforeKeyDown', function(event) { dom.enableImmediatePropagation(event); if (event.keyCode == helper.keyCode.SPACE || event.keyCode == helper.keyCode.ENTER) { var cell, checkbox, cellProperties; var selRange = instance.getSelectedRange(); var topLeft = selRange.getTopLeftCorner(); var bottomRight = selRange.getBottomRightCorner(); for (var row = topLeft.row; row <= bottomRight.row; row++) { for (var col = topLeft.col; col <= bottomRight.col; col++) { cell = instance.getCell(row, col); cellProperties = instance.getCellMeta(row, col); checkbox = cell.querySelectorAll('input[type=checkbox]'); if (checkbox.length > 0 && !cellProperties.readOnly) { if (!event.isImmediatePropagationStopped()) { event.stopImmediatePropagation(); event.preventDefault(); } for (var i = 0, len = checkbox.length; i < len; i++) { checkbox[i].checked = !checkbox[i].checked; eventManager.fireEvent(checkbox[i], 'change'); } } } } } }); } } //# },{"./../dom.js":34,"./../eventManager.js":48,"./../helpers.js":49,"./../renderers.js":76}],80:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { htmlRenderer: {get: function() { return htmlRenderer; }}, __esModule: {value: true} }); var $___46__46__47_dom_46_js__, $___46__46__47_renderers_46_js__; var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var $__0 = ($___46__46__47_renderers_46_js__ = require("./../renderers.js"), $___46__46__47_renderers_46_js__ && $___46__46__47_renderers_46_js__.__esModule && $___46__46__47_renderers_46_js__ || {default: $___46__46__47_renderers_46_js__}), getRenderer = $__0.getRenderer, registerRenderer = $__0.registerRenderer; ; registerRenderer('html', htmlRenderer); function htmlRenderer(instance, TD, row, col, prop, value, cellProperties) { getRenderer('base').apply(this, arguments); dom.fastInnerHTML(TD, value); } //# },{"./../dom.js":34,"./../renderers.js":76}],81:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { numericRenderer: {get: function() { return numericRenderer; }}, __esModule: {value: true} }); var $___46__46__47_dom_46_js__, $___46__46__47_helpers_46_js__, $__numeral__, $___46__46__47_renderers_46_js__; var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var helper = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}); var numeral = ($__numeral__ = require("numeral"), $__numeral__ && $__numeral__.__esModule && $__numeral__ || {default: $__numeral__}).default; var $__1 = ($___46__46__47_renderers_46_js__ = require("./../renderers.js"), $___46__46__47_renderers_46_js__ && $___46__46__47_renderers_46_js__.__esModule && $___46__46__47_renderers_46_js__ || {default: $___46__46__47_renderers_46_js__}), getRenderer = $__1.getRenderer, registerRenderer = $__1.registerRenderer; ; registerRenderer('numeric', numericRenderer); function numericRenderer(instance, TD, row, col, prop, value, cellProperties) { if (helper.isNumeric(value)) { if (typeof cellProperties.language !== 'undefined') { numeral.language(cellProperties.language); } value = numeral(value).format(cellProperties.format || '0'); dom.addClass(TD, 'htNumeric'); } getRenderer('text')(instance, TD, row, col, prop, value, cellProperties); } //# },{"./../dom.js":34,"./../helpers.js":49,"./../renderers.js":76,"numeral":"numeral"}],82:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { passwordRenderer: {get: function() { return passwordRenderer; }}, __esModule: {value: true} }); var $___46__46__47_dom_46_js__, $___46__46__47_renderers_46_js__; var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var $__0 = ($___46__46__47_renderers_46_js__ = require("./../renderers.js"), $___46__46__47_renderers_46_js__ && $___46__46__47_renderers_46_js__.__esModule && $___46__46__47_renderers_46_js__ || {default: $___46__46__47_renderers_46_js__}), getRenderer = $__0.getRenderer, registerRenderer = $__0.registerRenderer; ; registerRenderer('password', passwordRenderer); function passwordRenderer(instance, TD, row, col, prop, value, cellProperties) { getRenderer('text').apply(this, arguments); value = TD.innerHTML; var hash; var hashLength = cellProperties.hashLength || value.length; var hashSymbol = cellProperties.hashSymbol || '*'; for (hash = ''; hash.split(hashSymbol).length - 1 < hashLength; hash += hashSymbol) {} dom.fastInnerHTML(TD, hash); } //# },{"./../dom.js":34,"./../renderers.js":76}],83:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { textRenderer: {get: function() { return textRenderer; }}, __esModule: {value: true} }); var $___46__46__47_dom_46_js__, $___46__46__47_helpers_46_js__, $___46__46__47_renderers_46_js__; var dom = ($___46__46__47_dom_46_js__ = require("./../dom.js"), $___46__46__47_dom_46_js__ && $___46__46__47_dom_46_js__.__esModule && $___46__46__47_dom_46_js__ || {default: $___46__46__47_dom_46_js__}); var helper = ($___46__46__47_helpers_46_js__ = require("./../helpers.js"), $___46__46__47_helpers_46_js__ && $___46__46__47_helpers_46_js__.__esModule && $___46__46__47_helpers_46_js__ || {default: $___46__46__47_helpers_46_js__}); var $__0 = ($___46__46__47_renderers_46_js__ = require("./../renderers.js"), $___46__46__47_renderers_46_js__ && $___46__46__47_renderers_46_js__.__esModule && $___46__46__47_renderers_46_js__ || {default: $___46__46__47_renderers_46_js__}), getRenderer = $__0.getRenderer, registerRenderer = $__0.registerRenderer; ; registerRenderer('text', textRenderer); function textRenderer(instance, TD, row, col, prop, value, cellProperties) { getRenderer('base').apply(this, arguments); if (!value && cellProperties.placeholder) { value = cellProperties.placeholder; } var escaped = helper.stringify(value); if (!instance.getSettings().trimWhitespace) { escaped = escaped.replace(/ /g, String.fromCharCode(160)); } if (cellProperties.rendererTemplate) { dom.empty(TD); var TEMPLATE = document.createElement('TEMPLATE'); TEMPLATE.setAttribute('bind', '{{}}'); TEMPLATE.innerHTML = cellProperties.rendererTemplate; HTMLTemplateElement.decorate(TEMPLATE); TEMPLATE.model = instance.getSourceDataAtRow(row); TD.appendChild(TEMPLATE); } else { dom.fastInnerText(TD, escaped); } } //# },{"./../dom.js":34,"./../helpers.js":49,"./../renderers.js":76}],84:[function(require,module,exports){ "use strict"; if (!Array.prototype.filter) { Array.prototype.filter = function(fun, thisp) { "use strict"; if (typeof this === "undefined" || this === null) { throw new TypeError(); } if (typeof fun !== "function") { throw new TypeError(); } thisp = thisp || this; if (isNodeList(thisp)) { thisp = convertNodeListToArray(thisp); } var len = thisp.length, res = [], i, val; for (i = 0; i < len; i += 1) { if (thisp.hasOwnProperty(i)) { val = thisp[i]; if (fun.call(thisp, val, i, thisp)) { res.push(val); } } } return res; function isNodeList(object) { return /NodeList/i.test(object.item); } function convertNodeListToArray(nodeList) { var array = []; for (var i = 0, len = nodeList.length; i < len; i++) { array[i] = nodeList[i]; } return array; } }; } //# },{}],85:[function(require,module,exports){ "use strict"; if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) { from += len; } for (; from < len; from++) { if (from in this && this[from] === elt) { return from; } } return -1; }; } //# },{}],86:[function(require,module,exports){ "use strict"; if (!Array.isArray) { Array.isArray = function(obj) { return Object.prototype.toString.call(obj) == '[object Array]'; }; } //# },{}],87:[function(require,module,exports){ "use strict"; (function(global) { 'use strict'; if (global.$traceurRuntime) { return; } var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $Object.defineProperties; var $defineProperty = $Object.defineProperty; var $freeze = $Object.freeze; var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor; var $getOwnPropertyNames = $Object.getOwnPropertyNames; var $keys = $Object.keys; var $hasOwnProperty = $Object.prototype.hasOwnProperty; var $toString = $Object.prototype.toString; var $preventExtensions = Object.preventExtensions; var $seal = Object.seal; var $isExtensible = Object.isExtensible; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var method = nonEnum; var counter = 0; function newUniqueString() { return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__'; } var symbolInternalProperty = newUniqueString(); var symbolDescriptionProperty = newUniqueString(); var symbolDataProperty = newUniqueString(); var symbolValues = $create(null); var privateNames = $create(null); function isPrivateName(s) { return privateNames[s]; } function createPrivateName() { var s = newUniqueString(); privateNames[s] = true; return s; } function isShimSymbol(symbol) { return typeof symbol === 'object' && symbol instanceof SymbolValue; } function typeOf(v) { if (isShimSymbol(v)) return 'symbol'; return typeof v; } function Symbol(description) { var value = new SymbolValue(description); if (!(this instanceof Symbol)) return value; throw new TypeError('Symbol cannot be new\'ed'); } $defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(Symbol.prototype, 'toString', method(function() { var symbolValue = this[symbolDataProperty]; if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); var desc = symbolValue[symbolDescriptionProperty]; if (desc === undefined) desc = ''; return 'Symbol(' + desc + ')'; })); $defineProperty(Symbol.prototype, 'valueOf', method(function() { var symbolValue = this[symbolDataProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; return symbolValue; })); function SymbolValue(description) { var key = newUniqueString(); $defineProperty(this, symbolDataProperty, {value: this}); $defineProperty(this, symbolInternalProperty, {value: key}); $defineProperty(this, symbolDescriptionProperty, {value: description}); freeze(this); symbolValues[key] = this; } $defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(SymbolValue.prototype, 'toString', { value: Symbol.prototype.toString, enumerable: false }); $defineProperty(SymbolValue.prototype, 'valueOf', { value: Symbol.prototype.valueOf, enumerable: false }); var hashProperty = createPrivateName(); var hashPropertyDescriptor = {value: undefined}; var hashObjectProperties = { hash: {value: undefined}, self: {value: undefined} }; var hashCounter = 0; function getOwnHashObject(object) { var hashObject = object[hashProperty]; if (hashObject && hashObject.self === object) return hashObject; if ($isExtensible(object)) { hashObjectProperties.hash.value = hashCounter++; hashObjectProperties.self.value = object; hashPropertyDescriptor.value = $create(null, hashObjectProperties); $defineProperty(object, hashProperty, hashPropertyDescriptor); return hashPropertyDescriptor.value; } return undefined; } function freeze(object) { getOwnHashObject(object); return $freeze.apply(this, arguments); } function preventExtensions(object) { getOwnHashObject(object); return $preventExtensions.apply(this, arguments); } function seal(object) { getOwnHashObject(object); return $seal.apply(this, arguments); } freeze(SymbolValue.prototype); function isSymbolString(s) { return symbolValues[s] || privateNames[s]; } function toProperty(name) { if (isShimSymbol(name)) return name[symbolInternalProperty]; return name; } function removeSymbolKeys(array) { var rv = []; for (var i = 0; i < array.length; i++) { if (!isSymbolString(array[i])) { rv.push(array[i]); } } return rv; } function getOwnPropertyNames(object) { return removeSymbolKeys($getOwnPropertyNames(object)); } function keys(object) { return removeSymbolKeys($keys(object)); } function getOwnPropertySymbols(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var symbol = symbolValues[names[i]]; if (symbol) { rv.push(symbol); } } return rv; } function getOwnPropertyDescriptor(object, name) { return $getOwnPropertyDescriptor(object, toProperty(name)); } function hasOwnProperty(name) { return $hasOwnProperty.call(this, toProperty(name)); } function getOption(name) { return global.traceur && global.traceur.options[name]; } function defineProperty(object, name, descriptor) { if (isShimSymbol(name)) { name = name[symbolInternalProperty]; } $defineProperty(object, name, descriptor); return object; } function polyfillObject(Object) { $defineProperty(Object, 'defineProperty', {value: defineProperty}); $defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames}); $defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor}); $defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty}); $defineProperty(Object, 'freeze', {value: freeze}); $defineProperty(Object, 'preventExtensions', {value: preventExtensions}); $defineProperty(Object, 'seal', {value: seal}); $defineProperty(Object, 'keys', {value: keys}); } function exportStar(object) { for (var i = 1; i < arguments.length; i++) { var names = $getOwnPropertyNames(arguments[i]); for (var j = 0; j < names.length; j++) { var name = names[j]; if (isSymbolString(name)) continue; (function(mod, name) { $defineProperty(object, name, { get: function() { return mod[name]; }, enumerable: true }); })(arguments[i], names[j]); } } return object; } function isObject(x) { return x != null && (typeof x === 'object' || typeof x === 'function'); } function toObject(x) { if (x == null) throw $TypeError(); return $Object(x); } function checkObjectCoercible(argument) { if (argument == null) { throw new TypeError('Value cannot be converted to an Object'); } return argument; } function polyfillSymbol(global, Symbol) { if (!global.Symbol) { global.Symbol = Symbol; Object.getOwnPropertySymbols = getOwnPropertySymbols; } if (!global.Symbol.iterator) { global.Symbol.iterator = Symbol('Symbol.iterator'); } } function setupGlobals(global) { polyfillSymbol(global, Symbol); global.Reflect = global.Reflect || {}; global.Reflect.global = global.Reflect.global || global; polyfillObject(global.Object); } setupGlobals(global); global.$traceurRuntime = { checkObjectCoercible: checkObjectCoercible, createPrivateName: createPrivateName, defineProperties: $defineProperties, defineProperty: $defineProperty, exportStar: exportStar, getOwnHashObject: getOwnHashObject, getOwnPropertyDescriptor: $getOwnPropertyDescriptor, getOwnPropertyNames: $getOwnPropertyNames, isObject: isObject, isPrivateName: isPrivateName, isSymbolString: isSymbolString, keys: $keys, setupGlobals: setupGlobals, toObject: toObject, toProperty: toProperty, typeof: typeOf }; })(window); (function() { 'use strict'; var path; function relativeRequire(callerPath, requiredPath) { path = path || typeof require !== 'undefined' && require('path'); function isDirectory(path) { return path.slice(-1) === '/'; } function isAbsolute(path) { return path[0] === '/'; } function isRelative(path) { return path[0] === '.'; } if (isDirectory(requiredPath) || isAbsolute(requiredPath)) return; return isRelative(requiredPath) ? require(path.resolve(path.dirname(callerPath), requiredPath)) : require(requiredPath); } $traceurRuntime.require = relativeRequire; })(); (function() { 'use strict'; function spread() { var rv = [], j = 0, iterResult; for (var i = 0; i < arguments.length; i++) { var valueToSpread = $traceurRuntime.checkObjectCoercible(arguments[i]); if (typeof valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)] !== 'function') { throw new TypeError('Cannot spread non-iterable object.'); } var iter = valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)](); while (!(iterResult = iter.next()).done) { rv[j++] = iterResult.value; } } return rv; } $traceurRuntime.spread = spread; })(); (function() { 'use strict'; var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor; var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames; var $getPrototypeOf = Object.getPrototypeOf; var $__0 = Object, getOwnPropertyNames = $__0.getOwnPropertyNames, getOwnPropertySymbols = $__0.getOwnPropertySymbols; function superDescriptor(homeObject, name) { var proto = $getPrototypeOf(homeObject); do { var result = $getOwnPropertyDescriptor(proto, name); if (result) return result; proto = $getPrototypeOf(proto); } while (proto); return undefined; } function superConstructor(ctor) { return ctor.__proto__; } function superCall(self, homeObject, name, args) { return superGet(self, homeObject, name).apply(self, args); } function superGet(self, homeObject, name) { var descriptor = superDescriptor(homeObject, name); if (descriptor) { if (!descriptor.get) return descriptor.value; return descriptor.get.call(self); } return undefined; } function superSet(self, homeObject, name, value) { var descriptor = superDescriptor(homeObject, name); if (descriptor && descriptor.set) { descriptor.set.call(self, value); return value; } throw $TypeError(("super has no setter '" + name + "'.")); } function getDescriptors(object) { var descriptors = {}; var names = getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; descriptors[name] = $getOwnPropertyDescriptor(object, name); } var symbols = getOwnPropertySymbols(object); for (var i = 0; i < symbols.length; i++) { var symbol = symbols[i]; descriptors[$traceurRuntime.toProperty(symbol)] = $getOwnPropertyDescriptor(object, $traceurRuntime.toProperty(symbol)); } return descriptors; } function createClass(ctor, object, staticObject, superClass) { $defineProperty(object, 'constructor', { value: ctor, configurable: true, enumerable: false, writable: true }); if (arguments.length > 3) { if (typeof superClass === 'function') ctor.__proto__ = superClass; ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object)); } else { ctor.prototype = object; } $defineProperty(ctor, 'prototype', { configurable: false, writable: false }); return $defineProperties(ctor, getDescriptors(staticObject)); } function getProtoParent(superClass) { if (typeof superClass === 'function') { var prototype = superClass.prototype; if ($Object(prototype) === prototype || prototype === null) return superClass.prototype; throw new $TypeError('super prototype must be an Object or null'); } if (superClass === null) return null; throw new $TypeError(("Super expression must either be null or a function, not " + typeof superClass + ".")); } function defaultSuperCall(self, homeObject, args) { if ($getPrototypeOf(homeObject) !== null) superCall(self, homeObject, 'constructor', args); } $traceurRuntime.createClass = createClass; $traceurRuntime.defaultSuperCall = defaultSuperCall; $traceurRuntime.superCall = superCall; $traceurRuntime.superConstructor = superConstructor; $traceurRuntime.superGet = superGet; $traceurRuntime.superSet = superSet; })(); //# },{"path":undefined}],88:[function(require,module,exports){ "use strict"; if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], 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; }; }()); } //# },{}],89:[function(require,module,exports){ "use strict"; if (typeof WeakMap === 'undefined') { (function() { var defineProperty = Object.defineProperty; try { var properDefineProperty = true; defineProperty(function() {}, 'foo', {}); } catch (e) { properDefineProperty = false; } var counter = +(new Date) % 1e9; var WeakMap = function() { this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__'); if (!properDefineProperty) { this._wmCache = []; } }; if (properDefineProperty) { WeakMap.prototype = { set: function(key, value) { var entry = key[this.name]; if (entry && entry[0] === key) entry[1] = value; else defineProperty(key, this.name, { value: [key, value], writable: true }); }, get: function(key) { var entry; return (entry = key[this.name]) && entry[0] === key ? entry[1] : undefined; }, has: function(key) { this.get(key) ? true : false; }, 'delete': function(key) { this.set(key, undefined); } }; } else { WeakMap.prototype = { set: function(key, value) { if (typeof key == 'undefined' || typeof value == 'undefined') return; for (var i = 0, len = this._wmCache.length; i < len; i++) { if (this._wmCache[i].key == key) { this._wmCache[i].value = value; return; } } this._wmCache.push({ key: key, value: value }); }, get: function(key) { if (typeof key == 'undefined') return; for (var i = 0, len = this._wmCache.length; i < len; i++) { if (this._wmCache[i].key == key) { return this._wmCache[i].value; } } return; }, has: function(key) { this.get(key) ? true : false; }, 'delete': function(key) { if (typeof key == 'undefined') return; for (var i = 0, len = this._wmCache.length; i < len; i++) { if (this._wmCache[i].key == key) { Array.prototype.slice.call(this._wmCache, i, 1); } } } }; } window.WeakMap = WeakMap; })(); } //# },{}],90:[function(require,module,exports){ "use strict"; Object.defineProperties(exports, { TableView: {get: function() { return TableView; }}, __esModule: {value: true} }); var $__dom_46_js__, $__helpers_46_js__, $__eventManager_46_js__, $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__, $__3rdparty_47_walkontable_47_src_47_selection_46_js__, $__3rdparty_47_walkontable_47_src_47_core_46_js__; var dom = ($__dom_46_js__ = require("./dom.js"), $__dom_46_js__ && $__dom_46_js__.__esModule && $__dom_46_js__ || {default: $__dom_46_js__}); var helper = ($__helpers_46_js__ = require("./helpers.js"), $__helpers_46_js__ && $__helpers_46_js__.__esModule && $__helpers_46_js__ || {default: $__helpers_46_js__}); var eventManagerObject = ($__eventManager_46_js__ = require("./eventManager.js"), $__eventManager_46_js__ && $__eventManager_46_js__.__esModule && $__eventManager_46_js__ || {default: $__eventManager_46_js__}).eventManager; var WalkontableCellCoords = ($__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ = require("./3rdparty/walkontable/src/cellCoords.js"), $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ && $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__.__esModule && $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__ || {default: $__3rdparty_47_walkontable_47_src_47_cellCoords_46_js__}).WalkontableCellCoords; var WalkontableSelection = ($__3rdparty_47_walkontable_47_src_47_selection_46_js__ = require("./3rdparty/walkontable/src/selection.js"), $__3rdparty_47_walkontable_47_src_47_selection_46_js__ && $__3rdparty_47_walkontable_47_src_47_selection_46_js__.__esModule && $__3rdparty_47_walkontable_47_src_47_selection_46_js__ || {default: $__3rdparty_47_walkontable_47_src_47_selection_46_js__}).WalkontableSelection; var Walkontable = ($__3rdparty_47_walkontable_47_src_47_core_46_js__ = require("./3rdparty/walkontable/src/core.js"), $__3rdparty_47_walkontable_47_src_47_core_46_js__ && $__3rdparty_47_walkontable_47_src_47_core_46_js__.__esModule && $__3rdparty_47_walkontable_47_src_47_core_46_js__ || {default: $__3rdparty_47_walkontable_47_src_47_core_46_js__}).Walkontable; ; Handsontable.TableView = TableView; function TableView(instance) { var that = this; this.eventManager = eventManagerObject(instance); this.instance = instance; this.settings = instance.getSettings(); var originalStyle = instance.rootElement.getAttribute('style'); if (originalStyle) { instance.rootElement.setAttribute('data-originalstyle', originalStyle); } dom.addClass(instance.rootElement, 'handsontable'); var table = document.createElement('TABLE'); table.className = 'htCore'; this.THEAD = document.createElement('THEAD'); table.appendChild(this.THEAD); this.TBODY = document.createElement('TBODY'); table.appendChild(this.TBODY); instance.table = table; instance.container.insertBefore(table, instance.container.firstChild); this.eventManager.addEventListener(instance.rootElement, 'mousedown', function(event) { if (!that.isTextSelectionAllowed(event.target)) { clearTextSelection(); event.preventDefault(); window.focus(); } }); this.eventManager.addEventListener(document.documentElement, 'keyup', function(event) { if (instance.selection.isInProgress() && !event.shiftKey) { instance.selection.finish(); } }); var isMouseDown; this.isMouseDown = function() { return isMouseDown; }; this.eventManager.addEventListener(document.documentElement, 'mouseup', function(event) { if (instance.selection.isInProgress() && event.which === 1) { instance.selection.finish(); } isMouseDown = false; if (helper.isOutsideInput(document.activeElement)) { instance.unlisten(); } }); this.eventManager.addEventListener(document.documentElement, 'mousedown', function(event) { var next = event.target; if (isMouseDown) { return; } if (next !== instance.view.wt.wtTable.holder) { while (next !== document.documentElement) { if (next === null) { if (event.isTargetWebComponent) { break; } return; } if (next === instance.rootElement) { return; } next = next.parentNode; } } else { var scrollbarWidth = Handsontable.Dom.getScrollbarWidth(); if (document.elementFromPoint(event.x + scrollbarWidth, event.y) !== instance.view.wt.wtTable.holder || document.elementFromPoint(event.x, event.y + scrollbarWidth) !== instance.view.wt.wtTable.holder) { return; } } if (that.settings.outsideClickDeselects) { instance.deselectCell(); } else { instance.destroyEditor(); } }); this.eventManager.addEventListener(table, 'selectstart', function(event) { if (that.settings.fragmentSelection) { return; } event.preventDefault(); }); var clearTextSelection = function() { if (window.getSelection) { if (window.getSelection().empty) { window.getSelection().empty(); } else if (window.getSelection().removeAllRanges) { window.getSelection().removeAllRanges(); } } else if (document.selection) { document.selection.empty(); } }; var selections = [new WalkontableSelection({ className: 'current', border: { width: 2, color: '#5292F7', cornerVisible: function() { return that.settings.fillHandle && !that.isCellEdited() && !instance.selection.isMultiple(); }, multipleSelectionHandlesVisible: function() { return !that.isCellEdited() && !instance.selection.isMultiple(); } } }), new WalkontableSelection({ className: 'area', border: { width: 1, color: '#89AFF9', cornerVisible: function() { return that.settings.fillHandle && !that.isCellEdited() && instance.selection.isMultiple(); }, multipleSelectionHandlesVisible: function() { return !that.isCellEdited() && instance.selection.isMultiple(); } } }), new WalkontableSelection({ className: 'highlight', highlightRowClassName: that.settings.currentRowClassName, highlightColumnClassName: that.settings.currentColClassName }), new WalkontableSelection({ className: 'fill', border: { width: 1, color: 'red' } })]; selections.current = selections[0]; selections.area = selections[1]; selections.highlight = selections[2]; selections.fill = selections[3]; var walkontableConfig = { debug: function() { return that.settings.debug; }, table: table, stretchH: this.settings.stretchH, data: instance.getDataAtCell, totalRows: instance.countRows, totalColumns: instance.countCols, fixedColumnsLeft: function() { return that.settings.fixedColumnsLeft; }, fixedRowsTop: function() { return that.settings.fixedRowsTop; }, renderAllRows: that.settings.renderAllRows, rowHeaders: function() { var arr = []; if (instance.hasRowHeaders()) { arr.push(function(index, TH) { that.appendRowHeader(index, TH); }); } Handsontable.hooks.run(instance, 'afterGetRowHeaderRenderers', arr); return arr; }, columnHeaders: function() { var arr = []; if (instance.hasColHeaders()) { arr.push(function(index, TH) { that.appendColHeader(index, TH); }); } Handsontable.hooks.run(instance, 'afterGetColumnHeaderRenderers', arr); return arr; }, columnWidth: instance.getColWidth, rowHeight: instance.getRowHeight, cellRenderer: function(row, col, TD) { var prop = that.instance.colToProp(col), cellProperties = that.instance.getCellMeta(row, col), renderer = that.instance.getCellRenderer(cellProperties); var value = that.instance.getDataAtRowProp(row, prop); renderer(that.instance, TD, row, col, prop, value, cellProperties); Handsontable.hooks.run(that.instance, 'afterRenderer', TD, row, col, prop, value, cellProperties); }, selections: selections, hideBorderOnMouseDownOver: function() { return that.settings.fragmentSelection; }, onCellMouseDown: function(event, coords, TD, wt) { instance.listen(); that.activeWt = wt; isMouseDown = true; dom.enableImmediatePropagation(event); Handsontable.hooks.run(instance, 'beforeOnCellMouseDown', event, coords, TD); if (!event.isImmediatePropagationStopped()) { if (event.button === 2 && instance.selection.inInSelection(coords)) {} else if (event.shiftKey) { if (coords.row >= 0 && coords.col >= 0) { instance.selection.setRangeEnd(coords); } } else { if ((coords.row < 0 || coords.col < 0) && (coords.row >= 0 || coords.col >= 0)) { if (coords.row < 0) { instance.selectCell(0, coords.col, instance.countRows() - 1, coords.col); instance.selection.setSelectedHeaders(false, true); } if (coords.col < 0) { instance.selectCell(coords.row, 0, coords.row, instance.countCols() - 1); instance.selection.setSelectedHeaders(true, false); } } else { coords.row = coords.row < 0 ? 0 : coords.row; coords.col = coords.col < 0 ? 0 : coords.col; instance.selection.setRangeStart(coords); } } Handsontable.hooks.run(instance, 'afterOnCellMouseDown', event, coords, TD); that.activeWt = that.wt; } }, onCellMouseOver: function(event, coords, TD, wt) { that.activeWt = wt; if (coords.row >= 0 && coords.col >= 0) { if (isMouseDown) { instance.selection.setRangeEnd(coords); } } else { if (isMouseDown) { if (coords.row < 0) { instance.selection.setRangeEnd(new WalkontableCellCoords(instance.countRows() - 1, coords.col)); instance.selection.setSelectedHeaders(false, true); } if (coords.col < 0) { instance.selection.setRangeEnd(new WalkontableCellCoords(coords.row, instance.countCols() - 1)); instance.selection.setSelectedHeaders(true, false); } } } Handsontable.hooks.run(instance, 'afterOnCellMouseOver', event, coords, TD); that.activeWt = that.wt; }, onCellCornerMouseDown: function(event) { event.preventDefault(); Handsontable.hooks.run(instance, 'afterOnCellCornerMouseDown', event); }, beforeDraw: function(force) { that.beforeRender(force); }, onDraw: function(force) { that.onDraw(force); }, onScrollVertically: function() { instance.runHooks('afterScrollVertically'); }, onScrollHorizontally: function() { instance.runHooks('afterScrollHorizontally'); }, onBeforeDrawBorders: function(corners, borderClassName) { instance.runHooks('beforeDrawBorders', corners, borderClassName); }, onBeforeTouchScroll: function() { instance.runHooks('beforeTouchScroll'); }, onAfterMomentumScroll: function() { instance.runHooks('afterMomentumScroll'); }, viewportRowCalculatorOverride: function(calc) { if (that.settings.viewportRowRenderingOffset) { calc.startRow = Math.max(calc.startRow - that.settings.viewportRowRenderingOffset, 0); calc.endRow = Math.min(calc.endRow + that.settings.viewportRowRenderingOffset, instance.countRows() - 1); } instance.runHooks('afterViewportRowCalculatorOverride', calc); }, viewportColumnCalculatorOverride: function(calc) { if (that.settings.viewportColumnRenderingOffset) { calc.startColumn = Math.max(calc.startColumn - that.settings.viewportColumnRenderingOffset, 0); calc.endColumn = Math.min(calc.endColumn + that.settings.viewportColumnRenderingOffset, instance.countCols() - 1); } instance.runHooks('afterViewportColumnCalculatorOverride', calc); } }; Handsontable.hooks.run(instance, 'beforeInitWalkontable', walkontableConfig); this.wt = new Walkontable(walkontableConfig); this.activeWt = this.wt; this.eventManager.addEventListener(that.wt.wtTable.spreader, 'mousedown', function(event) { if (event.target === that.wt.wtTable.spreader && event.which === 3) { helper.stopPropagation(event); } }); this.eventManager.addEventListener(that.wt.wtTable.spreader, 'contextmenu', function(event) { if (event.target === that.wt.wtTable.spreader && event.which === 3) { helper.stopPropagation(event); } }); this.eventManager.addEventListener(document.documentElement, 'click', function() { if (that.settings.observeDOMVisibility) { if (that.wt.drawInterrupted) { that.instance.forceFullRender = true; that.render(); } } }); } TableView.prototype.isTextSelectionAllowed = function(el) { if (helper.isInput(el)) { return true; } if (this.settings.fragmentSelection && dom.isChildOf(el, this.TBODY)) { return true; } return false; }; TableView.prototype.isCellEdited = function() { var activeEditor = this.instance.getActiveEditor(); return activeEditor && activeEditor.isOpened(); }; TableView.prototype.beforeRender = function(force) { if (force) { Handsontable.hooks.run(this.instance, 'beforeRender', this.instance.forceFullRender); } }; TableView.prototype.onDraw = function(force) { if (force) { Handsontable.hooks.run(this.instance, 'afterRender', this.instance.forceFullRender); } }; TableView.prototype.render = function() { this.wt.draw(!this.instance.forceFullRender); this.instance.forceFullRender = false; }; TableView.prototype.getCellAtCoords = function(coords, topmost) { var td = this.wt.getCell(coords, topmost); if (td < 0) { return null; } else { return td; } }; TableView.prototype.scrollViewport = function(coords) { this.wt.scrollViewport(coords); }; TableView.prototype.appendRowHeader = function(row, TH) { var DIV = document.createElement('DIV'), SPAN = document.createElement('SPAN'); DIV.className = 'relative'; SPAN.className = 'rowHeader'; if (row > -1) { dom.fastInnerHTML(SPAN, this.instance.getRowHeader(row)); } else { dom.fastInnerText(SPAN, String.fromCharCode(160)); } DIV.appendChild(SPAN); dom.empty(TH); TH.appendChild(DIV); Handsontable.hooks.run(this.instance, 'afterGetRowHeader', row, TH); }; TableView.prototype.appendColHeader = function(col, TH) { var DIV = document.createElement('DIV'), SPAN = document.createElement('SPAN'); DIV.className = 'relative'; SPAN.className = 'colHeader'; if (col > -1) { dom.fastInnerHTML(SPAN, this.instance.getColHeader(col)); } else { dom.fastInnerText(SPAN, String.fromCharCode(160)); dom.addClass(SPAN, 'cornerHeader'); } DIV.appendChild(SPAN); dom.empty(TH); TH.appendChild(DIV); Handsontable.hooks.run(this.instance, 'afterGetColHeader', col, TH); }; TableView.prototype.maximumVisibleElementWidth = function(leftOffset) { var workspaceWidth = this.wt.wtViewport.getWorkspaceWidth(); var maxWidth = workspaceWidth - leftOffset; return maxWidth > 0 ? maxWidth : 0; }; TableView.prototype.maximumVisibleElementHeight = function(topOffset) { var workspaceHeight = this.wt.wtViewport.getWorkspaceHeight(); var maxHeight = workspaceHeight - topOffset; return maxHeight > 0 ? maxHeight : 0; }; TableView.prototype.mainViewIsActive = function() { return this.wt === this.activeWt; }; TableView.prototype.destroy = function() { this.wt.destroy(); this.eventManager.clear(); }; //# },{"./3rdparty/walkontable/src/cellCoords.js":8,"./3rdparty/walkontable/src/core.js":12,"./3rdparty/walkontable/src/selection.js":20,"./dom.js":34,"./eventManager.js":48,"./helpers.js":49}],91:[function(require,module,exports){ "use strict"; var process = function(value, callback) { var originalVal = value; var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null; return function(source) { var found = false; for (var s = 0, slen = source.length; s < slen; s++) { if (originalVal === source[s]) { found = true; break; } else if (lowercaseVal === source[s].toLowerCase()) { found = true; break; } } callback(found); }; }; Handsontable.AutocompleteValidator = function(value, callback) { if (this.strict && this.source) { if (typeof this.source === 'function') { this.source(value, process(value, callback)); } else { process(value, callback)(this.source); } } else { callback(true); } }; //# },{}],92:[function(require,module,exports){ "use strict"; var $__moment__; var moment = ($__moment__ = require("moment"), $__moment__ && $__moment__.__esModule && $__moment__ || {default: $__moment__}).default; Handsontable.DateValidator = function(value, callback) { var correctedValue = null, valid = true, dateEditor = Handsontable.editors.getEditor('date', this.instance); if (value === null) { value = ''; } var isValidDate = moment(new Date(value)).isValid(), isValidFormat = moment(value, this.dateFormat || dateEditor.defaultDateFormat, true).isValid(); if (!isValidDate) { valid = false; } if (!isValidDate && isValidFormat) { valid = true; } if (isValidDate && !isValidFormat) { if (this.correctFormat === true) { correctedValue = correctFormat(value, this.dateFormat); this.instance.setDataAtCell(this.row, this.col, correctedValue, 'dateValidator'); valid = true; } else { valid = false; } } callback(valid); }; var correctFormat = function(value, dateFormat) { value = moment(new Date(value)).format(dateFormat); return value; }; //# },{"moment":"moment"}],93:[function(require,module,exports){ "use strict"; Handsontable.NumericValidator = function(value, callback) { if (value === null) { value = ''; } callback(/^-?\d*(\.|\,)?\d*$/.test(value)); }; //# },{}],"moment":[function(require,module,exports){ //! moment.js //! version : 2.10.2 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.moment = factory() }(this, function () { 'use strict'; var hookCallback; function utils_hooks__hooks () { return hookCallback.apply(null, arguments); } // This is done to register the method called with moment() // without creating circular dependencies. function setHookCallback (callback) { hookCallback = callback; } function defaultParsingFlags() { // We need to deep clone this object. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso : false }; } function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } function hasOwnProp(a, b) { return Object.prototype.hasOwnProperty.call(a, b); } function extend(a, b) { for (var i in b) { if (hasOwnProp(b, i)) { a[i] = b[i]; } } if (hasOwnProp(b, 'toString')) { a.toString = b.toString; } if (hasOwnProp(b, 'valueOf')) { a.valueOf = b.valueOf; } return a; } function create_utc__createUTC (input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, true).utc(); } function valid__isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0 && m._pf.bigHour === undefined; } } return m._isValid; } function valid__createInvalid (flags) { var m = create_utc__createUTC(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; } var momentProperties = utils_hooks__hooks.momentProperties = []; function copyConfig(to, from) { var i, prop, val; if (typeof from._isAMomentObject !== 'undefined') { to._isAMomentObject = from._isAMomentObject; } if (typeof from._i !== 'undefined') { to._i = from._i; } if (typeof from._f !== 'undefined') { to._f = from._f; } if (typeof from._l !== 'undefined') { to._l = from._l; } if (typeof from._strict !== 'undefined') { to._strict = from._strict; } if (typeof from._tzm !== 'undefined') { to._tzm = from._tzm; } if (typeof from._isUTC !== 'undefined') { to._isUTC = from._isUTC; } if (typeof from._offset !== 'undefined') { to._offset = from._offset; } if (typeof from._pf !== 'undefined') { to._pf = from._pf; } if (typeof from._locale !== 'undefined') { to._locale = from._locale; } if (momentProperties.length > 0) { for (i in momentProperties) { prop = momentProperties[i]; val = from[prop]; if (typeof val !== 'undefined') { to[prop] = val; } } } return to; } var updateInProgress = false; // Moment prototype object function Moment(config) { copyConfig(this, config); this._d = new Date(+config._d); // Prevent infinite loop in case updateOffset creates new moment // objects. if (updateInProgress === false) { updateInProgress = true; utils_hooks__hooks.updateOffset(this); updateInProgress = false; } } function isMoment (obj) { return obj instanceof Moment || (obj != null && hasOwnProp(obj, '_isAMomentObject')); } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function Locale() { } var locales = {}; var globalLocale; function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return null; } function loadLocale(name) { var oldLocale = null; // TODO: Find a better way to register and load all the locales in Node if (!locales[name] && typeof module !== 'undefined' && module && module.exports) { try { oldLocale = globalLocale._abbr; require('./locale/' + name); // because defineLocale currently also sets the global locale, we // want to undo that for lazy loaded locales locale_locales__getSetGlobalLocale(oldLocale); } catch (e) { } } return locales[name]; } // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. function locale_locales__getSetGlobalLocale (key, values) { var data; if (key) { if (typeof values === 'undefined') { data = locale_locales__getLocale(key); } else { data = defineLocale(key, values); } if (data) { // moment.duration._locale = moment._locale = data; globalLocale = data; } } return globalLocale._abbr; } function defineLocale (name, values) { if (values !== null) { values.abbr = name; if (!locales[name]) { locales[name] = new Locale(); } locales[name].set(values); // backwards compat for now: also set the locale locale_locales__getSetGlobalLocale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } } // returns locale data function locale_locales__getLocale (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return globalLocale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); } var aliases = {}; function addUnitAlias (unit, shorthand) { var lowerCase = unit.toLowerCase(); aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; } function normalizeUnits(units) { return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeGetSet (unit, keepTime) { return function (value) { if (value != null) { get_set__set(this, unit, value); utils_hooks__hooks.updateOffset(this, keepTime); return this; } else { return get_set__get(this, unit); } }; } function get_set__get (mom, unit) { return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); } function get_set__set (mom, unit, value) { return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } // MOMENTS function getSet (units, value) { var unit; if (typeof units === 'object') { for (unit in units) { this.set(unit, units[unit]); } } else { units = normalizeUnits(units); if (typeof this[units] === 'function') { return this[units](value); } } return this; } function zeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } var formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g; var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; var formatFunctions = {}; var formatTokenFunctions = {}; // token: 'M' // padded: ['MM', 2] // ordinal: 'Mo' // callback: function () { this.month() + 1 } function addFormatToken (token, padded, ordinal, callback) { var func = callback; if (typeof callback === 'string') { func = function () { return this[callback](); }; } if (token) { formatTokenFunctions[token] = func; } if (padded) { formatTokenFunctions[padded[0]] = function () { return zeroFill(func.apply(this, arguments), padded[1], padded[2]); }; } if (ordinal) { formatTokenFunctions[ordinal] = function () { return this.localeData().ordinal(func.apply(this, arguments), token); }; } } function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ''; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } var match1 = /\d/; // 0 - 9 var match2 = /\d\d/; // 00 - 99 var match3 = /\d{3}/; // 000 - 999 var match4 = /\d{4}/; // 0000 - 9999 var match6 = /[+-]?\d{6}/; // -999999 - 999999 var match1to2 = /\d\d?/; // 0 - 99 var match1to3 = /\d{1,3}/; // 0 - 999 var match1to4 = /\d{1,4}/; // 0 - 9999 var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 var matchUnsigned = /\d+/; // 0 - inf var matchSigned = /[+-]?\d+/; // -inf - inf var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 // any word (or two) characters or numbers including two/three word month in arabic. var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i; var regexes = {}; function addRegexToken (token, regex, strictRegex) { regexes[token] = typeof regex === 'function' ? regex : function (isStrict) { return (isStrict && strictRegex) ? strictRegex : regex; }; } function getParseRegexForToken (token, config) { if (!hasOwnProp(regexes, token)) { return new RegExp(unescapeFormat(token)); } return regexes[token](config._strict, config._locale); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function unescapeFormat(s) { return s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } var tokens = {}; function addParseToken (token, callback) { var i, func = callback; if (typeof token === 'string') { token = [token]; } if (typeof callback === 'number') { func = function (input, array) { array[callback] = toInt(input); }; } for (i = 0; i < token.length; i++) { tokens[token[i]] = func; } } function addWeekParseToken (token, callback) { addParseToken(token, function (input, array, config, token) { config._w = config._w || {}; callback(input, config._w, config, token); }); } function addTimeToArrayFromToken(token, input, config) { if (input != null && hasOwnProp(tokens, token)) { tokens[token](input, config._a, config, token); } } var YEAR = 0; var MONTH = 1; var DATE = 2; var HOUR = 3; var MINUTE = 4; var SECOND = 5; var MILLISECOND = 6; function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } // FORMATTING addFormatToken('M', ['MM', 2], 'Mo', function () { return this.month() + 1; }); addFormatToken('MMM', 0, 0, function (format) { return this.localeData().monthsShort(this, format); }); addFormatToken('MMMM', 0, 0, function (format) { return this.localeData().months(this, format); }); // ALIASES addUnitAlias('month', 'M'); // PARSING addRegexToken('M', match1to2); addRegexToken('MM', match1to2, match2); addRegexToken('MMM', matchWord); addRegexToken('MMMM', matchWord); addParseToken(['M', 'MM'], function (input, array) { array[MONTH] = toInt(input) - 1; }); addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { var month = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid. if (month != null) { array[MONTH] = month; } else { config._pf.invalidMonth = input; } }); // LOCALES var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); function localeMonths (m) { return this._months[m.month()]; } var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); function localeMonthsShort (m) { return this._monthsShort[m.month()]; } function localeMonthsParse (monthName, format, strict) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = create_utc__createUTC([2000, i]); if (strict && !this._longMonthsParse[i]) { this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); } if (!strict && !this._monthsParse[i]) { regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { return i; } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { return i; } else if (!strict && this._monthsParse[i].test(monthName)) { return i; } } } // MOMENTS function setMonth (mom, value) { var dayOfMonth; // TODO: Move this out of here! if (typeof value === 'string') { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function getSetMonth (value) { if (value != null) { setMonth(this, value); utils_hooks__hooks.updateOffset(this, true); return this; } else { return get_set__get(this, 'Month'); } } function getDaysInMonth () { return daysInMonth(this.year(), this.month()); } function checkOverflow (m) { var overflow; var a = m._a; if (a && m._pf.overflow === -2) { overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } return m; } function warn(msg) { if (utils_hooks__hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (firstTime) { warn(msg); firstTime = false; } return fn.apply(this, arguments); }, fn); } var deprecations = {}; function deprecateSimple(name, msg) { if (!deprecations[name]) { warn(msg); deprecations[name] = true; } } utils_hooks__hooks.suppressDeprecationWarnings = false; var from_string__isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; var isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ]; // iso time formats and regexes var isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ]; var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; // date from iso format function configFromISO(config) { var i, l, string = config._i, match = from_string__isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be 'T' or undefined config._f = isoDates[i][0] + (match[6] || ' '); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(matchOffset)) { config._f += 'Z'; } configFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function configFromString(config) { var matched = aspNetJsonRegex.exec(config._i); if (matched !== null) { config._d = new Date(+matched[1]); return; } configFromISO(config); if (config._isValid === false) { delete config._isValid; utils_hooks__hooks.createFromInputFallback(config); } } utils_hooks__hooks.createFromInputFallback = deprecate( 'moment construction falls back to js Date. This is ' + 'discouraged and will be removed in upcoming major ' + 'release. Please refer to ' + 'https://github.com/moment/moment/issues/1407 for more info.', function (config) { config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); } ); function createDate (y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function createUTCDate (y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } addFormatToken(0, ['YY', 2], 0, function () { return this.year() % 100; }); addFormatToken(0, ['YYYY', 4], 0, 'year'); addFormatToken(0, ['YYYYY', 5], 0, 'year'); addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); // ALIASES addUnitAlias('year', 'y'); // PARSING addRegexToken('Y', matchSigned); addRegexToken('YY', match1to2, match2); addRegexToken('YYYY', match1to4, match4); addRegexToken('YYYYY', match1to6, match6); addRegexToken('YYYYYY', match1to6, match6); addParseToken(['YYYY', 'YYYYY', 'YYYYYY'], YEAR); addParseToken('YY', function (input, array) { array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input); }); // HELPERS function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } // HOOKS utils_hooks__hooks.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; // MOMENTS var getSetYear = makeGetSet('FullYear', false); function getIsLeapYear () { return isLeapYear(this.year()); } addFormatToken('w', ['ww', 2], 'wo', 'week'); addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); // ALIASES addUnitAlias('week', 'w'); addUnitAlias('isoWeek', 'W'); // PARSING addRegexToken('w', match1to2); addRegexToken('ww', match1to2, match2); addRegexToken('W', match1to2); addRegexToken('WW', match1to2, match2); addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { week[token.substr(0, 1)] = toInt(input); }); // HELPERS // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = local__createLocal(mom).add(daysToDayOfWeek, 'd'); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } // LOCALES function localeWeek (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; } var defaultLocaleWeek = { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }; function localeFirstDayOfWeek () { return this._week.dow; } function localeFirstDayOfYear () { return this._week.doy; } // MOMENTS function getSetWeek (input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); } function getSetISOWeek (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); } addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); // ALIASES addUnitAlias('dayOfYear', 'DDD'); // PARSING addRegexToken('DDD', match1to3); addRegexToken('DDDD', match3); addParseToken(['DDD', 'DDDD'], function (input, array, config) { config._dayOfYear = toInt(input); }); // HELPERS //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = createUTCDate(year, 0, 1).getUTCDay(); var daysToAdd; var dayOfYear; d = d === 0 ? 7 : d; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year : dayOfYear > 0 ? year : year - 1, dayOfYear : dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } // MOMENTS function getSetDayOfYear (input) { var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); } // Pick the first defined of two or three arguments. function defaults(a, b, c) { if (a != null) { return a; } if (b != null) { return b; } return c; } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()]; } return [now.getFullYear(), now.getMonth(), now.getDate()]; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function configFromArray (config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = createUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // Check for 24:00:00.000 if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) { config._nextDay = true; config._a[HOUR] = 0; } config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); // Apply timezone offset from input. The actual utcOffset can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); } if (config._nextDay) { config._a[HOUR] = 24; } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year); week = defaults(w.W, 1); weekday = defaults(w.E, 1); } else { dow = config._locale._week.dow; doy = config._locale._week.doy; weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year); week = defaults(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < dow) { ++week; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; } else { // default to begining of week weekday = dow; } } temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } utils_hooks__hooks.ISO_8601 = function () {}; // date from string and format string function configFromStringAndFormat(config) { // TODO: Move this to another part of the creation flow to prevent circular deps if (config._f === utils_hooks__hooks.ISO_8601) { configFromISO(config); return; } config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // clear _12h flag if hour is <= 12 if (config._pf.bigHour === true && config._a[HOUR] <= 12) { config._pf.bigHour = undefined; } // handle meridiem config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); configFromArray(config); checkOverflow(config); } function meridiemFixWrap (locale, hour, meridiem) { var isPm; if (meridiem == null) { // nothing to do return hour; } if (locale.meridiemHour != null) { return locale.meridiemHour(hour, meridiem); } else if (locale.isPM != null) { // Fallback isPm = locale.isPM(meridiem); if (isPm && hour < 12) { hour += 12; } if (!isPm && hour === 12) { hour = 0; } return hour; } else { // this is not supposed to happen return hour; } } function configFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; configFromStringAndFormat(tempConfig); if (!valid__isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } function configFromObject(config) { if (config._d) { return; } var i = normalizeObjectUnits(config._i); config._a = [i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond]; configFromArray(config); } function createFromConfig (config) { var input = config._i, format = config._f, res; config._locale = config._locale || locale_locales__getLocale(config._l); if (input === null || (format === undefined && input === '')) { return valid__createInvalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (isMoment(input)) { return new Moment(checkOverflow(input)); } else if (isArray(format)) { configFromStringAndArray(config); } else if (format) { configFromStringAndFormat(config); } else { configFromInput(config); } res = new Moment(checkOverflow(config)); if (res._nextDay) { // Adding is smart enough around DST res.add(1, 'd'); res._nextDay = undefined; } return res; } function configFromInput(config) { var input = config._i; if (input === undefined) { config._d = new Date(); } else if (isDate(input)) { config._d = new Date(+input); } else if (typeof input === 'string') { configFromString(config); } else if (isArray(input)) { config._a = map(input.slice(0), function (obj) { return parseInt(obj, 10); }); configFromArray(config); } else if (typeof(input) === 'object') { configFromObject(config); } else if (typeof(input) === 'number') { // from milliseconds config._d = new Date(input); } else { utils_hooks__hooks.createFromInputFallback(config); } } function createLocalOrUTC (input, format, locale, strict, isUTC) { var c = {}; if (typeof(locale) === 'boolean') { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c._isAMomentObject = true; c._useUTC = c._isUTC = isUTC; c._l = locale; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return createFromConfig(c); } function local__createLocal (input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, false); } var prototypeMin = deprecate( 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', function () { var other = local__createLocal.apply(null, arguments); return other < this ? this : other; } ); var prototypeMax = deprecate( 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', function () { var other = local__createLocal.apply(null, arguments); return other > this ? this : other; } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return local__createLocal(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (moments[i][fn](res)) { res = moments[i]; } } return res; } // TODO: Use [].sort instead? function min () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); } function max () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); } function Duration (duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = locale_locales__getLocale(); this._bubble(); } function isDuration (obj) { return obj instanceof Duration; } function offset (token, separator) { addFormatToken(token, 0, 0, function () { var offset = this.utcOffset(); var sign = '+'; if (offset < 0) { offset = -offset; sign = '-'; } return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); }); } offset('Z', ':'); offset('ZZ', ''); // PARSING addRegexToken('Z', matchOffset); addRegexToken('ZZ', matchOffset); addParseToken(['Z', 'ZZ'], function (input, array, config) { config._useUTC = true; config._tzm = offsetFromString(input); }); // HELPERS // timezone chunker // '+10:00' > ['10', '00'] // '-1530' > ['-15', '30'] var chunkOffset = /([\+\-]|\d\d)/gi; function offsetFromString(string) { var matches = ((string || '').match(matchOffset) || []); var chunk = matches[matches.length - 1] || []; var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; var minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? minutes : -minutes; } // Return a moment from input, that is local/utc/zone equivalent to model. function cloneWithOffset(input, model) { var res, diff; if (model._isUTC) { res = model.clone(); diff = (isMoment(input) || isDate(input) ? +input : +local__createLocal(input)) - (+res); // Use low-level api, because this fn is low-level api. res._d.setTime(+res._d + diff); utils_hooks__hooks.updateOffset(res, false); return res; } else { return local__createLocal(input).local(); } return model._isUTC ? local__createLocal(input).zone(model._offset || 0) : local__createLocal(input).local(); } function getDateOffset (m) { // On Firefox.24 Date#getTimezoneOffset returns a floating point. // https://github.com/moment/moment/pull/1871 return -Math.round(m._d.getTimezoneOffset() / 15) * 15; } // HOOKS // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. utils_hooks__hooks.updateOffset = function () {}; // MOMENTS // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. function getSetOffset (input, keepLocalTime) { var offset = this._offset || 0, localAdjust; if (input != null) { if (typeof input === 'string') { input = offsetFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = getDateOffset(this); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.add(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; utils_hooks__hooks.updateOffset(this, true); this._changeInProgress = null; } } return this; } else { return this._isUTC ? offset : getDateOffset(this); } } function getSetZone (input, keepLocalTime) { if (input != null) { if (typeof input !== 'string') { input = -input; } this.utcOffset(input, keepLocalTime); return this; } else { return -this.utcOffset(); } } function setOffsetToUTC (keepLocalTime) { return this.utcOffset(0, keepLocalTime); } function setOffsetToLocal (keepLocalTime) { if (this._isUTC) { this.utcOffset(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.subtract(getDateOffset(this), 'm'); } } return this; } function setOffsetToParsedOffset () { if (this._tzm) { this.utcOffset(this._tzm); } else if (typeof this._i === 'string') { this.utcOffset(offsetFromString(this._i)); } return this; } function hasAlignedHourOffset (input) { if (!input) { input = 0; } else { input = local__createLocal(input).utcOffset(); } return (this.utcOffset() - input) % 60 === 0; } function isDaylightSavingTime () { return ( this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset() ); } function isDaylightSavingTimeShifted () { if (this._a) { var other = this._isUTC ? create_utc__createUTC(this._a) : local__createLocal(this._a); return this.isValid() && compareArrays(this._a, other.toArray()) > 0; } return false; } function isLocal () { return !this._isUTC; } function isUtcOffset () { return this._isUTC; } function isUtc () { return this._isUTC && this._offset === 0; } var aspNetRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/; // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere var create__isoRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/; function create__createDuration (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, diffRes; if (isDuration(input)) { duration = { ms : input._milliseconds, d : input._days, M : input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y : 0, d : toInt(match[DATE]) * sign, h : toInt(match[HOUR]) * sign, m : toInt(match[MINUTE]) * sign, s : toInt(match[SECOND]) * sign, ms : toInt(match[MILLISECOND]) * sign }; } else if (!!(match = create__isoRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y : parseIso(match[2], sign), M : parseIso(match[3], sign), d : parseIso(match[4], sign), h : parseIso(match[5], sign), m : parseIso(match[6], sign), s : parseIso(match[7], sign), w : parseIso(match[8], sign) }; } else if (duration == null) {// checks for null or undefined duration = {}; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } return ret; } create__createDuration.fn = Duration.prototype; function parseIso (inp, sign) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; other = cloneWithOffset(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).'); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = create__createDuration(val, period); add_subtract__addSubtract(this, dur, direction); return this; }; } function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months; updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } if (days) { get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding); } if (months) { setMonth(mom, get_set__get(mom, 'Month') + months * isAdding); } if (updateOffset) { utils_hooks__hooks.updateOffset(mom, days || months); } } var add_subtract__add = createAdder(1, 'add'); var add_subtract__subtract = createAdder(-1, 'subtract'); function moment_calendar__calendar (time) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're local/utc/offset or not. var now = time || local__createLocal(), sod = cloneWithOffset(now, this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.localeData().calendar(format, this, local__createLocal(now))); } function clone () { return new Moment(this); } function isAfter (input, units) { var inputMs; units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); if (units === 'millisecond') { input = isMoment(input) ? input : local__createLocal(input); return +this > +input; } else { inputMs = isMoment(input) ? +input : +local__createLocal(input); return inputMs < +this.clone().startOf(units); } } function isBefore (input, units) { var inputMs; units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); if (units === 'millisecond') { input = isMoment(input) ? input : local__createLocal(input); return +this < +input; } else { inputMs = isMoment(input) ? +input : +local__createLocal(input); return +this.clone().endOf(units) < inputMs; } } function isBetween (from, to, units) { return this.isAfter(from, units) && this.isBefore(to, units); } function isSame (input, units) { var inputMs; units = normalizeUnits(units || 'millisecond'); if (units === 'millisecond') { input = isMoment(input) ? input : local__createLocal(input); return +this === +input; } else { inputMs = +local__createLocal(input); return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units)); } } function absFloor (number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } function diff (input, units, asFloat) { var that = cloneWithOffset(input, this), zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4, delta, output; units = normalizeUnits(units); if (units === 'year' || units === 'month' || units === 'quarter') { output = monthDiff(this, that); if (units === 'quarter') { output = output / 3; } else if (units === 'year') { output = output / 12; } } else { delta = this - that; output = units === 'second' ? delta / 1e3 : // 1000 units === 'minute' ? delta / 6e4 : // 1000 * 60 units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60 units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst delta; } return asFloat ? output : absFloor(output); } function monthDiff (a, b) { // difference in months var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), // b is in (anchor - 1 month, anchor + 1 month) anchor = a.clone().add(wholeMonthDiff, 'months'), anchor2, adjust; if (b - anchor < 0) { anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor - anchor2); } else { anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor2 - anchor); } return -(wholeMonthDiff + adjust); } utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; function toString () { return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } function moment_format__toISOString () { var m = this.clone().utc(); if (0 < m.year() && m.year() <= 9999) { if ('function' === typeof Date.prototype.toISOString) { // native implementation is ~50x faster, use it when we can return this.toDate().toISOString(); } else { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } } function format (inputString) { var output = formatMoment(this, inputString || utils_hooks__hooks.defaultFormat); return this.localeData().postformat(output); } function from (time, withoutSuffix) { return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); } function fromNow (withoutSuffix) { return this.from(local__createLocal(), withoutSuffix); } function locale (key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = locale_locales__getLocale(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } } var lang = deprecate( 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) { if (key === undefined) { return this.localeData(); } else { return this.locale(key); } } ); function localeData () { return this._locale; } function startOf (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); } // weeks are a special case if (units === 'week') { this.weekday(0); } if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; } function endOf (units) { units = normalizeUnits(units); if (units === undefined || units === 'millisecond') { return this; } return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); } function to_type__valueOf () { return +this._d - ((this._offset || 0) * 60000); } function unix () { return Math.floor(+this / 1000); } function toDate () { return this._offset ? new Date(+this) : this._d; } function toArray () { var m = this; return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; } function moment_valid__isValid () { return valid__isValid(this); } function parsingFlags () { return extend({}, this._pf); } function invalidAt () { return this._pf.overflow; } addFormatToken(0, ['gg', 2], 0, function () { return this.weekYear() % 100; }); addFormatToken(0, ['GG', 2], 0, function () { return this.isoWeekYear() % 100; }); function addWeekYearFormatToken (token, getter) { addFormatToken(0, [token, token.length], 0, getter); } addWeekYearFormatToken('gggg', 'weekYear'); addWeekYearFormatToken('ggggg', 'weekYear'); addWeekYearFormatToken('GGGG', 'isoWeekYear'); addWeekYearFormatToken('GGGGG', 'isoWeekYear'); // ALIASES addUnitAlias('weekYear', 'gg'); addUnitAlias('isoWeekYear', 'GG'); // PARSING addRegexToken('G', matchSigned); addRegexToken('g', matchSigned); addRegexToken('GG', match1to2, match2); addRegexToken('gg', match1to2, match2); addRegexToken('GGGG', match1to4, match4); addRegexToken('gggg', match1to4, match4); addRegexToken('GGGGG', match1to6, match6); addRegexToken('ggggg', match1to6, match6); addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { week[token.substr(0, 2)] = toInt(input); }); addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { week[token] = utils_hooks__hooks.parseTwoDigitYear(input); }); // HELPERS function weeksInYear(year, dow, doy) { return weekOfYear(local__createLocal([year, 11, 31 + dow - doy]), dow, doy).week; } // MOMENTS function getSetWeekYear (input) { var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; return input == null ? year : this.add((input - year), 'y'); } function getSetISOWeekYear (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add((input - year), 'y'); } function getISOWeeksInYear () { return weeksInYear(this.year(), 1, 4); } function getWeeksInYear () { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } addFormatToken('Q', 0, 0, 'quarter'); // ALIASES addUnitAlias('quarter', 'Q'); // PARSING addRegexToken('Q', match1); addParseToken('Q', function (input, array) { array[MONTH] = (toInt(input) - 1) * 3; }); // MOMENTS function getSetQuarter (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); } addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES addUnitAlias('date', 'D'); // PARSING addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { return isStrict ? locale._ordinalParse : locale._ordinalParseLenient; }); addParseToken(['D', 'DD'], DATE); addParseToken('Do', function (input, array) { array[DATE] = toInt(input.match(match1to2)[0], 10); }); // MOMENTS var getSetDayOfMonth = makeGetSet('Date', true); addFormatToken('d', 0, 'do', 'day'); addFormatToken('dd', 0, 0, function (format) { return this.localeData().weekdaysMin(this, format); }); addFormatToken('ddd', 0, 0, function (format) { return this.localeData().weekdaysShort(this, format); }); addFormatToken('dddd', 0, 0, function (format) { return this.localeData().weekdays(this, format); }); addFormatToken('e', 0, 0, 'weekday'); addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES addUnitAlias('day', 'd'); addUnitAlias('weekday', 'e'); addUnitAlias('isoWeekday', 'E'); // PARSING addRegexToken('d', match1to2); addRegexToken('e', match1to2); addRegexToken('E', match1to2); addRegexToken('dd', matchWord); addRegexToken('ddd', matchWord); addRegexToken('dddd', matchWord); addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config) { var weekday = config._locale.weekdaysParse(input); // if we didn't get a weekday name, mark the date as invalid if (weekday != null) { week.d = weekday; } else { config._pf.invalidWeekday = input; } }); addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { week[token] = toInt(input); }); // HELPERS function parseWeekday(input, locale) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = locale.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } // LOCALES var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); function localeWeekdays (m) { return this._weekdays[m.day()]; } var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); function localeWeekdaysShort (m) { return this._weekdaysShort[m.day()]; } var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); function localeWeekdaysMin (m) { return this._weekdaysMin[m.day()]; } function localeWeekdaysParse (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = local__createLocal([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } } // MOMENTS function getSetDayOfWeek (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } } function getSetLocaleDayOfWeek (input) { var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); } function getSetISODayOfWeek (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); } addFormatToken('H', ['HH', 2], 0, 'hour'); addFormatToken('h', ['hh', 2], 0, function () { return this.hours() % 12 || 12; }); function meridiem (token, lowercase) { addFormatToken(token, 0, 0, function () { return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); }); } meridiem('a', true); meridiem('A', false); // ALIASES addUnitAlias('hour', 'h'); // PARSING function matchMeridiem (isStrict, locale) { return locale._meridiemParse; } addRegexToken('a', matchMeridiem); addRegexToken('A', matchMeridiem); addRegexToken('H', match1to2); addRegexToken('h', match1to2); addRegexToken('HH', match1to2, match2); addRegexToken('hh', match1to2, match2); addParseToken(['H', 'HH'], HOUR); addParseToken(['a', 'A'], function (input, array, config) { config._isPm = config._locale.isPM(input); config._meridiem = input; }); addParseToken(['h', 'hh'], function (input, array, config) { array[HOUR] = toInt(input); config._pf.bigHour = true; }); // LOCALES function localeIsPM (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); } var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; function localeMeridiem (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } } // MOMENTS // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. var getSetHour = makeGetSet('Hours', true); addFormatToken('m', ['mm', 2], 0, 'minute'); // ALIASES addUnitAlias('minute', 'm'); // PARSING addRegexToken('m', match1to2); addRegexToken('mm', match1to2, match2); addParseToken(['m', 'mm'], MINUTE); // MOMENTS var getSetMinute = makeGetSet('Minutes', false); addFormatToken('s', ['ss', 2], 0, 'second'); // ALIASES addUnitAlias('second', 's'); // PARSING addRegexToken('s', match1to2); addRegexToken('ss', match1to2, match2); addParseToken(['s', 'ss'], SECOND); // MOMENTS var getSetSecond = makeGetSet('Seconds', false); addFormatToken('S', 0, 0, function () { return ~~(this.millisecond() / 100); }); addFormatToken(0, ['SS', 2], 0, function () { return ~~(this.millisecond() / 10); }); function millisecond__milliseconds (token) { addFormatToken(0, [token, 3], 0, 'millisecond'); } millisecond__milliseconds('SSS'); millisecond__milliseconds('SSSS'); // ALIASES addUnitAlias('millisecond', 'ms'); // PARSING addRegexToken('S', match1to3, match1); addRegexToken('SS', match1to3, match2); addRegexToken('SSS', match1to3, match3); addRegexToken('SSSS', matchUnsigned); addParseToken(['S', 'SS', 'SSS', 'SSSS'], function (input, array) { array[MILLISECOND] = toInt(('0.' + input) * 1000); }); // MOMENTS var getSetMillisecond = makeGetSet('Milliseconds', false); addFormatToken('z', 0, 0, 'zoneAbbr'); addFormatToken('zz', 0, 0, 'zoneName'); // MOMENTS function getZoneAbbr () { return this._isUTC ? 'UTC' : ''; } function getZoneName () { return this._isUTC ? 'Coordinated Universal Time' : ''; } var momentPrototype__proto = Moment.prototype; momentPrototype__proto.add = add_subtract__add; momentPrototype__proto.calendar = moment_calendar__calendar; momentPrototype__proto.clone = clone; momentPrototype__proto.diff = diff; momentPrototype__proto.endOf = endOf; momentPrototype__proto.format = format; momentPrototype__proto.from = from; momentPrototype__proto.fromNow = fromNow; momentPrototype__proto.get = getSet; momentPrototype__proto.invalidAt = invalidAt; momentPrototype__proto.isAfter = isAfter; momentPrototype__proto.isBefore = isBefore; momentPrototype__proto.isBetween = isBetween; momentPrototype__proto.isSame = isSame; momentPrototype__proto.isValid = moment_valid__isValid; momentPrototype__proto.lang = lang; momentPrototype__proto.locale = locale; momentPrototype__proto.localeData = localeData; momentPrototype__proto.max = prototypeMax; momentPrototype__proto.min = prototypeMin; momentPrototype__proto.parsingFlags = parsingFlags; momentPrototype__proto.set = getSet; momentPrototype__proto.startOf = startOf; momentPrototype__proto.subtract = add_subtract__subtract; momentPrototype__proto.toArray = toArray; momentPrototype__proto.toDate = toDate; momentPrototype__proto.toISOString = moment_format__toISOString; momentPrototype__proto.toJSON = moment_format__toISOString; momentPrototype__proto.toString = toString; momentPrototype__proto.unix = unix; momentPrototype__proto.valueOf = to_type__valueOf; // Year momentPrototype__proto.year = getSetYear; momentPrototype__proto.isLeapYear = getIsLeapYear; // Week Year momentPrototype__proto.weekYear = getSetWeekYear; momentPrototype__proto.isoWeekYear = getSetISOWeekYear; // Quarter momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter; // Month momentPrototype__proto.month = getSetMonth; momentPrototype__proto.daysInMonth = getDaysInMonth; // Week momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek; momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek; momentPrototype__proto.weeksInYear = getWeeksInYear; momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear; // Day momentPrototype__proto.date = getSetDayOfMonth; momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek; momentPrototype__proto.weekday = getSetLocaleDayOfWeek; momentPrototype__proto.isoWeekday = getSetISODayOfWeek; momentPrototype__proto.dayOfYear = getSetDayOfYear; // Hour momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour; // Minute momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute; // Second momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond; // Millisecond momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond; // Offset momentPrototype__proto.utcOffset = getSetOffset; momentPrototype__proto.utc = setOffsetToUTC; momentPrototype__proto.local = setOffsetToLocal; momentPrototype__proto.parseZone = setOffsetToParsedOffset; momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset; momentPrototype__proto.isDST = isDaylightSavingTime; momentPrototype__proto.isDSTShifted = isDaylightSavingTimeShifted; momentPrototype__proto.isLocal = isLocal; momentPrototype__proto.isUtcOffset = isUtcOffset; momentPrototype__proto.isUtc = isUtc; momentPrototype__proto.isUTC = isUtc; // Timezone momentPrototype__proto.zoneAbbr = getZoneAbbr; momentPrototype__proto.zoneName = getZoneName; // Deprecations momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779', getSetZone); var momentPrototype = momentPrototype__proto; function moment__createUnix (input) { return local__createLocal(input * 1000); } function moment__createInZone () { return local__createLocal.apply(null, arguments).parseZone(); } var defaultCalendar = { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }; function locale_calendar__calendar (key, mom, now) { var output = this._calendar[key]; return typeof output === 'function' ? output.call(mom, now) : output; } var defaultLongDateFormat = { LTS : 'h:mm:ss A', LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY LT', LLLL : 'dddd, MMMM D, YYYY LT' }; function longDateFormat (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; } var defaultInvalidDate = 'Invalid date'; function invalidDate () { return this._invalidDate; } var defaultOrdinal = '%d'; var defaultOrdinalParse = /\d{1,2}/; function ordinal (number) { return this._ordinal.replace('%d', number); } function preParsePostFormat (string) { return string; } var defaultRelativeTime = { future : 'in %s', past : '%s ago', s : 'a few seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }; function relative__relativeTime (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); } function pastFuture (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); } function locale_set__set (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } // Lenient ordinal parsing accepts just a number in addition to // number + (possibly) stuff coming from _ordinalParseLenient. this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + /\d{1,2}/.source); } var prototype__proto = Locale.prototype; prototype__proto._calendar = defaultCalendar; prototype__proto.calendar = locale_calendar__calendar; prototype__proto._longDateFormat = defaultLongDateFormat; prototype__proto.longDateFormat = longDateFormat; prototype__proto._invalidDate = defaultInvalidDate; prototype__proto.invalidDate = invalidDate; prototype__proto._ordinal = defaultOrdinal; prototype__proto.ordinal = ordinal; prototype__proto._ordinalParse = defaultOrdinalParse; prototype__proto.preparse = preParsePostFormat; prototype__proto.postformat = preParsePostFormat; prototype__proto._relativeTime = defaultRelativeTime; prototype__proto.relativeTime = relative__relativeTime; prototype__proto.pastFuture = pastFuture; prototype__proto.set = locale_set__set; // Month prototype__proto.months = localeMonths; prototype__proto._months = defaultLocaleMonths; prototype__proto.monthsShort = localeMonthsShort; prototype__proto._monthsShort = defaultLocaleMonthsShort; prototype__proto.monthsParse = localeMonthsParse; // Week prototype__proto.week = localeWeek; prototype__proto._week = defaultLocaleWeek; prototype__proto.firstDayOfYear = localeFirstDayOfYear; prototype__proto.firstDayOfWeek = localeFirstDayOfWeek; // Day of Week prototype__proto.weekdays = localeWeekdays; prototype__proto._weekdays = defaultLocaleWeekdays; prototype__proto.weekdaysMin = localeWeekdaysMin; prototype__proto._weekdaysMin = defaultLocaleWeekdaysMin; prototype__proto.weekdaysShort = localeWeekdaysShort; prototype__proto._weekdaysShort = defaultLocaleWeekdaysShort; prototype__proto.weekdaysParse = localeWeekdaysParse; // Hours prototype__proto.isPM = localeIsPM; prototype__proto._meridiemParse = defaultLocaleMeridiemParse; prototype__proto.meridiem = localeMeridiem; function lists__get (format, index, field, setter) { var locale = locale_locales__getLocale(); var utc = create_utc__createUTC().set(setter, index); return locale[field](utc, format); } function list (format, index, field, count, setter) { if (typeof format === 'number') { index = format; format = undefined; } format = format || ''; if (index != null) { return lists__get(format, index, field, setter); } var i; var out = []; for (i = 0; i < count; i++) { out[i] = lists__get(format, i, field, setter); } return out; } function lists__listMonths (format, index) { return list(format, index, 'months', 12, 'month'); } function lists__listMonthsShort (format, index) { return list(format, index, 'monthsShort', 12, 'month'); } function lists__listWeekdays (format, index) { return list(format, index, 'weekdays', 7, 'day'); } function lists__listWeekdaysShort (format, index) { return list(format, index, 'weekdaysShort', 7, 'day'); } function lists__listWeekdaysMin (format, index) { return list(format, index, 'weekdaysMin', 7, 'day'); } locale_locales__getSetGlobalLocale('en', { ordinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); // Side effect imports utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale); utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale); var mathAbs = Math.abs; function duration_abs__abs () { var data = this._data; this._milliseconds = mathAbs(this._milliseconds); this._days = mathAbs(this._days); this._months = mathAbs(this._months); data.milliseconds = mathAbs(data.milliseconds); data.seconds = mathAbs(data.seconds); data.minutes = mathAbs(data.minutes); data.hours = mathAbs(data.hours); data.months = mathAbs(data.months); data.years = mathAbs(data.years); return this; } function duration_add_subtract__addSubtract (duration, input, value, direction) { var other = create__createDuration(input, value); duration._milliseconds += direction * other._milliseconds; duration._days += direction * other._days; duration._months += direction * other._months; return duration._bubble(); } // supports only 2.0-style add(1, 's') or add(duration) function duration_add_subtract__add (input, value) { return duration_add_subtract__addSubtract(this, input, value, 1); } // supports only 2.0-style subtract(1, 's') or subtract(duration) function duration_add_subtract__subtract (input, value) { return duration_add_subtract__addSubtract(this, input, value, -1); } function bubble () { var milliseconds = this._milliseconds; var days = this._days; var months = this._months; var data = this._data; var seconds, minutes, hours, years = 0; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absFloor(milliseconds / 1000); data.seconds = seconds % 60; minutes = absFloor(seconds / 60); data.minutes = minutes % 60; hours = absFloor(minutes / 60); data.hours = hours % 24; days += absFloor(hours / 24); // Accurately convert days to years, assume start from year 0. years = absFloor(daysToYears(days)); days -= absFloor(yearsToDays(years)); // 30 days to a month // TODO (iskren): Use anchor date (like 1st Jan) to compute this. months += absFloor(days / 30); days %= 30; // 12 months -> 1 year years += absFloor(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; return this; } function daysToYears (days) { // 400 years have 146097 days (taking into account leap year rules) return days * 400 / 146097; } function yearsToDays (years) { // years * 365 + absFloor(years / 4) - // absFloor(years / 100) + absFloor(years / 400); return years * 146097 / 400; } function as (units) { var days; var months; var milliseconds = this._milliseconds; units = normalizeUnits(units); if (units === 'month' || units === 'year') { days = this._days + milliseconds / 864e5; months = this._months + daysToYears(days) * 12; return units === 'month' ? months : months / 12; } else { // handle milliseconds separately because of floating point math errors (issue #1867) days = this._days + Math.round(yearsToDays(this._months / 12)); switch (units) { case 'week' : return days / 7 + milliseconds / 6048e5; case 'day' : return days + milliseconds / 864e5; case 'hour' : return days * 24 + milliseconds / 36e5; case 'minute' : return days * 24 * 60 + milliseconds / 6e4; case 'second' : return days * 24 * 60 * 60 + milliseconds / 1000; // Math.floor prevents floating point math errors here case 'millisecond': return Math.floor(days * 24 * 60 * 60 * 1000) + milliseconds; default: throw new Error('Unknown unit ' + units); } } } // TODO: Use this.as('ms')? function duration_as__valueOf () { return ( this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6 ); } function makeAs (alias) { return function () { return this.as(alias); }; } var asMilliseconds = makeAs('ms'); var asSeconds = makeAs('s'); var asMinutes = makeAs('m'); var asHours = makeAs('h'); var asDays = makeAs('d'); var asWeeks = makeAs('w'); var asMonths = makeAs('M'); var asYears = makeAs('y'); function duration_get__get (units) { units = normalizeUnits(units); return this[units + 's'](); } function makeGetter(name) { return function () { return this._data[name]; }; } var duration_get__milliseconds = makeGetter('milliseconds'); var seconds = makeGetter('seconds'); var minutes = makeGetter('minutes'); var hours = makeGetter('hours'); var days = makeGetter('days'); var months = makeGetter('months'); var years = makeGetter('years'); function weeks () { return absFloor(this.days() / 7); } var round = Math.round; var thresholds = { s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month M: 11 // months to year }; // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function duration_humanize__relativeTime (posNegDuration, withoutSuffix, locale) { var duration = create__createDuration(posNegDuration).abs(); var seconds = round(duration.as('s')); var minutes = round(duration.as('m')); var hours = round(duration.as('h')); var days = round(duration.as('d')); var months = round(duration.as('M')); var years = round(duration.as('y')); var a = seconds < thresholds.s && ['s', seconds] || minutes === 1 && ['m'] || minutes < thresholds.m && ['mm', minutes] || hours === 1 && ['h'] || hours < thresholds.h && ['hh', hours] || days === 1 && ['d'] || days < thresholds.d && ['dd', days] || months === 1 && ['M'] || months < thresholds.M && ['MM', months] || years === 1 && ['y'] || ['yy', years]; a[2] = withoutSuffix; a[3] = +posNegDuration > 0; a[4] = locale; return substituteTimeAgo.apply(null, a); } // This function allows you to set a threshold for relative time strings function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) { if (thresholds[threshold] === undefined) { return false; } if (limit === undefined) { return thresholds[threshold]; } thresholds[threshold] = limit; return true; } function humanize (withSuffix) { var locale = this.localeData(); var output = duration_humanize__relativeTime(this, !withSuffix, locale); if (withSuffix) { output = locale.pastFuture(+this, output); } return locale.postformat(output); } var iso_string__abs = Math.abs; function iso_string__toISOString() { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var Y = iso_string__abs(this.years()); var M = iso_string__abs(this.months()); var D = iso_string__abs(this.days()); var h = iso_string__abs(this.hours()); var m = iso_string__abs(this.minutes()); var s = iso_string__abs(this.seconds() + this.milliseconds() / 1000); var total = this.asSeconds(); if (!total) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (total < 0 ? '-' : '') + 'P' + (Y ? Y + 'Y' : '') + (M ? M + 'M' : '') + (D ? D + 'D' : '') + ((h || m || s) ? 'T' : '') + (h ? h + 'H' : '') + (m ? m + 'M' : '') + (s ? s + 'S' : ''); } var duration_prototype__proto = Duration.prototype; duration_prototype__proto.abs = duration_abs__abs; duration_prototype__proto.add = duration_add_subtract__add; duration_prototype__proto.subtract = duration_add_subtract__subtract; duration_prototype__proto.as = as; duration_prototype__proto.asMilliseconds = asMilliseconds; duration_prototype__proto.asSeconds = asSeconds; duration_prototype__proto.asMinutes = asMinutes; duration_prototype__proto.asHours = asHours; duration_prototype__proto.asDays = asDays; duration_prototype__proto.asWeeks = asWeeks; duration_prototype__proto.asMonths = asMonths; duration_prototype__proto.asYears = asYears; duration_prototype__proto.valueOf = duration_as__valueOf; duration_prototype__proto._bubble = bubble; duration_prototype__proto.get = duration_get__get; duration_prototype__proto.milliseconds = duration_get__milliseconds; duration_prototype__proto.seconds = seconds; duration_prototype__proto.minutes = minutes; duration_prototype__proto.hours = hours; duration_prototype__proto.days = days; duration_prototype__proto.weeks = weeks; duration_prototype__proto.months = months; duration_prototype__proto.years = years; duration_prototype__proto.humanize = humanize; duration_prototype__proto.toISOString = iso_string__toISOString; duration_prototype__proto.toString = iso_string__toISOString; duration_prototype__proto.toJSON = iso_string__toISOString; duration_prototype__proto.locale = locale; duration_prototype__proto.localeData = localeData; // Deprecations duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString); duration_prototype__proto.lang = lang; // Side effect imports addFormatToken('X', 0, 0, 'unix'); addFormatToken('x', 0, 0, 'valueOf'); // PARSING addRegexToken('x', matchSigned); addRegexToken('X', matchTimestamp); addParseToken('X', function (input, array, config) { config._d = new Date(parseFloat(input, 10) * 1000); }); addParseToken('x', function (input, array, config) { config._d = new Date(toInt(input)); }); // Side effect imports utils_hooks__hooks.version = '2.10.2'; setHookCallback(local__createLocal); utils_hooks__hooks.fn = momentPrototype; utils_hooks__hooks.min = min; utils_hooks__hooks.max = max; utils_hooks__hooks.utc = create_utc__createUTC; utils_hooks__hooks.unix = moment__createUnix; utils_hooks__hooks.months = lists__listMonths; utils_hooks__hooks.isDate = isDate; utils_hooks__hooks.locale = locale_locales__getSetGlobalLocale; utils_hooks__hooks.invalid = valid__createInvalid; utils_hooks__hooks.duration = create__createDuration; utils_hooks__hooks.isMoment = isMoment; utils_hooks__hooks.weekdays = lists__listWeekdays; utils_hooks__hooks.parseZone = moment__createInZone; utils_hooks__hooks.localeData = locale_locales__getLocale; utils_hooks__hooks.isDuration = isDuration; utils_hooks__hooks.monthsShort = lists__listMonthsShort; utils_hooks__hooks.weekdaysMin = lists__listWeekdaysMin; utils_hooks__hooks.defineLocale = defineLocale; utils_hooks__hooks.weekdaysShort = lists__listWeekdaysShort; utils_hooks__hooks.normalizeUnits = normalizeUnits; utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold; var _moment = utils_hooks__hooks; return _moment; })); },{}],"numeral":[function(require,module,exports){ "use strict"; (function() { var numeral, VERSION = '1.5.3', languages = {}, currentLanguage = 'en', zeroFormat = null, defaultFormat = '0,0', hasModule = (typeof module !== 'undefined' && module.exports); function Numeral(number) { this._value = number; } function toFixed(value, precision, roundingFunction, optionals) { var power = Math.pow(10, precision), optionalsRegExp, output; output = (roundingFunction(value * power) / power).toFixed(precision); if (optionals) { optionalsRegExp = new RegExp('0{1,' + optionals + '}$'); output = output.replace(optionalsRegExp, ''); } return output; } function formatNumeral(n, format, roundingFunction) { var output; if (format.indexOf('$') > -1) { output = formatCurrency(n, format, roundingFunction); } else if (format.indexOf('%') > -1) { output = formatPercentage(n, format, roundingFunction); } else if (format.indexOf(':') > -1) { output = formatTime(n, format); } else { output = formatNumber(n._value, format, roundingFunction); } return output; } function unformatNumeral(n, string) { var stringOriginal = string, thousandRegExp, millionRegExp, billionRegExp, trillionRegExp, suffixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], bytesMultiplier = false, power; if (string.indexOf(':') > -1) { n._value = unformatTime(string); } else { if (string === zeroFormat) { n._value = 0; } else { if (languages[currentLanguage].delimiters.decimal !== '.') { string = string.replace(/\./g, '').replace(languages[currentLanguage].delimiters.decimal, '.'); } thousandRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); millionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); billionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); trillionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); for (power = 0; power <= suffixes.length; power++) { bytesMultiplier = (string.indexOf(suffixes[power]) > -1) ? Math.pow(1024, power + 1) : false; if (bytesMultiplier) { break; } } n._value = ((bytesMultiplier) ? bytesMultiplier : 1) * ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) * ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) * ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) * ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) * ((string.indexOf('%') > -1) ? 0.01 : 1) * (((string.split('-').length + Math.min(string.split('(').length - 1, string.split(')').length - 1)) % 2) ? 1 : -1) * Number(string.replace(/[^0-9\.]+/g, '')); n._value = (bytesMultiplier) ? Math.ceil(n._value) : n._value; } } return n._value; } function formatCurrency(n, format, roundingFunction) { var symbolIndex = format.indexOf('$'), openParenIndex = format.indexOf('('), minusSignIndex = format.indexOf('-'), space = '', spliceIndex, output; if (format.indexOf(' $') > -1) { space = ' '; format = format.replace(' $', ''); } else if (format.indexOf('$ ') > -1) { space = ' '; format = format.replace('$ ', ''); } else { format = format.replace('$', ''); } output = formatNumber(n._value, format, roundingFunction); if (symbolIndex <= 1) { if (output.indexOf('(') > -1 || output.indexOf('-') > -1) { output = output.split(''); spliceIndex = 1; if (symbolIndex < openParenIndex || symbolIndex < minusSignIndex) { spliceIndex = 0; } output.splice(spliceIndex, 0, languages[currentLanguage].currency.symbol + space); output = output.join(''); } else { output = languages[currentLanguage].currency.symbol + space + output; } } else { if (output.indexOf(')') > -1) { output = output.split(''); output.splice(-1, 0, space + languages[currentLanguage].currency.symbol); output = output.join(''); } else { output = output + space + languages[currentLanguage].currency.symbol; } } return output; } function formatPercentage(n, format, roundingFunction) { var space = '', output, value = n._value * 100; if (format.indexOf(' %') > -1) { space = ' '; format = format.replace(' %', ''); } else { format = format.replace('%', ''); } output = formatNumber(value, format, roundingFunction); if (output.indexOf(')') > -1) { output = output.split(''); output.splice(-1, 0, space + '%'); output = output.join(''); } else { output = output + space + '%'; } return output; } function formatTime(n) { var hours = Math.floor(n._value / 60 / 60), minutes = Math.floor((n._value - (hours * 60 * 60)) / 60), seconds = Math.round(n._value - (hours * 60 * 60) - (minutes * 60)); return hours + ':' + ((minutes < 10) ? '0' + minutes : minutes) + ':' + ((seconds < 10) ? '0' + seconds : seconds); } function unformatTime(string) { var timeArray = string.split(':'), seconds = 0; if (timeArray.length === 3) { seconds = seconds + (Number(timeArray[0]) * 60 * 60); seconds = seconds + (Number(timeArray[1]) * 60); seconds = seconds + Number(timeArray[2]); } else if (timeArray.length === 2) { seconds = seconds + (Number(timeArray[0]) * 60); seconds = seconds + Number(timeArray[1]); } return Number(seconds); } function formatNumber(value, format, roundingFunction) { var negP = false, signed = false, optDec = false, abbr = '', abbrK = false, abbrM = false, abbrB = false, abbrT = false, abbrForce = false, bytes = '', ord = '', abs = Math.abs(value), suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], min, max, power, w, precision, thousands, d = '', neg = false; if (value === 0 && zeroFormat !== null) { return zeroFormat; } else { if (format.indexOf('(') > -1) { negP = true; format = format.slice(1, -1); } else if (format.indexOf('+') > -1) { signed = true; format = format.replace(/\+/g, ''); } if (format.indexOf('a') > -1) { abbrK = format.indexOf('aK') >= 0; abbrM = format.indexOf('aM') >= 0; abbrB = format.indexOf('aB') >= 0; abbrT = format.indexOf('aT') >= 0; abbrForce = abbrK || abbrM || abbrB || abbrT; if (format.indexOf(' a') > -1) { abbr = ' '; format = format.replace(' a', ''); } else { format = format.replace('a', ''); } if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) { abbr = abbr + languages[currentLanguage].abbreviations.trillion; value = value / Math.pow(10, 12); } else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9) && !abbrForce || abbrB) { abbr = abbr + languages[currentLanguage].abbreviations.billion; value = value / Math.pow(10, 9); } else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6) && !abbrForce || abbrM) { abbr = abbr + languages[currentLanguage].abbreviations.million; value = value / Math.pow(10, 6); } else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3) && !abbrForce || abbrK) { abbr = abbr + languages[currentLanguage].abbreviations.thousand; value = value / Math.pow(10, 3); } } if (format.indexOf('b') > -1) { if (format.indexOf(' b') > -1) { bytes = ' '; format = format.replace(' b', ''); } else { format = format.replace('b', ''); } for (power = 0; power <= suffixes.length; power++) { min = Math.pow(1024, power); max = Math.pow(1024, power + 1); if (value >= min && value < max) { bytes = bytes + suffixes[power]; if (min > 0) { value = value / min; } break; } } } if (format.indexOf('o') > -1) { if (format.indexOf(' o') > -1) { ord = ' '; format = format.replace(' o', ''); } else { format = format.replace('o', ''); } ord = ord + languages[currentLanguage].ordinal(value); } if (format.indexOf('[.]') > -1) { optDec = true; format = format.replace('[.]', '.'); } w = value.toString().split('.')[0]; precision = format.split('.')[1]; thousands = format.indexOf(','); if (precision) { if (precision.indexOf('[') > -1) { precision = precision.replace(']', ''); precision = precision.split('['); d = toFixed(value, (precision[0].length + precision[1].length), roundingFunction, precision[1].length); } else { d = toFixed(value, precision.length, roundingFunction); } w = d.split('.')[0]; if (d.split('.')[1].length) { d = languages[currentLanguage].delimiters.decimal + d.split('.')[1]; } else { d = ''; } if (optDec && Number(d.slice(1)) === 0) { d = ''; } } else { w = toFixed(value, null, roundingFunction); } if (w.indexOf('-') > -1) { w = w.slice(1); neg = true; } if (thousands > -1) { w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + languages[currentLanguage].delimiters.thousands); } if (format.indexOf('.') === 0) { w = ''; } return ((negP && neg) ? '(' : '') + ((!negP && neg) ? '-' : '') + ((!neg && signed) ? '+' : '') + w + d + ((ord) ? ord : '') + ((abbr) ? abbr : '') + ((bytes) ? bytes : '') + ((negP && neg) ? ')' : ''); } } numeral = function(input) { if (numeral.isNumeral(input)) { input = input.value(); } else if (input === 0 || typeof input === 'undefined') { input = 0; } else if (!Number(input)) { input = numeral.fn.unformat(input); } return new Numeral(Number(input)); }; numeral.version = VERSION; numeral.isNumeral = function(obj) { return obj instanceof Numeral; }; numeral.language = function(key, values) { if (!key) { return currentLanguage; } if (key && !values) { if (!languages[key]) { throw new Error('Unknown language : ' + key); } currentLanguage = key; } if (values || !languages[key]) { loadLanguage(key, values); } return numeral; }; numeral.languageData = function(key) { if (!key) { return languages[currentLanguage]; } if (!languages[key]) { throw new Error('Unknown language : ' + key); } return languages[key]; }; numeral.language('en', { delimiters: { thousands: ',', decimal: '.' }, abbreviations: { thousand: 'k', million: 'm', billion: 'b', trillion: 't' }, ordinal: function(number) { var b = number % 10; return (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; }, currency: {symbol: '$'} }); numeral.zeroFormat = function(format) { zeroFormat = typeof(format) === 'string' ? format : null; }; numeral.defaultFormat = function(format) { defaultFormat = typeof(format) === 'string' ? format : '0.0'; }; numeral.validate = function(val, culture) { var _decimalSep, _thousandSep, _currSymbol, _valArray, _abbrObj, _thousandRegEx, languageData, temp; if (typeof val !== 'string') { val += ''; if (console.warn) { console.warn('Numeral.js: Value is not string. It has been co-erced to: ', val); } } val = val.trim(); if (val === '') { return false; } val = val.replace(/^[+-]?/, ''); try { languageData = numeral.languageData(culture); } catch (e) { languageData = numeral.languageData(numeral.language()); } _currSymbol = languageData.currency.symbol; _abbrObj = languageData.abbreviations; _decimalSep = languageData.delimiters.decimal; if (languageData.delimiters.thousands === '.') { _thousandSep = '\\.'; } else { _thousandSep = languageData.delimiters.thousands; } temp = val.match(/^[^\d]+/); if (temp !== null) { val = val.substr(1); if (temp[0] !== _currSymbol) { return false; } } temp = val.match(/[^\d]+$/); if (temp !== null) { val = val.slice(0, -1); if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million && temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) { return false; } } if (!!val.match(/^\d+$/)) { return true; } _thousandRegEx = new RegExp(_thousandSep + '{2}'); if (!val.match(/[^\d.,]/g)) { _valArray = val.split(_decimalSep); if (_valArray.length > 2) { return false; } else { if (_valArray.length < 2) { return (!!_valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx)); } else { if (_valArray[0].length === 1) { return (!!_valArray[0].match(/^\d+$/) && !_valArray[0].match(_thousandRegEx) && !!_valArray[1].match(/^\d+$/)); } else { return (!!_valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx) && !!_valArray[1].match(/^\d+$/)); } } } } return false; }; function loadLanguage(key, values) { languages[key] = values; } if ('function' !== typeof Array.prototype.reduce) { Array.prototype.reduce = function(callback, opt_initialValue) { 'use strict'; if (null === this || 'undefined' === typeof this) { throw new TypeError('Array.prototype.reduce called on null or undefined'); } if ('function' !== typeof callback) { throw new TypeError(callback + ' is not a function'); } var index, value, length = this.length >>> 0, isValueSet = false; if (1 < arguments.length) { value = opt_initialValue; isValueSet = true; } for (index = 0; length > index; ++index) { if (this.hasOwnProperty(index)) { if (isValueSet) { value = callback(value, this[index], index, this); } else { value = this[index]; isValueSet = true; } } } if (!isValueSet) { throw new TypeError('Reduce of empty array with no initial value'); } return value; }; } function multiplier(x) { var parts = x.toString().split('.'); if (parts.length < 2) { return 1; } return Math.pow(10, parts[1].length); } function correctionFactor() { var args = Array.prototype.slice.call(arguments); return args.reduce(function(prev, next) { var mp = multiplier(prev), mn = multiplier(next); return mp > mn ? mp : mn; }, -Infinity); } numeral.fn = Numeral.prototype = { clone: function() { return numeral(this); }, format: function(inputString, roundingFunction) { return formatNumeral(this, inputString ? inputString : defaultFormat, (roundingFunction !== undefined) ? roundingFunction : Math.round); }, unformat: function(inputString) { if (Object.prototype.toString.call(inputString) === '[object Number]') { return inputString; } return unformatNumeral(this, inputString ? inputString : defaultFormat); }, value: function() { return this._value; }, valueOf: function() { return this._value; }, set: function(value) { this._value = Number(value); return this; }, add: function(value) { var corrFactor = correctionFactor.call(null, this._value, value); function cback(accum, curr, currI, O) { return accum + corrFactor * curr; } this._value = [this._value, value].reduce(cback, 0) / corrFactor; return this; }, subtract: function(value) { var corrFactor = correctionFactor.call(null, this._value, value); function cback(accum, curr, currI, O) { return accum - corrFactor * curr; } this._value = [value].reduce(cback, this._value * corrFactor) / corrFactor; return this; }, multiply: function(value) { function cback(accum, curr, currI, O) { var corrFactor = correctionFactor(accum, curr); return (accum * corrFactor) * (curr * corrFactor) / (corrFactor * corrFactor); } this._value = [this._value, value].reduce(cback, 1); return this; }, divide: function(value) { function cback(accum, curr, currI, O) { var corrFactor = correctionFactor(accum, curr); return (accum * corrFactor) / (curr * corrFactor); } this._value = [this._value, value].reduce(cback); return this; }, difference: function(value) { return Math.abs(numeral(this._value).subtract(value).value()); } }; if (hasModule) { module.exports = numeral; } if (typeof ender === 'undefined') { this['numeral'] = numeral; } if (typeof define === 'function' && define.amd) { define([], function() { return numeral; }); } }).call(window); //# },{}],"pikaday":[function(require,module,exports){ /*! * Pikaday * * Copyright © 2014 David Bushell | BSD & MIT license | https://github.com/dbushell/Pikaday */ (function (root, factory) { 'use strict'; var moment; if (typeof exports === 'object') { // CommonJS module // Load moment.js as an optional dependency try { moment = require('moment'); } catch (e) {} module.exports = factory(moment); } else if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(function (req) { // Load moment.js as an optional dependency var id = 'moment'; try { moment = req(id); } catch (e) {} return factory(moment); }); } else { root.Pikaday = factory(root.moment); } }(this, function (moment) { 'use strict'; /** * feature detection and helper functions */ var hasMoment = typeof moment === 'function', hasEventListeners = !!window.addEventListener, document = window.document, sto = window.setTimeout, addEvent = function(el, e, callback, capture) { if (hasEventListeners) { el.addEventListener(e, callback, !!capture); } else { el.attachEvent('on' + e, callback); } }, removeEvent = function(el, e, callback, capture) { if (hasEventListeners) { el.removeEventListener(e, callback, !!capture); } else { el.detachEvent('on' + e, callback); } }, fireEvent = function(el, eventName, data) { var ev; if (document.createEvent) { ev = document.createEvent('HTMLEvents'); ev.initEvent(eventName, true, false); ev = extend(ev, data); el.dispatchEvent(ev); } else if (document.createEventObject) { ev = document.createEventObject(); ev = extend(ev, data); el.fireEvent('on' + eventName, ev); } }, trim = function(str) { return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g,''); }, hasClass = function(el, cn) { return (' ' + el.className + ' ').indexOf(' ' + cn + ' ') !== -1; }, addClass = function(el, cn) { if (!hasClass(el, cn)) { el.className = (el.className === '') ? cn : el.className + ' ' + cn; } }, removeClass = function(el, cn) { el.className = trim((' ' + el.className + ' ').replace(' ' + cn + ' ', ' ')); }, isArray = function(obj) { return (/Array/).test(Object.prototype.toString.call(obj)); }, isDate = function(obj) { return (/Date/).test(Object.prototype.toString.call(obj)) && !isNaN(obj.getTime()); }, isWeekend = function(date) { var day = date.getDay(); return day === 0 || day === 6; }, isLeapYear = function(year) { // solution by Matti Virkkunen: http://stackoverflow.com/a/4881951 return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0; }, getDaysInMonth = function(year, month) { return [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }, setToStartOfDay = function(date) { if (isDate(date)) date.setHours(0,0,0,0); }, compareDates = function(a,b) { // weak date comparison (use setToStartOfDay(date) to ensure correct result) return a.getTime() === b.getTime(); }, extend = function(to, from, overwrite) { var prop, hasProp; for (prop in from) { hasProp = to[prop] !== undefined; if (hasProp && typeof from[prop] === 'object' && from[prop] !== null && from[prop].nodeName === undefined) { if (isDate(from[prop])) { if (overwrite) { to[prop] = new Date(from[prop].getTime()); } } else if (isArray(from[prop])) { if (overwrite) { to[prop] = from[prop].slice(0); } } else { to[prop] = extend({}, from[prop], overwrite); } } else if (overwrite || !hasProp) { to[prop] = from[prop]; } } return to; }, adjustCalendar = function(calendar) { if (calendar.month < 0) { calendar.year -= Math.ceil(Math.abs(calendar.month)/12); calendar.month += 12; } if (calendar.month > 11) { calendar.year += Math.floor(Math.abs(calendar.month)/12); calendar.month -= 12; } return calendar; }, /** * defaults and localisation */ defaults = { // bind the picker to a form field field: null, // automatically show/hide the picker on `field` focus (default `true` if `field` is set) bound: undefined, // position of the datepicker, relative to the field (default to bottom & left) // ('bottom' & 'left' keywords are not used, 'top' & 'right' are modifier on the bottom/left position) position: 'bottom left', // automatically fit in the viewport even if it means repositioning from the position option reposition: true, // the default output format for `.toString()` and `field` value format: 'YYYY-MM-DD', // the initial date to view when first opened defaultDate: null, // make the `defaultDate` the initial selected value setDefaultDate: false, // first day of week (0: Sunday, 1: Monday etc) firstDay: 0, // the minimum/earliest date that can be selected minDate: null, // the maximum/latest date that can be selected maxDate: null, // number of years either side, or array of upper/lower range yearRange: 10, // show week numbers at head of row showWeekNumber: false, // used internally (don't config outside) minYear: 0, maxYear: 9999, minMonth: undefined, maxMonth: undefined, isRTL: false, // Additional text to append to the year in the calendar title yearSuffix: '', // Render the month after year in the calendar title showMonthAfterYear: false, // how many months are visible numberOfMonths: 1, // when numberOfMonths is used, this will help you to choose where the main calendar will be (default `left`, can be set to `right`) // only used for the first display or when a selected date is not visible mainCalendar: 'left', // Specify a DOM element to render the calendar in container: undefined, // internationalization i18n: { previousMonth : 'Previous Month', nextMonth : 'Next Month', months : ['January','February','March','April','May','June','July','August','September','October','November','December'], weekdays : ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'], weekdaysShort : ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] }, // callback function onSelect: null, onOpen: null, onClose: null, onDraw: null }, /** * templating functions to abstract HTML rendering */ renderDayName = function(opts, day, abbr) { day += opts.firstDay; while (day >= 7) { day -= 7; } return abbr ? opts.i18n.weekdaysShort[day] : opts.i18n.weekdays[day]; }, renderDay = function(d, m, y, isSelected, isToday, isDisabled, isEmpty) { if (isEmpty) { return '<td class="is-empty"></td>'; } var arr = []; if (isDisabled) { arr.push('is-disabled'); } if (isToday) { arr.push('is-today'); } if (isSelected) { arr.push('is-selected'); } return '<td data-day="' + d + '" class="' + arr.join(' ') + '">' + '<button class="pika-button pika-day" type="button" ' + 'data-pika-year="' + y + '" data-pika-month="' + m + '" data-pika-day="' + d + '">' + d + '</button>' + '</td>'; }, renderWeek = function (d, m, y) { // Lifted from http://javascript.about.com/library/blweekyear.htm, lightly modified. var onejan = new Date(y, 0, 1), weekNum = Math.ceil((((new Date(y, m, d) - onejan) / 86400000) + onejan.getDay()+1)/7); return '<td class="pika-week">' + weekNum + '</td>'; }, renderRow = function(days, isRTL) { return '<tr>' + (isRTL ? days.reverse() : days).join('') + '</tr>'; }, renderBody = function(rows) { return '<tbody>' + rows.join('') + '</tbody>'; }, renderHead = function(opts) { var i, arr = []; if (opts.showWeekNumber) { arr.push('<th></th>'); } for (i = 0; i < 7; i++) { arr.push('<th scope="col"><abbr title="' + renderDayName(opts, i) + '">' + renderDayName(opts, i, true) + '</abbr></th>'); } return '<thead>' + (opts.isRTL ? arr.reverse() : arr).join('') + '</thead>'; }, renderTitle = function(instance, c, year, month, refYear) { var i, j, arr, opts = instance._o, isMinYear = year === opts.minYear, isMaxYear = year === opts.maxYear, html = '<div class="pika-title">', monthHtml, yearHtml, prev = true, next = true; for (arr = [], i = 0; i < 12; i++) { arr.push('<option value="' + (year === refYear ? i - c : 12 + i - c) + '"' + (i === month ? ' selected': '') + ((isMinYear && i < opts.minMonth) || (isMaxYear && i > opts.maxMonth) ? 'disabled' : '') + '>' + opts.i18n.months[i] + '</option>'); } monthHtml = '<div class="pika-label">' + opts.i18n.months[month] + '<select class="pika-select pika-select-month">' + arr.join('') + '</select></div>'; if (isArray(opts.yearRange)) { i = opts.yearRange[0]; j = opts.yearRange[1] + 1; } else { i = year - opts.yearRange; j = 1 + year + opts.yearRange; } for (arr = []; i < j && i <= opts.maxYear; i++) { if (i >= opts.minYear) { arr.push('<option value="' + i + '"' + (i === year ? ' selected': '') + '>' + (i) + '</option>'); } } yearHtml = '<div class="pika-label">' + year + opts.yearSuffix + '<select class="pika-select pika-select-year">' + arr.join('') + '</select></div>'; if (opts.showMonthAfterYear) { html += yearHtml + monthHtml; } else { html += monthHtml + yearHtml; } if (isMinYear && (month === 0 || opts.minMonth >= month)) { prev = false; } if (isMaxYear && (month === 11 || opts.maxMonth <= month)) { next = false; } if (c === 0) { html += '<button class="pika-prev' + (prev ? '' : ' is-disabled') + '" type="button">' + opts.i18n.previousMonth + '</button>'; } if (c === (instance._o.numberOfMonths - 1) ) { html += '<button class="pika-next' + (next ? '' : ' is-disabled') + '" type="button">' + opts.i18n.nextMonth + '</button>'; } return html += '</div>'; }, renderTable = function(opts, data) { return '<table cellpadding="0" cellspacing="0" class="pika-table">' + renderHead(opts) + renderBody(data) + '</table>'; }, /** * Pikaday constructor */ Pikaday = function(options) { var self = this, opts = self.config(options); self._onMouseDown = function(e) { if (!self._v) { return; } e = e || window.event; var target = e.target || e.srcElement; if (!target) { return; } if (!hasClass(target, 'is-disabled')) { if (hasClass(target, 'pika-button') && !hasClass(target, 'is-empty')) { self.setDate(new Date(target.getAttribute('data-pika-year'), target.getAttribute('data-pika-month'), target.getAttribute('data-pika-day'))); if (opts.bound) { sto(function() { self.hide(); if (opts.field) { opts.field.blur(); } }, 100); } return; } else if (hasClass(target, 'pika-prev')) { self.prevMonth(); } else if (hasClass(target, 'pika-next')) { self.nextMonth(); } } if (!hasClass(target, 'pika-select')) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; return false; } } else { self._c = true; } }; self._onChange = function(e) { e = e || window.event; var target = e.target || e.srcElement; if (!target) { return; } if (hasClass(target, 'pika-select-month')) { self.gotoMonth(target.value); } else if (hasClass(target, 'pika-select-year')) { self.gotoYear(target.value); } }; self._onInputChange = function(e) { var date; if (e.firedBy === self) { return; } if (hasMoment) { date = moment(opts.field.value, opts.format); date = (date && date.isValid()) ? date.toDate() : null; } else { date = new Date(Date.parse(opts.field.value)); } self.setDate(isDate(date) ? date : null); if (!self._v) { self.show(); } }; self._onInputFocus = function() { self.show(); }; self._onInputClick = function() { self.show(); }; self._onInputBlur = function() { // IE allows pika div to gain focus; catch blur the input field var pEl = document.activeElement; do { if (hasClass(pEl, 'pika-single')) { return; } } while ((pEl = pEl.parentNode)); if (!self._c) { self._b = sto(function() { self.hide(); }, 50); } self._c = false; }; self._onClick = function(e) { e = e || window.event; var target = e.target || e.srcElement, pEl = target; if (!target) { return; } if (!hasEventListeners && hasClass(target, 'pika-select')) { if (!target.onchange) { target.setAttribute('onchange', 'return;'); addEvent(target, 'change', self._onChange); } } do { if (hasClass(pEl, 'pika-single') || pEl === opts.trigger) { return; } } while ((pEl = pEl.parentNode)); if (self._v && target !== opts.trigger && pEl !== opts.trigger) { self.hide(); } }; self.el = document.createElement('div'); self.el.className = 'pika-single' + (opts.isRTL ? ' is-rtl' : ''); addEvent(self.el, 'mousedown', self._onMouseDown, true); addEvent(self.el, 'change', self._onChange); if (opts.field) { if (opts.container) { opts.container.appendChild(self.el); } else if (opts.bound) { document.body.appendChild(self.el); } else { opts.field.parentNode.insertBefore(self.el, opts.field.nextSibling); } addEvent(opts.field, 'change', self._onInputChange); if (!opts.defaultDate) { if (hasMoment && opts.field.value) { opts.defaultDate = moment(opts.field.value, opts.format).toDate(); } else { opts.defaultDate = new Date(Date.parse(opts.field.value)); } opts.setDefaultDate = true; } } var defDate = opts.defaultDate; if (isDate(defDate)) { if (opts.setDefaultDate) { self.setDate(defDate, true); } else { self.gotoDate(defDate); } } else { self.gotoDate(new Date()); } if (opts.bound) { this.hide(); self.el.className += ' is-bound'; addEvent(opts.trigger, 'click', self._onInputClick); addEvent(opts.trigger, 'focus', self._onInputFocus); addEvent(opts.trigger, 'blur', self._onInputBlur); } else { this.show(); } }; /** * public Pikaday API */ Pikaday.prototype = { /** * configure functionality */ config: function(options) { if (!this._o) { this._o = extend({}, defaults, true); } var opts = extend(this._o, options, true); opts.isRTL = !!opts.isRTL; opts.field = (opts.field && opts.field.nodeName) ? opts.field : null; opts.bound = !!(opts.bound !== undefined ? opts.field && opts.bound : opts.field); opts.trigger = (opts.trigger && opts.trigger.nodeName) ? opts.trigger : opts.field; opts.disableWeekends = !!opts.disableWeekends; opts.disableDayFn = (typeof opts.disableDayFn) == "function" ? opts.disableDayFn : null; var nom = parseInt(opts.numberOfMonths, 10) || 1; opts.numberOfMonths = nom > 4 ? 4 : nom; if (!isDate(opts.minDate)) { opts.minDate = false; } if (!isDate(opts.maxDate)) { opts.maxDate = false; } if ((opts.minDate && opts.maxDate) && opts.maxDate < opts.minDate) { opts.maxDate = opts.minDate = false; } if (opts.minDate) { setToStartOfDay(opts.minDate); opts.minYear = opts.minDate.getFullYear(); opts.minMonth = opts.minDate.getMonth(); } if (opts.maxDate) { setToStartOfDay(opts.maxDate); opts.maxYear = opts.maxDate.getFullYear(); opts.maxMonth = opts.maxDate.getMonth(); } if (isArray(opts.yearRange)) { var fallback = new Date().getFullYear() - 10; opts.yearRange[0] = parseInt(opts.yearRange[0], 10) || fallback; opts.yearRange[1] = parseInt(opts.yearRange[1], 10) || fallback; } else { opts.yearRange = Math.abs(parseInt(opts.yearRange, 10)) || defaults.yearRange; if (opts.yearRange > 100) { opts.yearRange = 100; } } return opts; }, /** * return a formatted string of the current selection (using Moment.js if available) */ toString: function(format) { return !isDate(this._d) ? '' : hasMoment ? moment(this._d).format(format || this._o.format) : this._d.toDateString(); }, /** * return a Moment.js object of the current selection (if available) */ getMoment: function() { return hasMoment ? moment(this._d) : null; }, /** * set the current selection from a Moment.js object (if available) */ setMoment: function(date, preventOnSelect) { if (hasMoment && moment.isMoment(date)) { this.setDate(date.toDate(), preventOnSelect); } }, /** * return a Date object of the current selection */ getDate: function() { return isDate(this._d) ? new Date(this._d.getTime()) : null; }, /** * set the current selection */ setDate: function(date, preventOnSelect) { if (!date) { this._d = null; if (this._o.field) { this._o.field.value = ''; fireEvent(this._o.field, 'change', { firedBy: this }); } return this.draw(); } if (typeof date === 'string') { date = new Date(Date.parse(date)); } if (!isDate(date)) { return; } var min = this._o.minDate, max = this._o.maxDate; if (isDate(min) && date < min) { date = min; } else if (isDate(max) && date > max) { date = max; } this._d = new Date(date.getTime()); setToStartOfDay(this._d); this.gotoDate(this._d); if (this._o.field) { this._o.field.value = this.toString(); fireEvent(this._o.field, 'change', { firedBy: this }); } if (!preventOnSelect && typeof this._o.onSelect === 'function') { this._o.onSelect.call(this, this.getDate()); } }, /** * change view to a specific date */ gotoDate: function(date) { var newCalendar = true; if (!isDate(date)) { return; } if (this.calendars) { var firstVisibleDate = new Date(this.calendars[0].year, this.calendars[0].month, 1), lastVisibleDate = new Date(this.calendars[this.calendars.length-1].year, this.calendars[this.calendars.length-1].month, 1), visibleDate = date.getTime(); // get the end of the month lastVisibleDate.setMonth(lastVisibleDate.getMonth()+1); lastVisibleDate.setDate(lastVisibleDate.getDate()-1); newCalendar = (visibleDate < firstVisibleDate.getTime() || lastVisibleDate.getTime() < visibleDate); } if (newCalendar) { this.calendars = [{ month: date.getMonth(), year: date.getFullYear() }]; if (this._o.mainCalendar === 'right') { this.calendars[0].month += 1 - this._o.numberOfMonths; } } this.adjustCalendars(); }, adjustCalendars: function() { this.calendars[0] = adjustCalendar(this.calendars[0]); for (var c = 1; c < this._o.numberOfMonths; c++) { this.calendars[c] = adjustCalendar({ month: this.calendars[0].month + c, year: this.calendars[0].year }); } this.draw(); }, gotoToday: function() { this.gotoDate(new Date()); }, /** * change view to a specific month (zero-index, e.g. 0: January) */ gotoMonth: function(month) { if (!isNaN(month)) { this.calendars[0].month = parseInt(month, 10); this.adjustCalendars(); } }, nextMonth: function() { this.calendars[0].month++; this.adjustCalendars(); }, prevMonth: function() { this.calendars[0].month--; this.adjustCalendars(); }, /** * change view to a specific full year (e.g. "2012") */ gotoYear: function(year) { if (!isNaN(year)) { this.calendars[0].year = parseInt(year, 10); this.adjustCalendars(); } }, /** * change the minDate */ setMinDate: function(value) { this._o.minDate = value; }, /** * change the maxDate */ setMaxDate: function(value) { this._o.maxDate = value; }, /** * refresh the HTML */ draw: function(force) { if (!this._v && !force) { return; } var opts = this._o, minYear = opts.minYear, maxYear = opts.maxYear, minMonth = opts.minMonth, maxMonth = opts.maxMonth, html = ''; if (this._y <= minYear) { this._y = minYear; if (!isNaN(minMonth) && this._m < minMonth) { this._m = minMonth; } } if (this._y >= maxYear) { this._y = maxYear; if (!isNaN(maxMonth) && this._m > maxMonth) { this._m = maxMonth; } } for (var c = 0; c < opts.numberOfMonths; c++) { html += '<div class="pika-lendar">' + renderTitle(this, c, this.calendars[c].year, this.calendars[c].month, this.calendars[0].year) + this.render(this.calendars[c].year, this.calendars[c].month) + '</div>'; } this.el.innerHTML = html; if (opts.bound) { if(opts.field.type !== 'hidden') { sto(function() { opts.trigger.focus(); }, 1); } } if (typeof this._o.onDraw === 'function') { var self = this; sto(function() { self._o.onDraw.call(self); }, 0); } }, adjustPosition: function() { if (this._o.container) return; var field = this._o.trigger, pEl = field, width = this.el.offsetWidth, height = this.el.offsetHeight, viewportWidth = window.innerWidth || document.documentElement.clientWidth, viewportHeight = window.innerHeight || document.documentElement.clientHeight, scrollTop = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop, left, top, clientRect; if (typeof field.getBoundingClientRect === 'function') { clientRect = field.getBoundingClientRect(); left = clientRect.left + window.pageXOffset; top = clientRect.bottom + window.pageYOffset; } else { left = pEl.offsetLeft; top = pEl.offsetTop + pEl.offsetHeight; while((pEl = pEl.offsetParent)) { left += pEl.offsetLeft; top += pEl.offsetTop; } } // default position is bottom & left if ((this._o.reposition && left + width > viewportWidth) || ( this._o.position.indexOf('right') > -1 && left - width + field.offsetWidth > 0 ) ) { left = left - width + field.offsetWidth; } if ((this._o.reposition && top + height > viewportHeight + scrollTop) || ( this._o.position.indexOf('top') > -1 && top - height - field.offsetHeight > 0 ) ) { top = top - height - field.offsetHeight; } this.el.style.cssText = [ 'position: absolute', 'left: ' + left + 'px', 'top: ' + top + 'px' ].join(';'); }, /** * render HTML for a particular month */ render: function(year, month) { var opts = this._o, now = new Date(), days = getDaysInMonth(year, month), before = new Date(year, month, 1).getDay(), data = [], row = []; setToStartOfDay(now); if (opts.firstDay > 0) { before -= opts.firstDay; if (before < 0) { before += 7; } } var cells = days + before, after = cells; while(after > 7) { after -= 7; } cells += 7 - after; for (var i = 0, r = 0; i < cells; i++) { var day = new Date(year, month, 1 + (i - before)), isSelected = isDate(this._d) ? compareDates(day, this._d) : false, isToday = compareDates(day, now), isEmpty = i < before || i >= (days + before), isDisabled = (opts.minDate && day < opts.minDate) || (opts.maxDate && day > opts.maxDate) || (opts.disableWeekends && isWeekend(day)) || (opts.disableDayFn && opts.disableDayFn(day)); row.push(renderDay(1 + (i - before), month, year, isSelected, isToday, isDisabled, isEmpty)); if (++r === 7) { if (opts.showWeekNumber) { row.unshift(renderWeek(i - before, month, year)); } data.push(renderRow(row, opts.isRTL)); row = []; r = 0; } } return renderTable(opts, data); }, isVisible: function() { return this._v; }, show: function() { if (!this._v) { removeClass(this.el, 'is-hidden'); this._v = true; this.draw(); if (this._o.bound) { addEvent(document, 'click', this._onClick); this.adjustPosition(); } if (typeof this._o.onOpen === 'function') { this._o.onOpen.call(this); } } }, hide: function() { var v = this._v; if (v !== false) { if (this._o.bound) { removeEvent(document, 'click', this._onClick); } this.el.style.cssText = ''; addClass(this.el, 'is-hidden'); this._v = false; if (v !== undefined && typeof this._o.onClose === 'function') { this._o.onClose.call(this); } } }, /** * GAME OVER */ destroy: function() { this.hide(); removeEvent(this.el, 'mousedown', this._onMouseDown, true); removeEvent(this.el, 'change', this._onChange); if (this._o.field) { removeEvent(this._o.field, 'change', this._onInputChange); if (this._o.bound) { removeEvent(this._o.trigger, 'click', this._onInputClick); removeEvent(this._o.trigger, 'focus', this._onInputFocus); removeEvent(this._o.trigger, 'blur', this._onInputBlur); } } if (this.el.parentNode) { this.el.parentNode.removeChild(this.el); } } }; return Pikaday; })); },{"moment":"moment"}],"zeroclipboard":[function(require,module,exports){ /*! * ZeroClipboard * The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface. * Copyright (c) 2009-2014 Jon Rohan, James M. Greene * Licensed MIT * http://zeroclipboard.org/ * v2.2.0 */ (function(window, undefined) { "use strict"; /** * Store references to critically important global functions that may be * overridden on certain web pages. */ var _window = window, _document = _window.document, _navigator = _window.navigator, _setTimeout = _window.setTimeout, _clearTimeout = _window.clearTimeout, _setInterval = _window.setInterval, _clearInterval = _window.clearInterval, _getComputedStyle = _window.getComputedStyle, _encodeURIComponent = _window.encodeURIComponent, _ActiveXObject = _window.ActiveXObject, _Error = _window.Error, _parseInt = _window.Number.parseInt || _window.parseInt, _parseFloat = _window.Number.parseFloat || _window.parseFloat, _isNaN = _window.Number.isNaN || _window.isNaN, _now = _window.Date.now, _keys = _window.Object.keys, _defineProperty = _window.Object.defineProperty, _hasOwn = _window.Object.prototype.hasOwnProperty, _slice = _window.Array.prototype.slice, _unwrap = function() { var unwrapper = function(el) { return el; }; if (typeof _window.wrap === "function" && typeof _window.unwrap === "function") { try { var div = _document.createElement("div"); var unwrappedDiv = _window.unwrap(div); if (div.nodeType === 1 && unwrappedDiv && unwrappedDiv.nodeType === 1) { unwrapper = _window.unwrap; } } catch (e) {} } return unwrapper; }(); /** * Convert an `arguments` object into an Array. * * @returns The arguments as an Array * @private */ var _args = function(argumentsObj) { return _slice.call(argumentsObj, 0); }; /** * Shallow-copy the owned, enumerable properties of one object over to another, similar to jQuery's `$.extend`. * * @returns The target object, augmented * @private */ var _extend = function() { var i, len, arg, prop, src, copy, args = _args(arguments), target = args[0] || {}; for (i = 1, len = args.length; i < len; i++) { if ((arg = args[i]) != null) { for (prop in arg) { if (_hasOwn.call(arg, prop)) { src = target[prop]; copy = arg[prop]; if (target !== copy && copy !== undefined) { target[prop] = copy; } } } } } return target; }; /** * Return a deep copy of the source object or array. * * @returns Object or Array * @private */ var _deepCopy = function(source) { var copy, i, len, prop; if (typeof source !== "object" || source == null || typeof source.nodeType === "number") { copy = source; } else if (typeof source.length === "number") { copy = []; for (i = 0, len = source.length; i < len; i++) { if (_hasOwn.call(source, i)) { copy[i] = _deepCopy(source[i]); } } } else { copy = {}; for (prop in source) { if (_hasOwn.call(source, prop)) { copy[prop] = _deepCopy(source[prop]); } } } return copy; }; /** * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to keep. * The inverse of `_omit`, mostly. The big difference is that these properties do NOT need to be enumerable to * be kept. * * @returns A new filtered object. * @private */ var _pick = function(obj, keys) { var newObj = {}; for (var i = 0, len = keys.length; i < len; i++) { if (keys[i] in obj) { newObj[keys[i]] = obj[keys[i]]; } } return newObj; }; /** * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to omit. * The inverse of `_pick`. * * @returns A new filtered object. * @private */ var _omit = function(obj, keys) { var newObj = {}; for (var prop in obj) { if (keys.indexOf(prop) === -1) { newObj[prop] = obj[prop]; } } return newObj; }; /** * Remove all owned, enumerable properties from an object. * * @returns The original object without its owned, enumerable properties. * @private */ var _deleteOwnProperties = function(obj) { if (obj) { for (var prop in obj) { if (_hasOwn.call(obj, prop)) { delete obj[prop]; } } } return obj; }; /** * Determine if an element is contained within another element. * * @returns Boolean * @private */ var _containedBy = function(el, ancestorEl) { if (el && el.nodeType === 1 && el.ownerDocument && ancestorEl && (ancestorEl.nodeType === 1 && ancestorEl.ownerDocument && ancestorEl.ownerDocument === el.ownerDocument || ancestorEl.nodeType === 9 && !ancestorEl.ownerDocument && ancestorEl === el.ownerDocument)) { do { if (el === ancestorEl) { return true; } el = el.parentNode; } while (el); } return false; }; /** * Get the URL path's parent directory. * * @returns String or `undefined` * @private */ var _getDirPathOfUrl = function(url) { var dir; if (typeof url === "string" && url) { dir = url.split("#")[0].split("?")[0]; dir = url.slice(0, url.lastIndexOf("/") + 1); } return dir; }; /** * Get the current script's URL by throwing an `Error` and analyzing it. * * @returns String or `undefined` * @private */ var _getCurrentScriptUrlFromErrorStack = function(stack) { var url, matches; if (typeof stack === "string" && stack) { matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/); if (matches && matches[1]) { url = matches[1]; } else { matches = stack.match(/\)@((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/); if (matches && matches[1]) { url = matches[1]; } } } return url; }; /** * Get the current script's URL by throwing an `Error` and analyzing it. * * @returns String or `undefined` * @private */ var _getCurrentScriptUrlFromError = function() { var url, err; try { throw new _Error(); } catch (e) { err = e; } if (err) { url = err.sourceURL || err.fileName || _getCurrentScriptUrlFromErrorStack(err.stack); } return url; }; /** * Get the current script's URL. * * @returns String or `undefined` * @private */ var _getCurrentScriptUrl = function() { var jsPath, scripts, i; if (_document.currentScript && (jsPath = _document.currentScript.src)) { return jsPath; } scripts = _document.getElementsByTagName("script"); if (scripts.length === 1) { return scripts[0].src || undefined; } if ("readyState" in scripts[0]) { for (i = scripts.length; i--; ) { if (scripts[i].readyState === "interactive" && (jsPath = scripts[i].src)) { return jsPath; } } } if (_document.readyState === "loading" && (jsPath = scripts[scripts.length - 1].src)) { return jsPath; } if (jsPath = _getCurrentScriptUrlFromError()) { return jsPath; } return undefined; }; /** * Get the unanimous parent directory of ALL script tags. * If any script tags are either (a) inline or (b) from differing parent * directories, this method must return `undefined`. * * @returns String or `undefined` * @private */ var _getUnanimousScriptParentDir = function() { var i, jsDir, jsPath, scripts = _document.getElementsByTagName("script"); for (i = scripts.length; i--; ) { if (!(jsPath = scripts[i].src)) { jsDir = null; break; } jsPath = _getDirPathOfUrl(jsPath); if (jsDir == null) { jsDir = jsPath; } else if (jsDir !== jsPath) { jsDir = null; break; } } return jsDir || undefined; }; /** * Get the presumed location of the "ZeroClipboard.swf" file, based on the location * of the executing JavaScript file (e.g. "ZeroClipboard.js", etc.). * * @returns String * @private */ var _getDefaultSwfPath = function() { var jsDir = _getDirPathOfUrl(_getCurrentScriptUrl()) || _getUnanimousScriptParentDir() || ""; return jsDir + "ZeroClipboard.swf"; }; /** * Keep track of if the page is framed (in an `iframe`). This can never change. * @private */ var _pageIsFramed = function() { return window.opener == null && (!!window.top && window != window.top || !!window.parent && window != window.parent); }(); /** * Keep track of the state of the Flash object. * @private */ var _flashState = { bridge: null, version: "0.0.0", pluginType: "unknown", disabled: null, outdated: null, sandboxed: null, unavailable: null, degraded: null, deactivated: null, overdue: null, ready: null }; /** * The minimum Flash Player version required to use ZeroClipboard completely. * @readonly * @private */ var _minimumFlashVersion = "11.0.0"; /** * The ZeroClipboard library version number, as reported by Flash, at the time the SWF was compiled. */ var _zcSwfVersion; /** * Keep track of all event listener registrations. * @private */ var _handlers = {}; /** * Keep track of the currently activated element. * @private */ var _currentElement; /** * Keep track of the element that was activated when a `copy` process started. * @private */ var _copyTarget; /** * Keep track of data for the pending clipboard transaction. * @private */ var _clipData = {}; /** * Keep track of data formats for the pending clipboard transaction. * @private */ var _clipDataFormatMap = null; /** * Keep track of the Flash availability check timeout. * @private */ var _flashCheckTimeout = 0; /** * Keep track of SWF network errors interval polling. * @private */ var _swfFallbackCheckInterval = 0; /** * The `message` store for events * @private */ var _eventMessages = { ready: "Flash communication is established", error: { "flash-disabled": "Flash is disabled or not installed. May also be attempting to run Flash in a sandboxed iframe, which is impossible.", "flash-outdated": "Flash is too outdated to support ZeroClipboard", "flash-sandboxed": "Attempting to run Flash in a sandboxed iframe, which is impossible", "flash-unavailable": "Flash is unable to communicate bidirectionally with JavaScript", "flash-degraded": "Flash is unable to preserve data fidelity when communicating with JavaScript", "flash-deactivated": "Flash is too outdated for your browser and/or is configured as click-to-activate.\nThis may also mean that the ZeroClipboard SWF object could not be loaded, so please check your `swfPath` configuration and/or network connectivity.\nMay also be attempting to run Flash in a sandboxed iframe, which is impossible.", "flash-overdue": "Flash communication was established but NOT within the acceptable time limit", "version-mismatch": "ZeroClipboard JS version number does not match ZeroClipboard SWF version number", "clipboard-error": "At least one error was thrown while ZeroClipboard was attempting to inject your data into the clipboard", "config-mismatch": "ZeroClipboard configuration does not match Flash's reality", "swf-not-found": "The ZeroClipboard SWF object could not be loaded, so please check your `swfPath` configuration and/or network connectivity" } }; /** * The `name`s of `error` events that can only occur is Flash has at least * been able to load the SWF successfully. * @private */ var _errorsThatOnlyOccurAfterFlashLoads = [ "flash-unavailable", "flash-degraded", "flash-overdue", "version-mismatch", "config-mismatch", "clipboard-error" ]; /** * The `name`s of `error` events that should likely result in the `_flashState` * variable's property values being updated. * @private */ var _flashStateErrorNames = [ "flash-disabled", "flash-outdated", "flash-sandboxed", "flash-unavailable", "flash-degraded", "flash-deactivated", "flash-overdue" ]; /** * A RegExp to match the `name` property of `error` events related to Flash. * @private */ var _flashStateErrorNameMatchingRegex = new RegExp("^flash-(" + _flashStateErrorNames.map(function(errorName) { return errorName.replace(/^flash-/, ""); }).join("|") + ")$"); /** * A RegExp to match the `name` property of `error` events related to Flash, * which is enabled. * @private */ var _flashStateEnabledErrorNameMatchingRegex = new RegExp("^flash-(" + _flashStateErrorNames.slice(1).map(function(errorName) { return errorName.replace(/^flash-/, ""); }).join("|") + ")$"); /** * ZeroClipboard configuration defaults for the Core module. * @private */ var _globalConfig = { swfPath: _getDefaultSwfPath(), trustedDomains: window.location.host ? [ window.location.host ] : [], cacheBust: true, forceEnhancedClipboard: false, flashLoadTimeout: 3e4, autoActivate: true, bubbleEvents: true, containerId: "global-zeroclipboard-html-bridge", containerClass: "global-zeroclipboard-container", swfObjectId: "global-zeroclipboard-flash-bridge", hoverClass: "zeroclipboard-is-hover", activeClass: "zeroclipboard-is-active", forceHandCursor: false, title: null, zIndex: 999999999 }; /** * The underlying implementation of `ZeroClipboard.config`. * @private */ var _config = function(options) { if (typeof options === "object" && options !== null) { for (var prop in options) { if (_hasOwn.call(options, prop)) { if (/^(?:forceHandCursor|title|zIndex|bubbleEvents)$/.test(prop)) { _globalConfig[prop] = options[prop]; } else if (_flashState.bridge == null) { if (prop === "containerId" || prop === "swfObjectId") { if (_isValidHtml4Id(options[prop])) { _globalConfig[prop] = options[prop]; } else { throw new Error("The specified `" + prop + "` value is not valid as an HTML4 Element ID"); } } else { _globalConfig[prop] = options[prop]; } } } } } if (typeof options === "string" && options) { if (_hasOwn.call(_globalConfig, options)) { return _globalConfig[options]; } return; } return _deepCopy(_globalConfig); }; /** * The underlying implementation of `ZeroClipboard.state`. * @private */ var _state = function() { _detectSandbox(); return { browser: _pick(_navigator, [ "userAgent", "platform", "appName" ]), flash: _omit(_flashState, [ "bridge" ]), zeroclipboard: { version: ZeroClipboard.version, config: ZeroClipboard.config() } }; }; /** * The underlying implementation of `ZeroClipboard.isFlashUnusable`. * @private */ var _isFlashUnusable = function() { return !!(_flashState.disabled || _flashState.outdated || _flashState.sandboxed || _flashState.unavailable || _flashState.degraded || _flashState.deactivated); }; /** * The underlying implementation of `ZeroClipboard.on`. * @private */ var _on = function(eventType, listener) { var i, len, events, added = {}; if (typeof eventType === "string" && eventType) { events = eventType.toLowerCase().split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.on(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].replace(/^on/, ""); added[eventType] = true; if (!_handlers[eventType]) { _handlers[eventType] = []; } _handlers[eventType].push(listener); } if (added.ready && _flashState.ready) { ZeroClipboard.emit({ type: "ready" }); } if (added.error) { for (i = 0, len = _flashStateErrorNames.length; i < len; i++) { if (_flashState[_flashStateErrorNames[i].replace(/^flash-/, "")] === true) { ZeroClipboard.emit({ type: "error", name: _flashStateErrorNames[i] }); break; } } if (_zcSwfVersion !== undefined && ZeroClipboard.version !== _zcSwfVersion) { ZeroClipboard.emit({ type: "error", name: "version-mismatch", jsVersion: ZeroClipboard.version, swfVersion: _zcSwfVersion }); } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.off`. * @private */ var _off = function(eventType, listener) { var i, len, foundIndex, events, perEventHandlers; if (arguments.length === 0) { events = _keys(_handlers); } else if (typeof eventType === "string" && eventType) { events = eventType.split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.off(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].toLowerCase().replace(/^on/, ""); perEventHandlers = _handlers[eventType]; if (perEventHandlers && perEventHandlers.length) { if (listener) { foundIndex = perEventHandlers.indexOf(listener); while (foundIndex !== -1) { perEventHandlers.splice(foundIndex, 1); foundIndex = perEventHandlers.indexOf(listener, foundIndex); } } else { perEventHandlers.length = 0; } } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.handlers`. * @private */ var _listeners = function(eventType) { var copy; if (typeof eventType === "string" && eventType) { copy = _deepCopy(_handlers[eventType]) || null; } else { copy = _deepCopy(_handlers); } return copy; }; /** * The underlying implementation of `ZeroClipboard.emit`. * @private */ var _emit = function(event) { var eventCopy, returnVal, tmp; event = _createEvent(event); if (!event) { return; } if (_preprocessEvent(event)) { return; } if (event.type === "ready" && _flashState.overdue === true) { return ZeroClipboard.emit({ type: "error", name: "flash-overdue" }); } eventCopy = _extend({}, event); _dispatchCallbacks.call(this, eventCopy); if (event.type === "copy") { tmp = _mapClipDataToFlash(_clipData); returnVal = tmp.data; _clipDataFormatMap = tmp.formatMap; } return returnVal; }; /** * The underlying implementation of `ZeroClipboard.create`. * @private */ var _create = function() { var previousState = _flashState.sandboxed; _detectSandbox(); if (typeof _flashState.ready !== "boolean") { _flashState.ready = false; } if (_flashState.sandboxed !== previousState && _flashState.sandboxed === true) { _flashState.ready = false; ZeroClipboard.emit({ type: "error", name: "flash-sandboxed" }); } else if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) { var maxWait = _globalConfig.flashLoadTimeout; if (typeof maxWait === "number" && maxWait >= 0) { _flashCheckTimeout = _setTimeout(function() { if (typeof _flashState.deactivated !== "boolean") { _flashState.deactivated = true; } if (_flashState.deactivated === true) { ZeroClipboard.emit({ type: "error", name: "flash-deactivated" }); } }, maxWait); } _flashState.overdue = false; _embedSwf(); } }; /** * The underlying implementation of `ZeroClipboard.destroy`. * @private */ var _destroy = function() { ZeroClipboard.clearData(); ZeroClipboard.blur(); ZeroClipboard.emit("destroy"); _unembedSwf(); ZeroClipboard.off(); }; /** * The underlying implementation of `ZeroClipboard.setData`. * @private */ var _setData = function(format, data) { var dataObj; if (typeof format === "object" && format && typeof data === "undefined") { dataObj = format; ZeroClipboard.clearData(); } else if (typeof format === "string" && format) { dataObj = {}; dataObj[format] = data; } else { return; } for (var dataFormat in dataObj) { if (typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat]) { _clipData[dataFormat] = dataObj[dataFormat]; } } }; /** * The underlying implementation of `ZeroClipboard.clearData`. * @private */ var _clearData = function(format) { if (typeof format === "undefined") { _deleteOwnProperties(_clipData); _clipDataFormatMap = null; } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) { delete _clipData[format]; } }; /** * The underlying implementation of `ZeroClipboard.getData`. * @private */ var _getData = function(format) { if (typeof format === "undefined") { return _deepCopy(_clipData); } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) { return _clipData[format]; } }; /** * The underlying implementation of `ZeroClipboard.focus`/`ZeroClipboard.activate`. * @private */ var _focus = function(element) { if (!(element && element.nodeType === 1)) { return; } if (_currentElement) { _removeClass(_currentElement, _globalConfig.activeClass); if (_currentElement !== element) { _removeClass(_currentElement, _globalConfig.hoverClass); } } _currentElement = element; _addClass(element, _globalConfig.hoverClass); var newTitle = element.getAttribute("title") || _globalConfig.title; if (typeof newTitle === "string" && newTitle) { var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.setAttribute("title", newTitle); } } var useHandCursor = _globalConfig.forceHandCursor === true || _getStyle(element, "cursor") === "pointer"; _setHandCursor(useHandCursor); _reposition(); }; /** * The underlying implementation of `ZeroClipboard.blur`/`ZeroClipboard.deactivate`. * @private */ var _blur = function() { var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.removeAttribute("title"); htmlBridge.style.left = "0px"; htmlBridge.style.top = "-9999px"; htmlBridge.style.width = "1px"; htmlBridge.style.height = "1px"; } if (_currentElement) { _removeClass(_currentElement, _globalConfig.hoverClass); _removeClass(_currentElement, _globalConfig.activeClass); _currentElement = null; } }; /** * The underlying implementation of `ZeroClipboard.activeElement`. * @private */ var _activeElement = function() { return _currentElement || null; }; /** * Check if a value is a valid HTML4 `ID` or `Name` token. * @private */ var _isValidHtml4Id = function(id) { return typeof id === "string" && id && /^[A-Za-z][A-Za-z0-9_:\-\.]*$/.test(id); }; /** * Create or update an `event` object, based on the `eventType`. * @private */ var _createEvent = function(event) { var eventType; if (typeof event === "string" && event) { eventType = event; event = {}; } else if (typeof event === "object" && event && typeof event.type === "string" && event.type) { eventType = event.type; } if (!eventType) { return; } eventType = eventType.toLowerCase(); if (!event.target && (/^(copy|aftercopy|_click)$/.test(eventType) || eventType === "error" && event.name === "clipboard-error")) { event.target = _copyTarget; } _extend(event, { type: eventType, target: event.target || _currentElement || null, relatedTarget: event.relatedTarget || null, currentTarget: _flashState && _flashState.bridge || null, timeStamp: event.timeStamp || _now() || null }); var msg = _eventMessages[event.type]; if (event.type === "error" && event.name && msg) { msg = msg[event.name]; } if (msg) { event.message = msg; } if (event.type === "ready") { _extend(event, { target: null, version: _flashState.version }); } if (event.type === "error") { if (_flashStateErrorNameMatchingRegex.test(event.name)) { _extend(event, { target: null, minimumVersion: _minimumFlashVersion }); } if (_flashStateEnabledErrorNameMatchingRegex.test(event.name)) { _extend(event, { version: _flashState.version }); } } if (event.type === "copy") { event.clipboardData = { setData: ZeroClipboard.setData, clearData: ZeroClipboard.clearData }; } if (event.type === "aftercopy") { event = _mapClipResultsFromFlash(event, _clipDataFormatMap); } if (event.target && !event.relatedTarget) { event.relatedTarget = _getRelatedTarget(event.target); } return _addMouseData(event); }; /** * Get a relatedTarget from the target's `data-clipboard-target` attribute * @private */ var _getRelatedTarget = function(targetEl) { var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target"); return relatedTargetId ? _document.getElementById(relatedTargetId) : null; }; /** * Add element and position data to `MouseEvent` instances * @private */ var _addMouseData = function(event) { if (event && /^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) { var srcElement = event.target; var fromElement = event.type === "_mouseover" && event.relatedTarget ? event.relatedTarget : undefined; var toElement = event.type === "_mouseout" && event.relatedTarget ? event.relatedTarget : undefined; var pos = _getElementPosition(srcElement); var screenLeft = _window.screenLeft || _window.screenX || 0; var screenTop = _window.screenTop || _window.screenY || 0; var scrollLeft = _document.body.scrollLeft + _document.documentElement.scrollLeft; var scrollTop = _document.body.scrollTop + _document.documentElement.scrollTop; var pageX = pos.left + (typeof event._stageX === "number" ? event._stageX : 0); var pageY = pos.top + (typeof event._stageY === "number" ? event._stageY : 0); var clientX = pageX - scrollLeft; var clientY = pageY - scrollTop; var screenX = screenLeft + clientX; var screenY = screenTop + clientY; var moveX = typeof event.movementX === "number" ? event.movementX : 0; var moveY = typeof event.movementY === "number" ? event.movementY : 0; delete event._stageX; delete event._stageY; _extend(event, { srcElement: srcElement, fromElement: fromElement, toElement: toElement, screenX: screenX, screenY: screenY, pageX: pageX, pageY: pageY, clientX: clientX, clientY: clientY, x: clientX, y: clientY, movementX: moveX, movementY: moveY, offsetX: 0, offsetY: 0, layerX: 0, layerY: 0 }); } return event; }; /** * Determine if an event's registered handlers should be execute synchronously or asynchronously. * * @returns {boolean} * @private */ var _shouldPerformAsync = function(event) { var eventType = event && typeof event.type === "string" && event.type || ""; return !/^(?:(?:before)?copy|destroy)$/.test(eventType); }; /** * Control if a callback should be executed asynchronously or not. * * @returns `undefined` * @private */ var _dispatchCallback = function(func, context, args, async) { if (async) { _setTimeout(function() { func.apply(context, args); }, 0); } else { func.apply(context, args); } }; /** * Handle the actual dispatching of events to client instances. * * @returns `undefined` * @private */ var _dispatchCallbacks = function(event) { if (!(typeof event === "object" && event && event.type)) { return; } var async = _shouldPerformAsync(event); var wildcardTypeHandlers = _handlers["*"] || []; var specificTypeHandlers = _handlers[event.type] || []; var handlers = wildcardTypeHandlers.concat(specificTypeHandlers); if (handlers && handlers.length) { var i, len, func, context, eventCopy, originalContext = this; for (i = 0, len = handlers.length; i < len; i++) { func = handlers[i]; context = originalContext; if (typeof func === "string" && typeof _window[func] === "function") { func = _window[func]; } if (typeof func === "object" && func && typeof func.handleEvent === "function") { context = func; func = func.handleEvent; } if (typeof func === "function") { eventCopy = _extend({}, event); _dispatchCallback(func, context, [ eventCopy ], async); } } } return this; }; /** * Check an `error` event's `name` property to see if Flash has * already loaded, which rules out possible `iframe` sandboxing. * @private */ var _getSandboxStatusFromErrorEvent = function(event) { var isSandboxed = null; if (_pageIsFramed === false || event && event.type === "error" && event.name && _errorsThatOnlyOccurAfterFlashLoads.indexOf(event.name) !== -1) { isSandboxed = false; } return isSandboxed; }; /** * Preprocess any special behaviors, reactions, or state changes after receiving this event. * Executes only once per event emitted, NOT once per client. * @private */ var _preprocessEvent = function(event) { var element = event.target || _currentElement || null; var sourceIsSwf = event._source === "swf"; delete event._source; switch (event.type) { case "error": var isSandboxed = event.name === "flash-sandboxed" || _getSandboxStatusFromErrorEvent(event); if (typeof isSandboxed === "boolean") { _flashState.sandboxed = isSandboxed; } if (_flashStateErrorNames.indexOf(event.name) !== -1) { _extend(_flashState, { disabled: event.name === "flash-disabled", outdated: event.name === "flash-outdated", unavailable: event.name === "flash-unavailable", degraded: event.name === "flash-degraded", deactivated: event.name === "flash-deactivated", overdue: event.name === "flash-overdue", ready: false }); } else if (event.name === "version-mismatch") { _zcSwfVersion = event.swfVersion; _extend(_flashState, { disabled: false, outdated: false, unavailable: false, degraded: false, deactivated: false, overdue: false, ready: false }); } _clearTimeoutsAndPolling(); break; case "ready": _zcSwfVersion = event.swfVersion; var wasDeactivated = _flashState.deactivated === true; _extend(_flashState, { disabled: false, outdated: false, sandboxed: false, unavailable: false, degraded: false, deactivated: false, overdue: wasDeactivated, ready: !wasDeactivated }); _clearTimeoutsAndPolling(); break; case "beforecopy": _copyTarget = element; break; case "copy": var textContent, htmlContent, targetEl = event.relatedTarget; if (!(_clipData["text/html"] || _clipData["text/plain"]) && targetEl && (htmlContent = targetEl.value || targetEl.outerHTML || targetEl.innerHTML) && (textContent = targetEl.value || targetEl.textContent || targetEl.innerText)) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); if (htmlContent !== textContent) { event.clipboardData.setData("text/html", htmlContent); } } else if (!_clipData["text/plain"] && event.target && (textContent = event.target.getAttribute("data-clipboard-text"))) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); } break; case "aftercopy": _queueEmitClipboardErrors(event); ZeroClipboard.clearData(); if (element && element !== _safeActiveElement() && element.focus) { element.focus(); } break; case "_mouseover": ZeroClipboard.focus(element); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) { _fireMouseEvent(_extend({}, event, { type: "mouseenter", bubbles: false, cancelable: false })); } _fireMouseEvent(_extend({}, event, { type: "mouseover" })); } break; case "_mouseout": ZeroClipboard.blur(); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) { _fireMouseEvent(_extend({}, event, { type: "mouseleave", bubbles: false, cancelable: false })); } _fireMouseEvent(_extend({}, event, { type: "mouseout" })); } break; case "_mousedown": _addClass(element, _globalConfig.activeClass); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_mouseup": _removeClass(element, _globalConfig.activeClass); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_click": _copyTarget = null; if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_mousemove": if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; } if (/^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) { return true; } }; /** * Check an "aftercopy" event for clipboard errors and emit a corresponding "error" event. * @private */ var _queueEmitClipboardErrors = function(aftercopyEvent) { if (aftercopyEvent.errors && aftercopyEvent.errors.length > 0) { var errorEvent = _deepCopy(aftercopyEvent); _extend(errorEvent, { type: "error", name: "clipboard-error" }); delete errorEvent.success; _setTimeout(function() { ZeroClipboard.emit(errorEvent); }, 0); } }; /** * Dispatch a synthetic MouseEvent. * * @returns `undefined` * @private */ var _fireMouseEvent = function(event) { if (!(event && typeof event.type === "string" && event)) { return; } var e, target = event.target || null, doc = target && target.ownerDocument || _document, defaults = { view: doc.defaultView || _window, canBubble: true, cancelable: true, detail: event.type === "click" ? 1 : 0, button: typeof event.which === "number" ? event.which - 1 : typeof event.button === "number" ? event.button : doc.createEvent ? 0 : 1 }, args = _extend(defaults, event); if (!target) { return; } if (doc.createEvent && target.dispatchEvent) { args = [ args.type, args.canBubble, args.cancelable, args.view, args.detail, args.screenX, args.screenY, args.clientX, args.clientY, args.ctrlKey, args.altKey, args.shiftKey, args.metaKey, args.button, args.relatedTarget ]; e = doc.createEvent("MouseEvents"); if (e.initMouseEvent) { e.initMouseEvent.apply(e, args); e._source = "js"; target.dispatchEvent(e); } } }; /** * Continuously poll the DOM until either: * (a) the fallback content becomes visible, or * (b) we receive an event from SWF (handled elsewhere) * * IMPORTANT: * This is NOT a necessary check but it can result in significantly faster * detection of bad `swfPath` configuration and/or network/server issues [in * supported browsers] than waiting for the entire `flashLoadTimeout` duration * to elapse before detecting that the SWF cannot be loaded. The detection * duration can be anywhere from 10-30 times faster [in supported browsers] by * using this approach. * * @returns `undefined` * @private */ var _watchForSwfFallbackContent = function() { var maxWait = _globalConfig.flashLoadTimeout; if (typeof maxWait === "number" && maxWait >= 0) { var pollWait = Math.min(1e3, maxWait / 10); var fallbackContentId = _globalConfig.swfObjectId + "_fallbackContent"; _swfFallbackCheckInterval = _setInterval(function() { var el = _document.getElementById(fallbackContentId); if (_isElementVisible(el)) { _clearTimeoutsAndPolling(); _flashState.deactivated = null; ZeroClipboard.emit({ type: "error", name: "swf-not-found" }); } }, pollWait); } }; /** * Create the HTML bridge element to embed the Flash object into. * @private */ var _createHtmlBridge = function() { var container = _document.createElement("div"); container.id = _globalConfig.containerId; container.className = _globalConfig.containerClass; container.style.position = "absolute"; container.style.left = "0px"; container.style.top = "-9999px"; container.style.width = "1px"; container.style.height = "1px"; container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex); return container; }; /** * Get the HTML element container that wraps the Flash bridge object/element. * @private */ var _getHtmlBridge = function(flashBridge) { var htmlBridge = flashBridge && flashBridge.parentNode; while (htmlBridge && htmlBridge.nodeName === "OBJECT" && htmlBridge.parentNode) { htmlBridge = htmlBridge.parentNode; } return htmlBridge || null; }; /** * Create the SWF object. * * @returns The SWF object reference. * @private */ var _embedSwf = function() { var len, flashBridge = _flashState.bridge, container = _getHtmlBridge(flashBridge); if (!flashBridge) { var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig); var allowNetworking = allowScriptAccess === "never" ? "none" : "all"; var flashvars = _vars(_extend({ jsVersion: ZeroClipboard.version }, _globalConfig)); var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig); container = _createHtmlBridge(); var divToBeReplaced = _document.createElement("div"); container.appendChild(divToBeReplaced); _document.body.appendChild(container); var tmpDiv = _document.createElement("div"); var usingActiveX = _flashState.pluginType === "activex"; tmpDiv.innerHTML = '<object id="' + _globalConfig.swfObjectId + '" name="' + _globalConfig.swfObjectId + '" ' + 'width="100%" height="100%" ' + (usingActiveX ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + ">" + (usingActiveX ? '<param name="movie" value="' + swfUrl + '"/>' : "") + '<param name="allowScriptAccess" value="' + allowScriptAccess + '"/>' + '<param name="allowNetworking" value="' + allowNetworking + '"/>' + '<param name="menu" value="false"/>' + '<param name="wmode" value="transparent"/>' + '<param name="flashvars" value="' + flashvars + '"/>' + '<div id="' + _globalConfig.swfObjectId + '_fallbackContent">&nbsp;</div>' + "</object>"; flashBridge = tmpDiv.firstChild; tmpDiv = null; _unwrap(flashBridge).ZeroClipboard = ZeroClipboard; container.replaceChild(flashBridge, divToBeReplaced); _watchForSwfFallbackContent(); } if (!flashBridge) { flashBridge = _document[_globalConfig.swfObjectId]; if (flashBridge && (len = flashBridge.length)) { flashBridge = flashBridge[len - 1]; } if (!flashBridge && container) { flashBridge = container.firstChild; } } _flashState.bridge = flashBridge || null; return flashBridge; }; /** * Destroy the SWF object. * @private */ var _unembedSwf = function() { var flashBridge = _flashState.bridge; if (flashBridge) { var htmlBridge = _getHtmlBridge(flashBridge); if (htmlBridge) { if (_flashState.pluginType === "activex" && "readyState" in flashBridge) { flashBridge.style.display = "none"; (function removeSwfFromIE() { if (flashBridge.readyState === 4) { for (var prop in flashBridge) { if (typeof flashBridge[prop] === "function") { flashBridge[prop] = null; } } if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } else { _setTimeout(removeSwfFromIE, 10); } })(); } else { if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } } _clearTimeoutsAndPolling(); _flashState.ready = null; _flashState.bridge = null; _flashState.deactivated = null; _zcSwfVersion = undefined; } }; /** * Map the data format names of the "clipData" to Flash-friendly names. * * @returns A new transformed object. * @private */ var _mapClipDataToFlash = function(clipData) { var newClipData = {}, formatMap = {}; if (!(typeof clipData === "object" && clipData)) { return; } for (var dataFormat in clipData) { if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) { switch (dataFormat.toLowerCase()) { case "text/plain": case "text": case "air:text": case "flash:text": newClipData.text = clipData[dataFormat]; formatMap.text = dataFormat; break; case "text/html": case "html": case "air:html": case "flash:html": newClipData.html = clipData[dataFormat]; formatMap.html = dataFormat; break; case "application/rtf": case "text/rtf": case "rtf": case "richtext": case "air:rtf": case "flash:rtf": newClipData.rtf = clipData[dataFormat]; formatMap.rtf = dataFormat; break; default: break; } } } return { data: newClipData, formatMap: formatMap }; }; /** * Map the data format names from Flash-friendly names back to their original "clipData" names (via a format mapping). * * @returns A new transformed object. * @private */ var _mapClipResultsFromFlash = function(clipResults, formatMap) { if (!(typeof clipResults === "object" && clipResults && typeof formatMap === "object" && formatMap)) { return clipResults; } var newResults = {}; for (var prop in clipResults) { if (_hasOwn.call(clipResults, prop)) { if (prop === "errors") { newResults[prop] = clipResults[prop] ? clipResults[prop].slice() : []; for (var i = 0, len = newResults[prop].length; i < len; i++) { newResults[prop][i].format = formatMap[newResults[prop][i].format]; } } else if (prop !== "success" && prop !== "data") { newResults[prop] = clipResults[prop]; } else { newResults[prop] = {}; var tmpHash = clipResults[prop]; for (var dataFormat in tmpHash) { if (dataFormat && _hasOwn.call(tmpHash, dataFormat) && _hasOwn.call(formatMap, dataFormat)) { newResults[prop][formatMap[dataFormat]] = tmpHash[dataFormat]; } } } } } return newResults; }; /** * Will look at a path, and will create a "?noCache={time}" or "&noCache={time}" * query param string to return. Does NOT append that string to the original path. * This is useful because ExternalInterface often breaks when a Flash SWF is cached. * * @returns The `noCache` query param with necessary "?"/"&" prefix. * @private */ var _cacheBust = function(path, options) { var cacheBust = options == null || options && options.cacheBust === true; if (cacheBust) { return (path.indexOf("?") === -1 ? "?" : "&") + "noCache=" + _now(); } else { return ""; } }; /** * Creates a query string for the FlashVars param. * Does NOT include the cache-busting query param. * * @returns FlashVars query string * @private */ var _vars = function(options) { var i, len, domain, domains, str = "", trustedOriginsExpanded = []; if (options.trustedDomains) { if (typeof options.trustedDomains === "string") { domains = [ options.trustedDomains ]; } else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) { domains = options.trustedDomains; } } if (domains && domains.length) { for (i = 0, len = domains.length; i < len; i++) { if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") { domain = _extractDomain(domains[i]); if (!domain) { continue; } if (domain === "*") { trustedOriginsExpanded.length = 0; trustedOriginsExpanded.push(domain); break; } trustedOriginsExpanded.push.apply(trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ]); } } } if (trustedOriginsExpanded.length) { str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(",")); } if (options.forceEnhancedClipboard === true) { str += (str ? "&" : "") + "forceEnhancedClipboard=true"; } if (typeof options.swfObjectId === "string" && options.swfObjectId) { str += (str ? "&" : "") + "swfObjectId=" + _encodeURIComponent(options.swfObjectId); } if (typeof options.jsVersion === "string" && options.jsVersion) { str += (str ? "&" : "") + "jsVersion=" + _encodeURIComponent(options.jsVersion); } return str; }; /** * Extract the domain (e.g. "github.com") from an origin (e.g. "https://github.com") or * URL (e.g. "https://github.com/zeroclipboard/zeroclipboard/"). * * @returns the domain * @private */ var _extractDomain = function(originOrUrl) { if (originOrUrl == null || originOrUrl === "") { return null; } originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, ""); if (originOrUrl === "") { return null; } var protocolIndex = originOrUrl.indexOf("//"); originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2); var pathIndex = originOrUrl.indexOf("/"); originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex); if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") { return null; } return originOrUrl || null; }; /** * Set `allowScriptAccess` based on `trustedDomains` and `window.location.host` vs. `swfPath`. * * @returns The appropriate script access level. * @private */ var _determineScriptAccess = function() { var _extractAllDomains = function(origins) { var i, len, tmp, resultsArray = []; if (typeof origins === "string") { origins = [ origins ]; } if (!(typeof origins === "object" && origins && typeof origins.length === "number")) { return resultsArray; } for (i = 0, len = origins.length; i < len; i++) { if (_hasOwn.call(origins, i) && (tmp = _extractDomain(origins[i]))) { if (tmp === "*") { resultsArray.length = 0; resultsArray.push("*"); break; } if (resultsArray.indexOf(tmp) === -1) { resultsArray.push(tmp); } } } return resultsArray; }; return function(currentDomain, configOptions) { var swfDomain = _extractDomain(configOptions.swfPath); if (swfDomain === null) { swfDomain = currentDomain; } var trustedDomains = _extractAllDomains(configOptions.trustedDomains); var len = trustedDomains.length; if (len > 0) { if (len === 1 && trustedDomains[0] === "*") { return "always"; } if (trustedDomains.indexOf(currentDomain) !== -1) { if (len === 1 && currentDomain === swfDomain) { return "sameDomain"; } return "always"; } } return "never"; }; }(); /** * Get the currently active/focused DOM element. * * @returns the currently active/focused element, or `null` * @private */ var _safeActiveElement = function() { try { return _document.activeElement; } catch (err) { return null; } }; /** * Add a class to an element, if it doesn't already have it. * * @returns The element, with its new class added. * @private */ var _addClass = function(element, value) { var c, cl, className, classNames = []; if (typeof value === "string" && value) { classNames = value.split(/\s+/); } if (element && element.nodeType === 1 && classNames.length > 0) { if (element.classList) { for (c = 0, cl = classNames.length; c < cl; c++) { element.classList.add(classNames[c]); } } else if (element.hasOwnProperty("className")) { className = " " + element.className + " "; for (c = 0, cl = classNames.length; c < cl; c++) { if (className.indexOf(" " + classNames[c] + " ") === -1) { className += classNames[c] + " "; } } element.className = className.replace(/^\s+|\s+$/g, ""); } } return element; }; /** * Remove a class from an element, if it has it. * * @returns The element, with its class removed. * @private */ var _removeClass = function(element, value) { var c, cl, className, classNames = []; if (typeof value === "string" && value) { classNames = value.split(/\s+/); } if (element && element.nodeType === 1 && classNames.length > 0) { if (element.classList && element.classList.length > 0) { for (c = 0, cl = classNames.length; c < cl; c++) { element.classList.remove(classNames[c]); } } else if (element.className) { className = (" " + element.className + " ").replace(/[\r\n\t]/g, " "); for (c = 0, cl = classNames.length; c < cl; c++) { className = className.replace(" " + classNames[c] + " ", " "); } element.className = className.replace(/^\s+|\s+$/g, ""); } } return element; }; /** * Attempt to interpret the element's CSS styling. If `prop` is `"cursor"`, * then we assume that it should be a hand ("pointer") cursor if the element * is an anchor element ("a" tag). * * @returns The computed style property. * @private */ var _getStyle = function(el, prop) { var value = _getComputedStyle(el, null).getPropertyValue(prop); if (prop === "cursor") { if (!value || value === "auto") { if (el.nodeName === "A") { return "pointer"; } } } return value; }; /** * Get the absolutely positioned coordinates of a DOM element. * * @returns Object containing the element's position, width, and height. * @private */ var _getElementPosition = function(el) { var pos = { left: 0, top: 0, width: 0, height: 0 }; if (el.getBoundingClientRect) { var elRect = el.getBoundingClientRect(); var pageXOffset = _window.pageXOffset; var pageYOffset = _window.pageYOffset; var leftBorderWidth = _document.documentElement.clientLeft || 0; var topBorderWidth = _document.documentElement.clientTop || 0; var leftBodyOffset = 0; var topBodyOffset = 0; if (_getStyle(_document.body, "position") === "relative") { var bodyRect = _document.body.getBoundingClientRect(); var htmlRect = _document.documentElement.getBoundingClientRect(); leftBodyOffset = bodyRect.left - htmlRect.left || 0; topBodyOffset = bodyRect.top - htmlRect.top || 0; } pos.left = elRect.left + pageXOffset - leftBorderWidth - leftBodyOffset; pos.top = elRect.top + pageYOffset - topBorderWidth - topBodyOffset; pos.width = "width" in elRect ? elRect.width : elRect.right - elRect.left; pos.height = "height" in elRect ? elRect.height : elRect.bottom - elRect.top; } return pos; }; /** * Determine is an element is visible somewhere within the document (page). * * @returns Boolean * @private */ var _isElementVisible = function(el) { if (!el) { return false; } var styles = _getComputedStyle(el, null); var hasCssHeight = _parseFloat(styles.height) > 0; var hasCssWidth = _parseFloat(styles.width) > 0; var hasCssTop = _parseFloat(styles.top) >= 0; var hasCssLeft = _parseFloat(styles.left) >= 0; var cssKnows = hasCssHeight && hasCssWidth && hasCssTop && hasCssLeft; var rect = cssKnows ? null : _getElementPosition(el); var isVisible = styles.display !== "none" && styles.visibility !== "collapse" && (cssKnows || !!rect && (hasCssHeight || rect.height > 0) && (hasCssWidth || rect.width > 0) && (hasCssTop || rect.top >= 0) && (hasCssLeft || rect.left >= 0)); return isVisible; }; /** * Clear all existing timeouts and interval polling delegates. * * @returns `undefined` * @private */ var _clearTimeoutsAndPolling = function() { _clearTimeout(_flashCheckTimeout); _flashCheckTimeout = 0; _clearInterval(_swfFallbackCheckInterval); _swfFallbackCheckInterval = 0; }; /** * Reposition the Flash object to cover the currently activated element. * * @returns `undefined` * @private */ var _reposition = function() { var htmlBridge; if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) { var pos = _getElementPosition(_currentElement); _extend(htmlBridge.style, { width: pos.width + "px", height: pos.height + "px", top: pos.top + "px", left: pos.left + "px", zIndex: "" + _getSafeZIndex(_globalConfig.zIndex) }); } }; /** * Sends a signal to the Flash object to display the hand cursor if `true`. * * @returns `undefined` * @private */ var _setHandCursor = function(enabled) { if (_flashState.ready === true) { if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") { _flashState.bridge.setHandCursor(enabled); } else { _flashState.ready = false; } } }; /** * Get a safe value for `zIndex` * * @returns an integer, or "auto" * @private */ var _getSafeZIndex = function(val) { if (/^(?:auto|inherit)$/.test(val)) { return val; } var zIndex; if (typeof val === "number" && !_isNaN(val)) { zIndex = val; } else if (typeof val === "string") { zIndex = _getSafeZIndex(_parseInt(val, 10)); } return typeof zIndex === "number" ? zIndex : "auto"; }; /** * Attempt to detect if ZeroClipboard is executing inside of a sandboxed iframe. * If it is, Flash Player cannot be used, so ZeroClipboard is dead in the water. * * @see {@link http://lists.w3.org/Archives/Public/public-whatwg-archive/2014Dec/0002.html} * @see {@link https://github.com/zeroclipboard/zeroclipboard/issues/511} * @see {@link http://zeroclipboard.org/test-iframes.html} * * @returns `true` (is sandboxed), `false` (is not sandboxed), or `null` (uncertain) * @private */ var _detectSandbox = function(doNotReassessFlashSupport) { var effectiveScriptOrigin, frame, frameError, previousState = _flashState.sandboxed, isSandboxed = null; doNotReassessFlashSupport = doNotReassessFlashSupport === true; if (_pageIsFramed === false) { isSandboxed = false; } else { try { frame = window.frameElement || null; } catch (e) { frameError = { name: e.name, message: e.message }; } if (frame && frame.nodeType === 1 && frame.nodeName === "IFRAME") { try { isSandboxed = frame.hasAttribute("sandbox"); } catch (e) { isSandboxed = null; } } else { try { effectiveScriptOrigin = document.domain || null; } catch (e) { effectiveScriptOrigin = null; } if (effectiveScriptOrigin === null || frameError && frameError.name === "SecurityError" && /(^|[\s\(\[@])sandbox(es|ed|ing|[\s\.,!\)\]@]|$)/.test(frameError.message.toLowerCase())) { isSandboxed = true; } } } _flashState.sandboxed = isSandboxed; if (previousState !== isSandboxed && !doNotReassessFlashSupport) { _detectFlashSupport(_ActiveXObject); } return isSandboxed; }; /** * Detect the Flash Player status, version, and plugin type. * * @see {@link https://code.google.com/p/doctype-mirror/wiki/ArticleDetectFlash#The_code} * @see {@link http://stackoverflow.com/questions/12866060/detecting-pepper-ppapi-flash-with-javascript} * * @returns `undefined` * @private */ var _detectFlashSupport = function(ActiveXObject) { var plugin, ax, mimeType, hasFlash = false, isActiveX = false, isPPAPI = false, flashVersion = ""; /** * Derived from Apple's suggested sniffer. * @param {String} desc e.g. "Shockwave Flash 7.0 r61" * @returns {String} "7.0.61" * @private */ function parseFlashVersion(desc) { var matches = desc.match(/[\d]+/g); matches.length = 3; return matches.join("."); } function isPepperFlash(flashPlayerFileName) { return !!flashPlayerFileName && (flashPlayerFileName = flashPlayerFileName.toLowerCase()) && (/^(pepflashplayer\.dll|libpepflashplayer\.so|pepperflashplayer\.plugin)$/.test(flashPlayerFileName) || flashPlayerFileName.slice(-13) === "chrome.plugin"); } function inspectPlugin(plugin) { if (plugin) { hasFlash = true; if (plugin.version) { flashVersion = parseFlashVersion(plugin.version); } if (!flashVersion && plugin.description) { flashVersion = parseFlashVersion(plugin.description); } if (plugin.filename) { isPPAPI = isPepperFlash(plugin.filename); } } } if (_navigator.plugins && _navigator.plugins.length) { plugin = _navigator.plugins["Shockwave Flash"]; inspectPlugin(plugin); if (_navigator.plugins["Shockwave Flash 2.0"]) { hasFlash = true; flashVersion = "2.0.0.11"; } } else if (_navigator.mimeTypes && _navigator.mimeTypes.length) { mimeType = _navigator.mimeTypes["application/x-shockwave-flash"]; plugin = mimeType && mimeType.enabledPlugin; inspectPlugin(plugin); } else if (typeof ActiveXObject !== "undefined") { isActiveX = true; try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e1) { try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); hasFlash = true; flashVersion = "6.0.21"; } catch (e2) { try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e3) { isActiveX = false; } } } } _flashState.disabled = hasFlash !== true; _flashState.outdated = flashVersion && _parseFloat(flashVersion) < _parseFloat(_minimumFlashVersion); _flashState.version = flashVersion || "0.0.0"; _flashState.pluginType = isPPAPI ? "pepper" : isActiveX ? "activex" : hasFlash ? "netscape" : "unknown"; }; /** * Invoke the Flash detection algorithms immediately upon inclusion so we're not waiting later. */ _detectFlashSupport(_ActiveXObject); /** * Always assess the `sandboxed` state of the page at important Flash-related moments. */ _detectSandbox(true); /** * A shell constructor for `ZeroClipboard` client instances. * * @constructor */ var ZeroClipboard = function() { if (!(this instanceof ZeroClipboard)) { return new ZeroClipboard(); } if (typeof ZeroClipboard._createClient === "function") { ZeroClipboard._createClient.apply(this, _args(arguments)); } }; /** * The ZeroClipboard library's version number. * * @static * @readonly * @property {string} */ _defineProperty(ZeroClipboard, "version", { value: "2.2.0", writable: false, configurable: true, enumerable: true }); /** * Update or get a copy of the ZeroClipboard global configuration. * Returns a copy of the current/updated configuration. * * @returns Object * @static */ ZeroClipboard.config = function() { return _config.apply(this, _args(arguments)); }; /** * Diagnostic method that describes the state of the browser, Flash Player, and ZeroClipboard. * * @returns Object * @static */ ZeroClipboard.state = function() { return _state.apply(this, _args(arguments)); }; /** * Check if Flash is unusable for any reason: disabled, outdated, deactivated, etc. * * @returns Boolean * @static */ ZeroClipboard.isFlashUnusable = function() { return _isFlashUnusable.apply(this, _args(arguments)); }; /** * Register an event listener. * * @returns `ZeroClipboard` * @static */ ZeroClipboard.on = function() { return _on.apply(this, _args(arguments)); }; /** * Unregister an event listener. * If no `listener` function/object is provided, it will unregister all listeners for the provided `eventType`. * If no `eventType` is provided, it will unregister all listeners for every event type. * * @returns `ZeroClipboard` * @static */ ZeroClipboard.off = function() { return _off.apply(this, _args(arguments)); }; /** * Retrieve event listeners for an `eventType`. * If no `eventType` is provided, it will retrieve all listeners for every event type. * * @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null` */ ZeroClipboard.handlers = function() { return _listeners.apply(this, _args(arguments)); }; /** * Event emission receiver from the Flash object, forwarding to any registered JavaScript event listeners. * * @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`. * @static */ ZeroClipboard.emit = function() { return _emit.apply(this, _args(arguments)); }; /** * Create and embed the Flash object. * * @returns The Flash object * @static */ ZeroClipboard.create = function() { return _create.apply(this, _args(arguments)); }; /** * Self-destruct and clean up everything, including the embedded Flash object. * * @returns `undefined` * @static */ ZeroClipboard.destroy = function() { return _destroy.apply(this, _args(arguments)); }; /** * Set the pending data for clipboard injection. * * @returns `undefined` * @static */ ZeroClipboard.setData = function() { return _setData.apply(this, _args(arguments)); }; /** * Clear the pending data for clipboard injection. * If no `format` is provided, all pending data formats will be cleared. * * @returns `undefined` * @static */ ZeroClipboard.clearData = function() { return _clearData.apply(this, _args(arguments)); }; /** * Get a copy of the pending data for clipboard injection. * If no `format` is provided, a copy of ALL pending data formats will be returned. * * @returns `String` or `Object` * @static */ ZeroClipboard.getData = function() { return _getData.apply(this, _args(arguments)); }; /** * Sets the current HTML object that the Flash object should overlay. This will put the global * Flash object on top of the current element; depending on the setup, this may also set the * pending clipboard text data as well as the Flash object's wrapping element's title attribute * based on the underlying HTML element and ZeroClipboard configuration. * * @returns `undefined` * @static */ ZeroClipboard.focus = ZeroClipboard.activate = function() { return _focus.apply(this, _args(arguments)); }; /** * Un-overlays the Flash object. This will put the global Flash object off-screen; depending on * the setup, this may also unset the Flash object's wrapping element's title attribute based on * the underlying HTML element and ZeroClipboard configuration. * * @returns `undefined` * @static */ ZeroClipboard.blur = ZeroClipboard.deactivate = function() { return _blur.apply(this, _args(arguments)); }; /** * Returns the currently focused/"activated" HTML element that the Flash object is wrapping. * * @returns `HTMLElement` or `null` * @static */ ZeroClipboard.activeElement = function() { return _activeElement.apply(this, _args(arguments)); }; /** * Keep track of the ZeroClipboard client instance counter. */ var _clientIdCounter = 0; /** * Keep track of the state of the client instances. * * Entry structure: * _clientMeta[client.id] = { * instance: client, * elements: [], * handlers: {} * }; */ var _clientMeta = {}; /** * Keep track of the ZeroClipboard clipped elements counter. */ var _elementIdCounter = 0; /** * Keep track of the state of the clipped element relationships to clients. * * Entry structure: * _elementMeta[element.zcClippingId] = [client1.id, client2.id]; */ var _elementMeta = {}; /** * Keep track of the state of the mouse event handlers for clipped elements. * * Entry structure: * _mouseHandlers[element.zcClippingId] = { * mouseover: function(event) {}, * mouseout: function(event) {}, * mouseenter: function(event) {}, * mouseleave: function(event) {}, * mousemove: function(event) {} * }; */ var _mouseHandlers = {}; /** * Extending the ZeroClipboard configuration defaults for the Client module. */ _extend(_globalConfig, { autoActivate: true }); /** * The real constructor for `ZeroClipboard` client instances. * @private */ var _clientConstructor = function(elements) { var client = this; client.id = "" + _clientIdCounter++; _clientMeta[client.id] = { instance: client, elements: [], handlers: {} }; if (elements) { client.clip(elements); } ZeroClipboard.on("*", function(event) { return client.emit(event); }); ZeroClipboard.on("destroy", function() { client.destroy(); }); ZeroClipboard.create(); }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.on`. * @private */ var _clientOn = function(eventType, listener) { var i, len, events, added = {}, meta = _clientMeta[this.id], handlers = meta && meta.handlers; if (!meta) { throw new Error("Attempted to add new listener(s) to a destroyed ZeroClipboard client instance"); } if (typeof eventType === "string" && eventType) { events = eventType.toLowerCase().split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { this.on(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].replace(/^on/, ""); added[eventType] = true; if (!handlers[eventType]) { handlers[eventType] = []; } handlers[eventType].push(listener); } if (added.ready && _flashState.ready) { this.emit({ type: "ready", client: this }); } if (added.error) { for (i = 0, len = _flashStateErrorNames.length; i < len; i++) { if (_flashState[_flashStateErrorNames[i].replace(/^flash-/, "")]) { this.emit({ type: "error", name: _flashStateErrorNames[i], client: this }); break; } } if (_zcSwfVersion !== undefined && ZeroClipboard.version !== _zcSwfVersion) { this.emit({ type: "error", name: "version-mismatch", jsVersion: ZeroClipboard.version, swfVersion: _zcSwfVersion }); } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.off`. * @private */ var _clientOff = function(eventType, listener) { var i, len, foundIndex, events, perEventHandlers, meta = _clientMeta[this.id], handlers = meta && meta.handlers; if (!handlers) { return this; } if (arguments.length === 0) { events = _keys(handlers); } else if (typeof eventType === "string" && eventType) { events = eventType.split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { this.off(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].toLowerCase().replace(/^on/, ""); perEventHandlers = handlers[eventType]; if (perEventHandlers && perEventHandlers.length) { if (listener) { foundIndex = perEventHandlers.indexOf(listener); while (foundIndex !== -1) { perEventHandlers.splice(foundIndex, 1); foundIndex = perEventHandlers.indexOf(listener, foundIndex); } } else { perEventHandlers.length = 0; } } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.handlers`. * @private */ var _clientListeners = function(eventType) { var copy = null, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers; if (handlers) { if (typeof eventType === "string" && eventType) { copy = handlers[eventType] ? handlers[eventType].slice(0) : []; } else { copy = _deepCopy(handlers); } } return copy; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.emit`. * @private */ var _clientEmit = function(event) { if (_clientShouldEmit.call(this, event)) { if (typeof event === "object" && event && typeof event.type === "string" && event.type) { event = _extend({}, event); } var eventCopy = _extend({}, _createEvent(event), { client: this }); _clientDispatchCallbacks.call(this, eventCopy); } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.clip`. * @private */ var _clientClip = function(elements) { if (!_clientMeta[this.id]) { throw new Error("Attempted to clip element(s) to a destroyed ZeroClipboard client instance"); } elements = _prepClip(elements); for (var i = 0; i < elements.length; i++) { if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) { if (!elements[i].zcClippingId) { elements[i].zcClippingId = "zcClippingId_" + _elementIdCounter++; _elementMeta[elements[i].zcClippingId] = [ this.id ]; if (_globalConfig.autoActivate === true) { _addMouseHandlers(elements[i]); } } else if (_elementMeta[elements[i].zcClippingId].indexOf(this.id) === -1) { _elementMeta[elements[i].zcClippingId].push(this.id); } var clippedElements = _clientMeta[this.id] && _clientMeta[this.id].elements; if (clippedElements.indexOf(elements[i]) === -1) { clippedElements.push(elements[i]); } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.unclip`. * @private */ var _clientUnclip = function(elements) { var meta = _clientMeta[this.id]; if (!meta) { return this; } var clippedElements = meta.elements; var arrayIndex; if (typeof elements === "undefined") { elements = clippedElements.slice(0); } else { elements = _prepClip(elements); } for (var i = elements.length; i--; ) { if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) { arrayIndex = 0; while ((arrayIndex = clippedElements.indexOf(elements[i], arrayIndex)) !== -1) { clippedElements.splice(arrayIndex, 1); } var clientIds = _elementMeta[elements[i].zcClippingId]; if (clientIds) { arrayIndex = 0; while ((arrayIndex = clientIds.indexOf(this.id, arrayIndex)) !== -1) { clientIds.splice(arrayIndex, 1); } if (clientIds.length === 0) { if (_globalConfig.autoActivate === true) { _removeMouseHandlers(elements[i]); } delete elements[i].zcClippingId; } } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.elements`. * @private */ var _clientElements = function() { var meta = _clientMeta[this.id]; return meta && meta.elements ? meta.elements.slice(0) : []; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.destroy`. * @private */ var _clientDestroy = function() { if (!_clientMeta[this.id]) { return; } this.unclip(); this.off(); delete _clientMeta[this.id]; }; /** * Inspect an Event to see if the Client (`this`) should honor it for emission. * @private */ var _clientShouldEmit = function(event) { if (!(event && event.type)) { return false; } if (event.client && event.client !== this) { return false; } var meta = _clientMeta[this.id]; var clippedEls = meta && meta.elements; var hasClippedEls = !!clippedEls && clippedEls.length > 0; var goodTarget = !event.target || hasClippedEls && clippedEls.indexOf(event.target) !== -1; var goodRelTarget = event.relatedTarget && hasClippedEls && clippedEls.indexOf(event.relatedTarget) !== -1; var goodClient = event.client && event.client === this; if (!meta || !(goodTarget || goodRelTarget || goodClient)) { return false; } return true; }; /** * Handle the actual dispatching of events to a client instance. * * @returns `undefined` * @private */ var _clientDispatchCallbacks = function(event) { var meta = _clientMeta[this.id]; if (!(typeof event === "object" && event && event.type && meta)) { return; } var async = _shouldPerformAsync(event); var wildcardTypeHandlers = meta && meta.handlers["*"] || []; var specificTypeHandlers = meta && meta.handlers[event.type] || []; var handlers = wildcardTypeHandlers.concat(specificTypeHandlers); if (handlers && handlers.length) { var i, len, func, context, eventCopy, originalContext = this; for (i = 0, len = handlers.length; i < len; i++) { func = handlers[i]; context = originalContext; if (typeof func === "string" && typeof _window[func] === "function") { func = _window[func]; } if (typeof func === "object" && func && typeof func.handleEvent === "function") { context = func; func = func.handleEvent; } if (typeof func === "function") { eventCopy = _extend({}, event); _dispatchCallback(func, context, [ eventCopy ], async); } } } }; /** * Prepares the elements for clipping/unclipping. * * @returns An Array of elements. * @private */ var _prepClip = function(elements) { if (typeof elements === "string") { elements = []; } return typeof elements.length !== "number" ? [ elements ] : elements; }; /** * Add a `mouseover` handler function for a clipped element. * * @returns `undefined` * @private */ var _addMouseHandlers = function(element) { if (!(element && element.nodeType === 1)) { return; } var _suppressMouseEvents = function(event) { if (!(event || (event = _window.event))) { return; } if (event._source !== "js") { event.stopImmediatePropagation(); event.preventDefault(); } delete event._source; }; var _elementMouseOver = function(event) { if (!(event || (event = _window.event))) { return; } _suppressMouseEvents(event); ZeroClipboard.focus(element); }; element.addEventListener("mouseover", _elementMouseOver, false); element.addEventListener("mouseout", _suppressMouseEvents, false); element.addEventListener("mouseenter", _suppressMouseEvents, false); element.addEventListener("mouseleave", _suppressMouseEvents, false); element.addEventListener("mousemove", _suppressMouseEvents, false); _mouseHandlers[element.zcClippingId] = { mouseover: _elementMouseOver, mouseout: _suppressMouseEvents, mouseenter: _suppressMouseEvents, mouseleave: _suppressMouseEvents, mousemove: _suppressMouseEvents }; }; /** * Remove a `mouseover` handler function for a clipped element. * * @returns `undefined` * @private */ var _removeMouseHandlers = function(element) { if (!(element && element.nodeType === 1)) { return; } var mouseHandlers = _mouseHandlers[element.zcClippingId]; if (!(typeof mouseHandlers === "object" && mouseHandlers)) { return; } var key, val, mouseEvents = [ "move", "leave", "enter", "out", "over" ]; for (var i = 0, len = mouseEvents.length; i < len; i++) { key = "mouse" + mouseEvents[i]; val = mouseHandlers[key]; if (typeof val === "function") { element.removeEventListener(key, val, false); } } delete _mouseHandlers[element.zcClippingId]; }; /** * Creates a new ZeroClipboard client instance. * Optionally, auto-`clip` an element or collection of elements. * * @constructor */ ZeroClipboard._createClient = function() { _clientConstructor.apply(this, _args(arguments)); }; /** * Register an event listener to the client. * * @returns `this` */ ZeroClipboard.prototype.on = function() { return _clientOn.apply(this, _args(arguments)); }; /** * Unregister an event handler from the client. * If no `listener` function/object is provided, it will unregister all handlers for the provided `eventType`. * If no `eventType` is provided, it will unregister all handlers for every event type. * * @returns `this` */ ZeroClipboard.prototype.off = function() { return _clientOff.apply(this, _args(arguments)); }; /** * Retrieve event listeners for an `eventType` from the client. * If no `eventType` is provided, it will retrieve all listeners for every event type. * * @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null` */ ZeroClipboard.prototype.handlers = function() { return _clientListeners.apply(this, _args(arguments)); }; /** * Event emission receiver from the Flash object for this client's registered JavaScript event listeners. * * @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`. */ ZeroClipboard.prototype.emit = function() { return _clientEmit.apply(this, _args(arguments)); }; /** * Register clipboard actions for new element(s) to the client. * * @returns `this` */ ZeroClipboard.prototype.clip = function() { return _clientClip.apply(this, _args(arguments)); }; /** * Unregister the clipboard actions of previously registered element(s) on the page. * If no elements are provided, ALL registered elements will be unregistered. * * @returns `this` */ ZeroClipboard.prototype.unclip = function() { return _clientUnclip.apply(this, _args(arguments)); }; /** * Get all of the elements to which this client is clipped. * * @returns array of clipped elements */ ZeroClipboard.prototype.elements = function() { return _clientElements.apply(this, _args(arguments)); }; /** * Self-destruct and clean up everything for a single client. * This will NOT destroy the embedded Flash object. * * @returns `undefined` */ ZeroClipboard.prototype.destroy = function() { return _clientDestroy.apply(this, _args(arguments)); }; /** * Stores the pending plain text to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setText = function(text) { if (!_clientMeta[this.id]) { throw new Error("Attempted to set pending clipboard data from a destroyed ZeroClipboard client instance"); } ZeroClipboard.setData("text/plain", text); return this; }; /** * Stores the pending HTML text to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setHtml = function(html) { if (!_clientMeta[this.id]) { throw new Error("Attempted to set pending clipboard data from a destroyed ZeroClipboard client instance"); } ZeroClipboard.setData("text/html", html); return this; }; /** * Stores the pending rich text (RTF) to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setRichText = function(richText) { if (!_clientMeta[this.id]) { throw new Error("Attempted to set pending clipboard data from a destroyed ZeroClipboard client instance"); } ZeroClipboard.setData("application/rtf", richText); return this; }; /** * Stores the pending data to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setData = function() { if (!_clientMeta[this.id]) { throw new Error("Attempted to set pending clipboard data from a destroyed ZeroClipboard client instance"); } ZeroClipboard.setData.apply(this, _args(arguments)); return this; }; /** * Clears the pending data to inject into the clipboard. * If no `format` is provided, all pending data formats will be cleared. * * @returns `this` */ ZeroClipboard.prototype.clearData = function() { if (!_clientMeta[this.id]) { throw new Error("Attempted to clear pending clipboard data from a destroyed ZeroClipboard client instance"); } ZeroClipboard.clearData.apply(this, _args(arguments)); return this; }; /** * Gets a copy of the pending data to inject into the clipboard. * If no `format` is provided, a copy of ALL pending data formats will be returned. * * @returns `String` or `Object` */ ZeroClipboard.prototype.getData = function() { if (!_clientMeta[this.id]) { throw new Error("Attempted to get pending clipboard data from a destroyed ZeroClipboard client instance"); } return ZeroClipboard.getData.apply(this, _args(arguments)); }; if (typeof define === "function" && define.amd) { define(function() { return ZeroClipboard; }); } else if (typeof module === "object" && module && typeof module.exports === "object" && module.exports) { module.exports = ZeroClipboard; } else { window.ZeroClipboard = ZeroClipboard; } })(function() { return this || window; }()); },{}]},{},[30,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,91,92,93,78,79,80,81,82,83,38,42,47,39,40,41,43,44,45,46]);
web/assets/js/homepage/CarGallery.js
xuqiantong/NY_Auto
import React from 'react'; import ReactDOM from 'react-dom'; import CarFilter from './CarFilter.js'; var Filter = require('react-filter'); function CarName(props) { const make = props.name.vehicle_make; const year = props.name.vehicle_year; const model = props.name.vehicle_model; var trim = props.name.vehicle_trim; if (trim == "" || trim == "-") trim = ""; return ( <div className="car-name"> {year} {make} {model} {trim} </div> ); } function ColorCircle(props) { return ( <div className="car-color-circle"> <svg height="25" width="25"> <circle cx="13" cy="13" r="10" stroke="black" fill={props.color}/> </svg> </div> ); } function CarColor(props) { const ext_color = props.color.vehicle_color_ext; const int_color = props.color.vehicle_color_int; return ( <div className="car-color"> <div className="ext-color"> Exterior Color: <ColorCircle color={ext_color} /> </div> <div className="int-color"> Interior Color: <ColorCircle color={int_color} /> </div> </div> ); } function CarEquip(props) { const equips = props.equips.vehicle_equipment; return ( <div className="car-equips"> {equips} and more... </div> ); } function Image(props) { return ( <div className={props.class}> <a href={"/detail" + props.id} ><img src={props.path} alt="./images/carAlt.png" width={props.width} height={props.height} /> </a> </div> ); } function Car(props) { const car = props.car; console.log(car); const bgImage = car.image_path; const itemStyle = { backgroundImage: "url(" + bgImage + ")", backgroundSize: "cover", backgroundPositionY: "50%", backgroundPositionX: "50%" }; return ( <div className="car-display"> <a className="car-display-a" href={"/detail" + car.vehicle_id}> <div className="col-md-6 col-md-push-1 col-sm-10 col-sm-push-1 col-xs-10 col-xs-push-1 car-img-wrapper" id={car.vehicle_id} style={itemStyle}></div> <div className="col-md-5 col-md-push-1 col-sm-10 col-sm-push-1 col-xs-10 col-xs-push-1 "> <CarName name={car}/> <div className="car-mile"> {car.vehicle_mileage} miles </div> <div className="car-price"> $ {car.vehicle_list_price} </div> <CarColor color={car}/> <CarEquip equips={car}/> </div> </a> </div> ); } function LoadMore(props) { return ( <div className="loadmore"> <a className="loadmore" href="/buy">Load More</a> </div> ); } //get data from database and filter var CarGallery = React.createClass({ loadCarsFromServer: function(){ $.ajax({ url: this.props.url1, datatype: 'json', cache: false, success: function(vehicle_image) { this.setState({vehicle_image: vehicle_image}); }.bind(this) }) $.ajax({ url: this.props.url2, datatype: 'json', cache: false, success: function(vehicles) { this.setState({vehicles: vehicles}); }.bind(this) }) }, getInitialState: function() { return { vehicle_image: [], vehicles: [], searchKeys: [] }; }, componentDidMount: function() { this.loadCarsFromServer(); }, render: function() { var vehicles = []; var filterlist = []; var count = 0; var vehicle_images = this.state.vehicle_image; if (this.state.vehicles && this.state.vehicle_image) { vehicles = this.state.vehicles.map(function(car){ var id = car.id; var equip_count = 0; var equips = ""; if (car.eb_Power_Mirrors){ if (equip_count < 3){ equips = equips.concat("Power Mirrors/ "); equip_count++; } } if (car.eb_Power_Windows){ if (equip_count < 3){ equips = equips.concat("Power Windows/ "); equip_count++; } } if (car.eb_Traction_Control){ if (equip_count < 3){ equips = equips.concat("Traction Control/ "); equip_count++; } } if (car.eb_Stability_Control){ if (equip_count < 3){ equips = equips.concat("Stability Control/ "); equip_count++; } } if (car.eb_Cruise_Control){ if (equip_count < 3){ equips = equips.concat("Cruise Control/ "); equip_count++; } } if (car.eb_Security_System){ if (equip_count < 3){ equips = equips.concat("Security System/ "); equip_count++; } } if (car.eb_Tire_Pressure_Monitoring_System){ if (equip_count < 3){ equips = equips.concat("Tire Pressure Monitoring System/ "); equip_count++; } } if (car.eb_Radio_CD_Player){ if (equip_count < 3){ equips = equips.concat("Radio CD Player/ "); equip_count++; } } if (car.eb_AUX){ if (equip_count < 3){ equips = equips.concat("AUX/ "); equip_count++; } } if (car.eb_USB){ if (equip_count < 3){ equips = equips.concat("USB/ "); equip_count++; } } if (car.eb_Steering_Wheel_Audio_Control){ if (equip_count < 3){ equips = equips.concat("Steering Wheel Audio Control/ "); equip_count++; } } if (car.eb_AntiLock_Brake_System){ if (equip_count < 3){ equips = equips.concat("AntiLock Brake System/ "); equip_count++; } } if (car.eb_AC){ if (equip_count < 3){ equips = equips.concat("eb_AC/ "); equip_count++; } } if (car.es_Universal_Garage_Opener){ if (equip_count < 3){ equips = equips.concat("Universal Garage Opener/ "); equip_count++; } } if (car.es_Power_Seats_Driver){ if (equip_count < 3){ equips = equips.concat("Power Seats Driver/ "); equip_count++; } } if (car.es_Power_Seats_Both){ if (equip_count < 3){ equips = equips.concat("Power_Seats_Both/ "); equip_count++; } } if (car.es_Rain_Sensing_Wiper){ if (equip_count < 3){ equips = equips.concat("Rain Sensing Wiper/ "); equip_count++; } } if (car.es_Back_Up_Camera){ if (equip_count < 3){ equips = equips.concat("Back Up Camera/ "); equip_count++; } } if (car.es_Parking_Sensor){ if (equip_count < 3){ equips = equips.concat("Parking Sensor/ "); equip_count++; } } if (car.es_Sunroof){ if (equip_count < 3){ equips = equips.concat("Sunroof/ "); equip_count++; } } if (car.es_All_Weather_Floor_Mats){ if (equip_count < 3){ equips = equips.concat("All Weather Floor Mats/ "); equip_count++; } } if (car.es_Automatic_Headlights){ if (equip_count < 3){ equips = equips.concat("Automatic Headlights/ "); equip_count++; } } if (car.es_Daytime_Running_Lights){ if (equip_count < 3){ equips = equips.concat("Daytime Running Lights/ "); equip_count++; } } if (car.es_Tilt_Steering_Wheel){ if (equip_count < 3){ equips = equips.concat("Tilt Steering Wheel/ "); equip_count++; } } if (car.es_Navigation_GPS){ if (equip_count < 3){ equips = equips.concat("Navigation GPS/ "); equip_count++; } } if (car.es_Dual_Climate_Control){ if (equip_count < 3){ equips = equips.concat("Dual Climate Control/ "); equip_count++; } } if (car.ep_Heads_Up_Display){ if (equip_count < 3){ equips = equips.concat("Heads Up Display/ "); equip_count++; } } if (car.ep_Heated_Seats_Front){ if (equip_count < 3){ equips = equips.concat("Heated Seats Front/ "); equip_count++; } } if (car.ep_Heated_Seats_Rear){ if (equip_count < 3){ equips = equips.concat("Heated Seats Rear/ "); equip_count++; } } if (car.ep_Cooled_Seats_Front){ if (equip_count < 3){ equips = equips.concat("Cooled Seats Front/ "); equip_count++; } } if (car.ep_Cooled_Seats_Rear){ if (equip_count < 3){ equips = equips.concat("Cooled Seats Rear/ "); equip_count++; } } if (car.ep_Lane_Departure_System){ if (equip_count < 3){ equips = equips.concat("Lane Departure System/ "); equip_count++; } } if (car.ep_Keyless_Entry){ if (equip_count < 3){ equips = equips.concat("Keyless Entry/ "); equip_count++; } } if (car.ep_Keyless_Start){ if (equip_count < 3){ equips = equips.concat("Keyless Start/ "); equip_count++; } } if (car.ep_Rear_Spoiler){ if (equip_count < 3){ equips = equips.concat("Rear Spoiler/ "); equip_count++; } } if (car.ep_Heated_Steering_Wheel){ if (equip_count < 3){ equips = equips.concat("Heated Steering Wheel/ "); equip_count++; } } if (car.ep_Panorama_Sunroof){ if (equip_count < 3){ equips = equips.concat("Panorama Sunroof/ "); equip_count++; } } if (car.ep_Night_Vision){ if (equip_count < 3){ equips = equips.concat("Night Vision/ "); equip_count++; } } if (car.ep_Premium_Stereo){ if (equip_count < 3){ equips = equips.concat("Premium Stereo/ "); equip_count++; } } var path; vehicle_images.map(function(rela){ if (id == rela.vehicle) { count++; path = rela.image; } }); return { vehicle_id: id, id: count, vehicle_year: car.year, vehicle_list_price: car.list_price, vehicle_equipment: equips, image_path: path, vehicle_style: car.body_type, vehicle_trim: car.trim, vehicle_color_int: car.color_int, vehicle_color_ext: car.color_ext, vehicle_mileage: car.mileage, vehicle_model: car.model, vehicle_drive: car.drive, vehicle_make: car.make, } }) if (this.state.searchKeys.length > 0) { var keys = this.state.searchKeys; vehicles.map(function(car){ if(keys[0]=="make"|| !(keys.indexOf(car.vehicle_make) === -1)) { if(keys[1]=="style" || !(keys.indexOf(car.vehicle_style) === -1)) { var year = car.vehicle_year; var inYearrange = 0; if(!(keys.indexOf("after2015") === -1)) { if(year >= 2015) { inYearrange = 1; } } else if(!(keys.indexOf("after2010") === -1)) { if(year >= 2010 && year < 2015) { inYearrange = 1; } } else if(!(keys.indexOf("after2005") === -1)) { if(year >= 2005 && year < 2010) { inYearrange = 1; } } else if(!(keys.indexOf("after2000") === -1)) { if(year >= 2000 && year < 2005) { inYearrange = 1; } } else if(!(keys.indexOf("after1990") === -1)) { if(year >= 1990 && year < 2000) { inYearrange = 1; } } if(keys[2]=="year"|| inYearrange == 1) { var mile = car.vehicle_mileage; var inMilerange = 0; if(!(keys.indexOf("lessthan10k") === -1)) { if(mile < 10000) { inMilerange = 1; } } else if(!(keys.indexOf("lessthan40k") === -1)) { if(mile >= 10000 && mile < 40000) { inMilerange = 1; } } else if(!(keys.indexOf("lessthan70k") === -1)) { if(mile >= 40000 && mile < 70000) { inMilerange = 1; } } else if(!(keys.indexOf("lessthan100k") === -1)) { if(mile >= 70000 && mile < 100000) { inMilerange = 1; } } else if(!(keys.indexOf("lessthan40k") === -1)) { if(mile >= 100000 && mile < 150000) { inMilerange = 1; } } if(keys[3]=="mileage"|| inMilerange == 1) { var price = car.vehicle_list_price; var inPricerange = 0; if(!(keys.indexOf("$less10k") === -1)) { if(price < 10000) { inPricerange = 1; } } else if(!(keys.indexOf("$less20k") === -1)) { if(price >= 10000 && price < 20000) { inPricerange = 1; } } else if(!(keys.indexOf("$less35k") === -1)) { if(price >= 20000 && price < 35000) { inPricerange = 1; } } else if(!(keys.indexOf("$less50k") === -1)) { if(price >= 35000 && price < 50000) { inPricerange = 1; } } else if(!(keys.indexOf("$less100k") === -1)) { if(price >= 50000 && price < 100000) { inPricerange = 1; } } else if(!(keys.indexOf("$less150k") === -1)) { if(price >= 100000 && price < 150000) { inPricerange = 1; } } if (keys[4]=="price"|| inPricerange == 1) { filterlist.push(car); } } } } } }); if (keys[5] !="sort") { if (!(keys.indexOf("byprice") === -1)) { filterlist.sort(function(a, b) {return a.vehicle_list_price - b.vehicle_list_price;}) } if (!(keys.indexOf("byyear") === -1)) { filterlist.sort(function(a, b) {return b.vehicle_year - a.vehicle_year;}) } if (!(keys.indexOf("bymileage") === -1)) { filterlist.sort(function(a, b) {return a.vehicle_mileage - b.vehicle_mileage;}) } } vehicles = filterlist; } var list = []; vehicles.map(function(car){ if(car.image_path) { list.push(car); } }) vehicles = list; var carList = vehicles.map(function(car){ return ( <div key={car.id} className="col-lg-6"> <Car car={car}/> </div> ) }); } return( <div className="car-display"> <CarFilter onUpdate={this.onUpdate} /> <div className="row"> {carList} </div> <LoadMore /> </div> ); }, onUpdate(searchKeys) { this.setState({searchKeys}) } }); export default CarGallery;